问:
How do I convert this to a Point-free function

import { chain, map, Apply } from "fp-ts/lib/IO";
import { log } from "fp-ts/lib/Console";
import { pipe } from "fp-ts/lib/function";
import * as D from "fp-ts/lib/Date";
import { sequenceT } from "fp-ts/lib/Apply";
import { v4 as uuidv4 } from "uuid";

export const Article = (title: string) =>
  ([id, now]: [string, Date]) => ({
    id,
    title,
    createdAt: now
  });

const createArticle = (title: string) =>
  pipe(sequenceT(Apply)(uuidv4, D.create), map(Article(title)));

const program = pipe(
  createArticle("hello"),
  chain(log)
);

program();

```

In the example above since Article requires 2 params that are side-effects. The question is on createArticle and if that could be written as a point free function.

答:
You can do the piping in reverse by applying the values to the function using ap. I had to create a function that helps TypeScript figure out the type of of.

import { chain, map, Apply, of, ap } from "fp-ts/lib/IO";
import { log } from "fp-ts/lib/Console";
import { flow, pipe } from "fp-ts/lib/function";
import * as D from "fp-ts/lib/Date";
import { sequenceT } from "fp-ts/lib/Apply";
import { v4 as uuidv4 } from "uuid";

const Article =
  (title: string) =>
  ([id, now]: [string, Date]) => ({
    id,
    title,
    createdAt: now,
  });

const ofString = (str: string) => of(str);

const createArticle = flow(
  ofString,
  map(Article),
  ap(sequenceT(Apply)(uuidv4, D.create))
);

const program = pipe(createArticle("hello"), chain(log));

program();
```

Body:
import { chain, map, Apply } from "fp-ts/lib/IO";
import { log } from "fp-ts/lib/Console";
import { pipe } from "fp-ts/lib/function";
import * as D from "fp-ts/lib/Date";
import { sequenceT } from "fp-ts/lib/Apply";
import { v4 as uuidv4 } from "uuid";

export const Article = (title: string) =>
  ([id, now]: [string, Date]) => ({
    id,
    title,
    createdAt: now
  });

const createArticle = (title: string) =>
  pipe(sequenceT(Apply)(uuidv4, D.create), map(Article(title)));

const program = pipe(
  createArticle("hello"),
  chain(log)
);

program();

In the example above since Article requires 2 params that are side-effects. The question is on createArticle and if that could be written as a point free function.


来源: stackexchange

问:
How to open an App from a link in email?
I have to open my App from a link in email .that is when registering in my App,i got a mail contains a link something like: click for open your app.so when i click the link from my mobile browser i need  the app  Launched.Is there any solution for this?

答:
AFAIK is not possible atm. Unless you use a push notification.
This should help

Push Notifications for Windows Phone
How to: Set Up a Notification Channel for Windows Phone
How to: Send a Push Notification for Windows Phone

ContentLicense: CC BY-SA 3.0


问:
Find by key deep in a nested array
Let's say I have an object:

```<code>[
    {
        'title': "some title"
        'channel_id':'123we'
        'options': [
                    {
                'channel_id':'abc'
                'image':'http://asdasd.com/all-inclusive-block-img.jpg'
                'title':'All-Inclusive'
                'options':[
                    {
                        'channel_id':'dsa2'
                        'title':'Some Recommends'
                        'options':[
                            {
                                'image':'http://www.asdasd.com'                                 'title':'Sandals'
                                'id':'1'
                                'content':{
                                     ...
</code>```

I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore's _.filter method, but I would have to start at the top and filter down.

答:
Found the answer I was looking for, especially Ali Alnoaimi's solution. I made some small adjustments to allow for the search of the value as well

```<code>function deepSearchByKey(object, originalKey, originalValue, matches = []) {
if (object != null) {
  if (Array.isArray(object)) {
    for (let arrayItem of object) {
      deepSearchByKey(arrayItem, originalKey, originalValue, matches);
    }
  } else if (typeof object == 'object') {
    for (let key of Object.keys(object)) {
      if (key == originalKey) {
        if (object[key] == originalValue) {
          matches.push(object);
        }
      } else {
        deepSearchByKey(object[key], originalKey, originalValue, matches);
      }
    }
  }
}

return matches;
}
</code>```

To use:

```<code>let result = deepSearchByKey(arrayOrObject, 'key', 'value');
</code>```

This will return the object containing the matching key and value.

ContentLicense: CC BY-SA 4.0

Title: Find by key deep in a nested array

Body:
Let's say I have an object:

[
    {
        'title': "some title"
        'channel_id':'123we'
        'options': [
                    {
                'channel_id':'abc'
                'image':'http://asdasd.com/all-inclusive-block-img.jpg'
                'title':'All-Inclusive'
                'options':[
                    {
                        'channel_id':'dsa2'
                        'title':'Some Recommends'
                        'options':[
                            {
                                'image':'http://www.asdasd.com'                                 'title':'Sandals'
                                'id':'1'
                                'content':{
                                     ...

I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore's _.filter method, but I would have to start at the top and filter down.

Body:
Found the answer I was looking for, especially Ali Alnoaimi's solution. I made some small adjustments to allow for the search of the value as well

function deepSearchByKey(object, originalKey, originalValue, matches = []) {
if (object != null) {
  if (Array.isArray(object)) {
    for (let arrayItem of object) {
      deepSearchByKey(arrayItem, originalKey, originalValue, matches);
    }
  } else if (typeof object == 'object') {
    for (let key of Object.keys(object)) {
      if (key == originalKey) {
        if (object[key] == originalValue) {
          matches.push(object);
        }
      } else {
        deepSearchByKey(object[key], originalKey, originalValue, matches);
      }
    }
  }
}

return matches;
}

To use:

let result = deepSearchByKey(arrayOrObject, 'key', 'value');

This will return the object containing the matching key and value.


问:
After groupby, create a Series from the smallest values in one column corresponding to a value in another column
I have some data like this:

```<code>df = pd.DataFrame({'x':[1,2,3,1,1,2,3,3,2],
                   'y':['n', 'n', 'p', 'p', 'n', 'n', 'n', 'p', 'n'],
                   'z':[52,75,77,68,92,32,62,70,34]})
</code>```

I'd like to first group it by x, and then check if p exists in any of the rows of each group, and add another column to the original dataframe (or to the grouped one, and then somehow flatten it back out?) that has either None if there were no p's in that group, or the smallest number corresponding to p from the z column.

So here it'd be:

```<code>   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68

   x  y   z  t
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None

   x  y   z  t
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70
</code>```

or flattened:

```<code>   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70
</code>```

So first we'd do

```<code>g = df.groupby('x')
</code>```

But then I'm not sure how to proceed.
I'm just having a hard time wrapping my head around it and running into all sorts of pandas error.

答:
@HenryEcker covered all the nice intuitive solutions. This one's just for fun.

The basic idea is filter the rows where "y" is 'p' and among these rows find the minimum value of "z" for each "x". Then map it back to "x":

```<code>df['t'] = df['x'].map(df[df['y'].eq('p')].groupby('x')['z'].min())
df = df.sort_values(by='x')
</code>```

An alternative method using eq + where. The basic idea is to mask the "z" values corresponding to non-"p"  values in column "y"; then groupby "x" and transform the minimum "z":

```<code>df['t'] = df['z'].where(df['y'].eq('p')).groupby(df['x']).transform('min')
</code>```

Output:

```<code>   x  y   z     t
0  1  n  52  68.0
3  1  p  68  68.0
4  1  n  92  68.0
1  2  n  75   NaN
5  2  n  32   NaN
8  2  n  34   NaN
2  3  p  77  70.0
6  3  n  62  70.0
7  3  p  70  70.0
</code>```

Body:
I have some data like this:

df = pd.DataFrame({'x':[1,2,3,1,1,2,3,3,2],
                   'y':['n', 'n', 'p', 'p', 'n', 'n', 'n', 'p', 'n'],
                   'z':[52,75,77,68,92,32,62,70,34]})

I'd like to first group it by x, and then check if p exists in any of the rows of each group, and add another column to the original dataframe (or to the grouped one, and then somehow flatten it back out?) that has either None if there were no p's in that group, or the smallest number corresponding to p from the z column.

So here it'd be:

   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68

   x  y   z  t
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None

   x  y   z  t
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70

or flattened:

   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70

So first we'd do

g = df.groupby('x')

But then I'm not sure how to proceed.
I'm just having a hard time wrapping my head around it and running into all sorts of pandas error.

Body:
@HenryEcker covered all the nice intuitive solutions. This one's just for fun.

The basic idea is filter the rows where "y" is 'p' and among these rows find the minimum value of "z" for each "x". Then map it back to "x":

df['t'] = df['x'].map(df[df['y'].eq('p')].groupby('x')['z'].min())
df = df.sort_values(by='x')

An alternative method using eq + where. The basic idea is to mask the "z" values corresponding to non-"p"  values in column "y"; then groupby "x" and transform the minimum "z":

df['t'] = df['z'].where(df['y'].eq('p')).groupby(df['x']).transform('min')

Output:

   x  y   z     t
0  1  n  52  68.0
3  1  p  68  68.0
4  1  n  92  68.0
1  2  n  75   NaN
5  2  n  32   NaN
8  2  n  34   NaN
2  3  p  77  70.0
6  3  n  62  70.0
7  3  p  70  70.0


问:
How do I check if a variable has gone up?
here is some code. I want to make an if statement but only when a variable has increased</p>
```<code>while True:
    a += 1

    if a ????
        print('a has changed')

</code>```

答:
Here is an option.</p>
```<code>while True:
    previous = a
    # do stuff
    a += 1

    if a != previous:
        print('a has changed')
</code>```

Body:
here is some code. I want to make an if statement but only when a variable has increased

while True:
    a += 1

    if a ????
        print('a has changed')

Body:
Here is an option.

while True:
    previous = a
    # do stuff
    a += 1

    if a != previous:
        print('a has changed')


问:
Silverlight datagrid twoway binding
I have datagrid in which one of the column is Textbox control, have set the binding as twoway. the grid is binded to a observable collection.
Issue : If I enter some value in text box, collection get populated. now if I clears that textbox the same has not been reflected to the collection. my binded property is nullable.

Thanks N Advance

答:
Check the Output window in Visual Studio for binding errors. You should see a warning that there is no implicit conversion from an empty string to an Integer.

You could use a ValueConverter to perform this task.

See this related question for other approaches. Note that some may not apply as the focus there is WPF.

WPF binding not working properly with properties of int type

Title: Silverlight datagrid twoway binding


问:
The border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?
I am trying to make a table with rounded corners using the CSS border-radius property. The table styles I'm using look something like this:

```<code>table {
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px
}
</code>```

Here's the problem. I also want to set the border-collapse:collapse property, and when that is set border-radius no longer works. Is there a CSS-based way I can get the same effect as border-collapse:collapse without actually using it?

It seems that a large part of the problem is that setting the table to have rounded corners does not affect the corners of the corner td elements. If the table was all one color, this wouldn't be a problem since I could just make the top and bottom td corners rounded for the first and last row respectively. However, I am using different background colors for the table to differentiate the headings and for striping, so the inner td elements would show their rounded corners as well.

Surrounding the table with another element with round corners doesn't work because the table's square corners "bleed through."

Specifying border width to 0 doesn't collapse the table.

Bottom td corners still square after setting cellspacing to zero.

The tables are generated in PHP, so I could just apply a different class to each of the outer th/tds and style each corner separately. I'd rather not do this, since it's not very elegant and a bit of a pain to apply to multiple tables, so please keep suggestions coming.

I'd like to do this without JavaScript.

答:
Use "overflow: hidden" with "border-radius"
This works with "collapse" table as well

Example:

border-radius: 1em;
overflow: hidden;

Body:
I am trying to make a table with rounded corners using the CSS border-radius property. The table styles I'm using look something like this:

table {
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px
}

Here's the problem. I also want to set the border-collapse:collapse property, and when that is set border-radius no longer works. Is there a CSS-based way I can get the same effect as border-collapse:collapse without actually using it?

It seems that a large part of the problem is that setting the table to have rounded corners does not affect the corners of the corner td elements. If the table was all one color, this wouldn't be a problem since I could just make the top and bottom td corners rounded for the first and last row respectively. However, I am using different background colors for the table to differentiate the headings and for striping, so the inner td elements would show their rounded corners as well.

Surrounding the table with another element with round corners doesn't work because the table's square corners "bleed through."

Specifying border width to 0 doesn't collapse the table.

Bottom td corners still square after setting cellspacing to zero.

The tables are generated in PHP, so I could just apply a different class to each of the outer th/tds and style each corner separately. I'd rather not do this, since it's not very elegant and a bit of a pain to apply to multiple tables, so please keep suggestions coming.

I'd like to do this without JavaScript.

LastEditorDisplayName: vamin


问:
Only one reducer is being recognized in my reducer tree/state in my redux dev tools
Hi I am new to redux and I'm having trouble seeing my entire tree of reducers, so far I only see the getTopGames reducer in my redux dev tools and I cant figure out why I can't see anything else like shop, and getGameDetails. Since I set up my store and combined all my reducers shouldn't I see all the reducer states in my devtools? (Ex. getTopGames, under that shop, under that getGameDetails)??? Thank you for any help and insight here is the github link https://github.com/andrewjkim745/Twitch-Store

答:
This is happening because in INITIAL_STATE you've only define getTopGames reducer.

That's why initially you can only see the getTopGames reducer in your redux dev tools. Add your other reducers shop and getGameDetails in INITIAL_STATE then you'll be able to see them initially in your redux dev tools. Even if you don't, once you start performing actions from other reducers, you can see them in your redux dev tools.


问:
Getting a "Type is not assignable to type FunctionComponent<Props>" and "Type is missing the following properties from type 'React Element<any, any>'
I'm trying to add TypeScript to my code but I'm constantly bumping into an error which I assume is related to my Props type or something. The whole error is this:

```<code>Type '({ volume, onload, isMuted, src, mediaType, ...config }: PropsWithChildren<Props>) => { howl: Howl | undefined; isMuted: boolean | undefined; volume: number; ready: boolean; pause: () => void; play: () => void; fade: (from: number, to: number, duration: number) => void; seek: () => number | undefined; duration: () =...' is not assignable to type 'FunctionComponent<Props>'.
Type '{ howl: Howl | undefined; isMuted: boolean | undefined; volume: number; ready: boolean; pause: () => void; play: () => void; fade: (from: number, to: number, duration: number) => void; seek: () => number | undefined; duration: () => number | undefined; }' is missing the following properties from type 'ReactElement<any, any>': type, props, keyts(2322)
</code>```

I am creating my Props type and then the parameters of my function is infered from the generic FunctionComponent. I have a suspicion that mapDispatchToProps might be the issue here somehow. My problem is that I can't deduce what the problem is from the error message.

```<code>import { useState, useEffect, useRef, FunctionComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { Howl } from 'howler';

import { getSignedMediaURL } from '../../services/meditations';
import { SetHasConnectivity } from 'src/store/user/actions';

const mapDispatchToProps = (dispatch: Dispatch) =>
    bindActionCreators({ SetHasConnectivity }, dispatch);

const noop = () => {};

type Props = {
    src: string | null;
    onload?: () => void;
    volume?: number;
    isMuted?: boolean;
    mediaType: 'soundscape' | 'meditation' | 'other';
    loop?: boolean;
    onend?: () => void;
    onstop?: () => void;
} & ReturnType<typeof mapDispatchToProps>;

const useMeditation: FunctionComponent<Props> = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }) => {
    const player = useRef<Howl>();
    const soundId = useRef<number>();

    const [ready, setReady] = useState(false);

    const onSoundLoad = () => {
        if (player.current) {
            player.current.volume(volume);
            setReady(true);
            onload();
        }
    };

    useEffect(() => {
        if (src) {
            (async function () {
                let url = src;

                if (mediaType === 'soundscape' || mediaType === 'meditation') {
                    try {
                        const response = await getSignedMediaURL(src, mediaType);
                        url = response.body.url;
                    } catch (error) {
                        console.log('Test');
                    }
                }

                player.current = new Howl({
                    src: [url],
                    html5: true,
                    volume: 0,
                    onload: onSoundLoad,
                    ...config,
                });
            })();
        } else {
            setReady(true);
        }

        return () => {
            if (player.current) {
                player.current.stop();
            }
        };
    }, []); // eslint-disable-line

    useEffect(() => {
        if (player.current) {
            player.current.volume(volume);
        }
    }, [volume]);

    useEffect(() => {
        if (player.current) {
            if (isMuted) {
                player.current.mute(true, soundId.current);
            } else {
                player.current.mute(false);
            }
        }
    }, [isMuted]);

    const pause = () => {
        if (player.current) {
            player.current.pause();
        }
    };

    const play = () => {
        if (player.current) {
            soundId.current = player.current.play();
        }
    };

    const fade = (from: number, to: number, duration: number) => {
        if (player.current) {
            if (!player.current.playing()) {
                play();
            }

            player.current.fade(from, to, duration, soundId.current);
        }
    };

    const seek = () => {
        if (player.current) {
            return player.current.seek();
        }

        return;
    };

    const duration = () => {
        if (player.current) {
            return player.current.duration();
        }

        return;
    };

    return {
        howl: player.current,
        isMuted,
        volume,
        ready,

        pause,
        play,
        fade,

        seek,
        duration,
    };
}

export connect(null, mapDispatchToProps)(useMeditation);
</code>```

答:
A React component must return a JSX Element (an HTML snippet, essentially) or null.  Your useMeditation is not a component -- it is a custom hook which returns an object.

This type annotation is incorrect:

```<code>const useMeditation: FunctionComponent<Props> = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }) => {
</code>```

It should be:

```<code>const useMeditation = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }: Props) => {
</code>```

You cannot use the connect higher-order component on a hook.  It can only be used on components.

You need to use the useDispatch hook instead.  I'm not seeing where you actually dispatch the action?  But it should look something like this.

```<code>// Same as before, but delete the `ReturnType<typeof mapDispatchToProps>`
type Props = { /* ... */ }

const useMeditation = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }: Props) => {

    // Get access to the dispatch function.
    const dispatch = useDispatch();

    // Dispatch your action.
    const someFunction = () => {
        dispatch(SetHasConnectivity(true));
    }

    /* ... rest of the hook ... */
}

// No need to use `connect` or anything else here, just export it.
export default useMeditation;
</code>```

Body:
I'm trying to add TypeScript to my code but I'm constantly bumping into an error which I assume is related to my Props type or something. The whole error is this:

Type '({ volume, onload, isMuted, src, mediaType, ...config }: PropsWithChildren<Props>) => { howl: Howl | undefined; isMuted: boolean | undefined; volume: number; ready: boolean; pause: () => void; play: () => void; fade: (from: number, to: number, duration: number) => void; seek: () => number | undefined; duration: () =...' is not assignable to type 'FunctionComponent<Props>'.
Type '{ howl: Howl | undefined; isMuted: boolean | undefined; volume: number; ready: boolean; pause: () => void; play: () => void; fade: (from: number, to: number, duration: number) => void; seek: () => number | undefined; duration: () => number | undefined; }' is missing the following properties from type 'ReactElement<any, any>': type, props, keyts(2322)

I am creating my Props type and then the parameters of my function is infered from the generic FunctionComponent. I have a suspicion that mapDispatchToProps might be the issue here somehow. My problem is that I can't deduce what the problem is from the error message.

import { useState, useEffect, useRef, FunctionComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { Howl } from 'howler';

import { getSignedMediaURL } from '../../services/meditations';
import { SetHasConnectivity } from 'src/store/user/actions';

const mapDispatchToProps = (dispatch: Dispatch) =>
    bindActionCreators({ SetHasConnectivity }, dispatch);

const noop = () => {};

type Props = {
    src: string | null;
    onload?: () => void;
    volume?: number;
    isMuted?: boolean;
    mediaType: 'soundscape' | 'meditation' | 'other';
    loop?: boolean;
    onend?: () => void;
    onstop?: () => void;
} & ReturnType<typeof mapDispatchToProps>;

const useMeditation: FunctionComponent<Props> = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }) => {
    const player = useRef<Howl>();
    const soundId = useRef<number>();

    const [ready, setReady] = useState(false);

    const onSoundLoad = () => {
        if (player.current) {
            player.current.volume(volume);
            setReady(true);
            onload();
        }
    };

    useEffect(() => {
        if (src) {
            (async function () {
                let url = src;

                if (mediaType === 'soundscape' || mediaType === 'meditation') {
                    try {
                        const response = await getSignedMediaURL(src, mediaType);
                        url = response.body.url;
                    } catch (error) {
                        console.log('Test');
                    }
                }

                player.current = new Howl({
                    src: [url],
                    html5: true,
                    volume: 0,
                    onload: onSoundLoad,
                    ...config,
                });
            })();
        } else {
            setReady(true);
        }

        return () => {
            if (player.current) {
                player.current.stop();
            }
        };
    }, []); // eslint-disable-line

    useEffect(() => {
        if (player.current) {
            player.current.volume(volume);
        }
    }, [volume]);

    useEffect(() => {
        if (player.current) {
            if (isMuted) {
                player.current.mute(true, soundId.current);
            } else {
                player.current.mute(false);
            }
        }
    }, [isMuted]);

    const pause = () => {
        if (player.current) {
            player.current.pause();
        }
    };

    const play = () => {
        if (player.current) {
            soundId.current = player.current.play();
        }
    };

    const fade = (from: number, to: number, duration: number) => {
        if (player.current) {
            if (!player.current.playing()) {
                play();
            }

            player.current.fade(from, to, duration, soundId.current);
        }
    };

    const seek = () => {
        if (player.current) {
            return player.current.seek();
        }

        return;
    };

    const duration = () => {
        if (player.current) {
            return player.current.duration();
        }

        return;
    };

    return {
        howl: player.current,
        isMuted,
        volume,
        ready,

        pause,
        play,
        fade,

        seek,
        duration,
    };
}

export connect(null, mapDispatchToProps)(useMeditation);

Body:
A React component must return a JSX Element (an HTML snippet, essentially) or null.  Your useMeditation is not a component -- it is a custom hook which returns an object.

This type annotation is incorrect:

const useMeditation: FunctionComponent<Props> = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }) => {

It should be:

const useMeditation = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }: Props) => {

You cannot use the connect higher-order component on a hook.  It can only be used on components.

You need to use the useDispatch hook instead.  I'm not seeing where you actually dispatch the action?  But it should look something like this.

// Same as before, but delete the `ReturnType<typeof mapDispatchToProps>`
type Props = { /* ... */ }

const useMeditation = ({ volume = 1, onload = noop, isMuted, src, mediaType, ...config }: Props) => {

    // Get access to the dispatch function.
    const dispatch = useDispatch();

    // Dispatch your action.
    const someFunction = () => {
        dispatch(SetHasConnectivity(true));
    }

    /* ... rest of the hook ... */
}

// No need to use `connect` or anything else here, just export it.
export default useMeditation;


问:
Best way to handle EventListeners/Handlers for 1000 buttons?
I'm working on a game where users can win buttons/badges as awards.  I estimate there will be around 500 awards, in all.

I want to allow the users to sell their duplicate/unwanted badges to the bank and buy new ones from the bank.

I am showing the badges in multiple awards frames.  Below the badges, I show the count, along with a "Buy" and "Sell" button.

My question is: What's the best way to handle SO MANY buy & sell buttons?  Is there a way around coding 1000 eventListeners and 1000 eventHandlers?

One possible solution is to name my buttons, incrementally, like "buy_mc1", "buy_mc2", etc.  Then do a loop to create listeners for this["buy_mc" + i].  However, I would then have to make VERY sure that I link these back correctly to the awards.

Currently, I have an "award_mc" field in my database, which stores the name of the movieclip in my .fla.  From that, I can access related assets, like the count field, like: this[db.award_mc + "_count"].txt.

Unfortunately, this method does not lend itself well to looped access.

Maybe I can create an array of movieclip names that are in synch with the buy/sell buttons.  For example:

myArray = {aMissionAward, anotherAward, ubernessAward};

My buttons would be:
buy_0, buy_1, buy_2, etc.

When someone clicks a button, I can link buy_2 to "ubernessAward", then look for "ubernessAward" on the database.

How can I get the number from the button, though?  Even if I can loop through setting up the eventListeners, will I have to set up individuatl eventHandlers to process the correct index number?

I'm open to suggestions on another way to do this.

-------------------------- EDIT ----------------------------

Here's my solution.  Props to Jens Struwe for pointing me in the right direction.

I was not able to get this to work with buttons on the stage.  Apparently, buttons are a static class.  MovieClips are dynamic, so I was able to get this to work by using MovieClips.  Here's what I did:

Added 3 MovieClips to the stage.
Named them "mc0", "mc1", and "mc2".

Add this AS3 code:

```<code>for (var i:Number=0; i<3; i++)
{
    this["mc" + i].addEventListener( MouseEvent.CLICK, onMcClick );
    this["mc" + i].awardKey = i;
}

function onMcClick( evt:MouseEvent ):void
{
    trace("MC ID = " +(evt.target).awardKey);

    switch ((evt.target).awardKey)
    {
        case 0:
            trace("     Do stuff for 0");
            break;
        case 1:
            trace("     Do stuff for 1");
            break;
        case 2:
            trace("     Do stuff for 2");
            break;
    }
}
</code>```

From here, I can tie the awardKey to an array of MovieClip names.  Then, I can use the MovieClip names to read my database.

This is why I come to Stack Overflow, FIRST, when I have a problem.  :)

答:
You need only one listener that can handle all of your buttons:

Let your buy and sell button click events bubble.

Give each button a unique identifier such as myButton.awardKey = "uberness";

Register a single event listener to the container of all of your buttons.

Determine the actual button clicked using event.target and the type of award using MyButton(event.target).awardKey.

Body:
I'm working on a game where users can win buttons/badges as awards.  I estimate there will be around 500 awards, in all.

I want to allow the users to sell their duplicate/unwanted badges to the bank and buy new ones from the bank.

I am showing the badges in multiple awards frames.  Below the badges, I show the count, along with a "Buy" and "Sell" button.

My question is: What's the best way to handle SO MANY buy & sell buttons?  Is there a way around coding 1000 eventListeners and 1000 eventHandlers?

One possible solution is to name my buttons, incrementally, like "buy_mc1", "buy_mc2", etc.  Then do a loop to create listeners for this["buy_mc" + i].  However, I would then have to make VERY sure that I link these back correctly to the awards.

Currently, I have an "award_mc" field in my database, which stores the name of the movieclip in my .fla.  From that, I can access related assets, like the count field, like: this[db.award_mc + "_count"].txt.

Unfortunately, this method does not lend itself well to looped access.

Maybe I can create an array of movieclip names that are in synch with the buy/sell buttons.  For example:

myArray = {aMissionAward, anotherAward, ubernessAward};

My buttons would be:
buy_0, buy_1, buy_2, etc.

When someone clicks a button, I can link buy_2 to "ubernessAward", then look for "ubernessAward" on the database.

How can I get the number from the button, though?  Even if I can loop through setting up the eventListeners, will I have to set up individuatl eventHandlers to process the correct index number?

I'm open to suggestions on another way to do this.

-------------------------- EDIT ----------------------------

Here's my solution.  Props to Jens Struwe for pointing me in the right direction.

I was not able to get this to work with buttons on the stage.  Apparently, buttons are a static class.  MovieClips are dynamic, so I was able to get this to work by using MovieClips.  Here's what I did:

Added 3 MovieClips to the stage.
Named them "mc0", "mc1", and "mc2".

Add this AS3 code:

for (var i:Number=0; i<3; i++)
{
    this["mc" + i].addEventListener( MouseEvent.CLICK, onMcClick );
    this["mc" + i].awardKey = i;
}

function onMcClick( evt:MouseEvent ):void
{
    trace("MC ID = " +(evt.target).awardKey);

    switch ((evt.target).awardKey)
    {
        case 0:
            trace("     Do stuff for 0");
            break;
        case 1:
            trace("     Do stuff for 1");
            break;
        case 2:
            trace("     Do stuff for 2");
            break;
    }
}

From here, I can tie the awardKey to an array of MovieClip names.  Then, I can use the MovieClip names to read my database.

This is why I come to Stack Overflow, FIRST, when I have a problem.  :)


问:
Is there a way to disable Click options from prompting via a global flag?
I'm using click to implement a command-line interface in Python. Click has a feature that can prompt for a value if one isn't specified. Like so:

@click.command()
@click.option('--name', prompt=True)
def hello(name):
    click.echo(f"Hello {name}!")
```

This is great when a CLI is being used interactively, but prompting during a non-interactive run is bad (can hang a shell script, for example). I'd like to add a -q flag that would globally disable prompting for every other option.

Is there a straightforward way to do this?

答:
You can define a Command Group that accepts a -q flag, then attach all the commands that you would want to be affected by this -q flag as subcommands of that group. Save the -q existence/non-existence in the group function, and pass it around to the subcommands as part of the command Context.

https://click.palletsprojects.com/en/8.0.x/commands/#nested-handling-and-contexts

Each time a command is invoked, a new context is created and linked with the parent context. Normally, you can’t see these contexts, but they are there. Contexts are passed to parameter callbacks together with the value automatically.

```<code>import click

@click.group()
@click.option("-q", help="Disable all prompts", flag_value=True, default=False)
@click.pass_context
def cli(ctx, q):
    # Ensure that ctx.obj exists and is a dict
    ctx.ensure_object(dict)
    # Apply group-wide feature switches
    ctx.obj["q"] = q
    print(f"In group: {ctx.obj}")

@cli.command()
@click.option("--name", prompt=True)
def cmd1(name):
    click.echo(f"Hello {name}!")
</code>```

$ python cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...

Options:
  -q      Disable all prompts
...

Commands:
  cmd1

$ python cli.py cmd1
In group: {'q': False}
Name: abc
Hello abc!

$ python cli.py cmd1 --name=xyz
In group: {'q': False}
Hello xyz!

$ python cli.py -q cmd1 --name=xyz
In group: {'q': True}
Hello xyz!
```
<p>Here, notice that <code>-q</code> is <em>a flag on the entire CLI</em>, not just for <code>cmd1</code>, which, as I understand, is what you wanted. It doesn't affect <code>cmd1</code> <em>yet</em>, but it's there in the context for all commands on that group.</p>
<p>How then do we actually disable the prompt based on what's <code>q</code> in the context? You can define a custom <code>click.Option</code> class and override the <code>prompt_for_value(ctx)</code> method.</p>
```import click

DEFAULTS = {
    "name": "automatically-set-name",
}

class DynamicPromptOption(click.Option):
    def prompt_for_value(self, ctx):
        q = ctx.obj.get("q")
        print(f"In option {self.name}: q={q}")
        if q:
            return DEFAULTS[self.name]
        return super().prompt_for_value(ctx)
```
<p>Here, you skip the base implementation call to' <code>prompt_for_value</code> when <code>-q</code> was passed (technically, when <code>q</code> is <code>True</code>-ish), and just return some automatic default value directly (in my example above, maybe from a global constant or dictionary of values).</p>
<p>Then, make sure to set the <code>cls=<custom class></code> parameter on your <code>@click.option</code> decorator to use your custom <code>Option</code> class.</p>
```@cli.command()
@click.option("--name", prompt=True, cls=DynamicPromptOption)
def cmd1(name):
    click.echo(f"Hello {name}!")
```
<pre class="lang-none prettyprint-override"><code>$ python cli.py cmd1
In group: {'q': False}
In option name: q=False
Name: abc
Hello abc!

$ python cli.py -q cmd1
In group: {'q': True}
In option name: q=True
Hello automatically-set-name!
</code>```

The nice thing is that the interactive usage should be unaffected:

$ python cli.py cmd1
In group: {'q': False}
In option name: q=False
Name: abc
Hello abc!

$ python cli.py cmd1 --name=xyz
In group: {'q': False}
Hello xyz!

$ python cli.py cmd1 --name
In group: {'q': False}
Error: Option '--name' requires an argument.
```

Body:
I'm using click to implement a command-line interface in Python. Click has a feature that can prompt for a value if one isn't specified. Like so:

@click.command()
@click.option('--name', prompt=True)
def hello(name):
    click.echo(f"Hello {name}!")

This is great when a CLI is being used interactively, but prompting during a non-interactive run is bad (can hang a shell script, for example). I'd like to add a -q flag that would globally disable prompting for every other option.

Is there a straightforward way to do this?

Body:
You can define a Command Group that accepts a -q flag, then attach all the commands that you would want to be affected by this -q flag as subcommands of that group. Save the -q existence/non-existence in the group function, and pass it around to the subcommands as part of the command Context.

https://click.palletsprojects.com/en/8.0.x/commands/#nested-handling-and-contexts

Each time a command is invoked, a new context is created and linked with the parent context. Normally, you can’t see these contexts, but they are there. Contexts are passed to parameter callbacks together with the value automatically.

import click

@click.group()
@click.option("-q", help="Disable all prompts", flag_value=True, default=False)
@click.pass_context
def cli(ctx, q):
    # Ensure that ctx.obj exists and is a dict
    ctx.ensure_object(dict)
    # Apply group-wide feature switches
    ctx.obj["q"] = q
    print(f"In group: {ctx.obj}")

@cli.command()
@click.option("--name", prompt=True)
def cmd1(name):
    click.echo(f"Hello {name}!")

$ python cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...

Options:
  -q      Disable all prompts
...

Commands:
  cmd1

$ python cli.py cmd1
In group: {'q': False}
Name: abc
Hello abc!

$ python cli.py cmd1 --name=xyz
In group: {'q': False}
Hello xyz!

$ python cli.py -q cmd1 --name=xyz
In group: {'q': True}
Hello xyz!

Here, notice that -q is a flag on the entire CLI, not just for cmd1, which, as I understand, is what you wanted. It doesn't affect cmd1 yet, but it's there in the context for all commands on that group.

How then do we actually disable the prompt based on what's q in the context? You can define a custom click.Option class and override the prompt_for_value(ctx) method.

import click

DEFAULTS = {
    "name": "automatically-set-name",
}

class DynamicPromptOption(click.Option):
    def prompt_for_value(self, ctx):
        q = ctx.obj.get("q")
        print(f"In option {self.name}: q={q}")
        if q:
            return DEFAULTS[self.name]
        return super().prompt_for_value(ctx)

Here, you skip the base implementation call to' prompt_for_value when -q was passed (technically, when q is True-ish), and just return some automatic default value directly (in my example above, maybe from a global constant or dictionary of values).

Then, make sure to set the cls=<custom class> parameter on your @click.option decorator to use your custom Option class.

@cli.command()
@click.option("--name", prompt=True, cls=DynamicPromptOption)
def cmd1(name):
    click.echo(f"Hello {name}!")

$ python cli.py cmd1
In group: {'q': False}
In option name: q=False
Name: abc
Hello abc!

$ python cli.py -q cmd1
In group: {'q': True}
In option name: q=True
Hello automatically-set-name!

The nice thing is that the interactive usage should be unaffected:

$ python cli.py cmd1
In group: {'q': False}
In option name: q=False
Name: abc
Hello abc!

$ python cli.py cmd1 --name=xyz
In group: {'q': False}
Hello xyz!

$ python cli.py cmd1 --name
In group: {'q': False}
Error: Option '--name' requires an argument.


问:
Jest dont show tests when there are more than one suite
Im testing my app.
When I run 'npm test' I want to see in the terminal all tests.
I have one file called auth.test.js with all my tests.

So my output when i run npm test is this one:

```<code>> jest --forceExit

 PASS  src/test/auth.test.js
  /LOGIN testing
    ✓ Should not login a unexistent username. (22ms)
    ✓ Should not login with incorrect credentials. (63ms)
    ✓ Should not login with empty fields. (2ms)
    ✓ Should login a moked user. (67ms)
  /SIGNUP testing
    ✓ Should not sign up a new user with invalid password. (3ms)
    ✓ Should not sign up a new user with invalid username. (2ms)
    ✓ Should sign up a new user. (72ms)
    ✓ Should not sign up a existing user. (4ms)
    ✓ Should not sign up with empty fields. (3ms)

Test Suites: 1 passed, 1 total
Tests:       9 passed, 9 total
Snapshots:   0 total
Time:        1.114s, estimated 2s
Ran all test suites.
</code>```

Thats fine. I can see all tests with details.

Now, I want to add a new file with tests, called api.tests.js.

Then, when I run 'npm test' i see this output:

```<code>> jest --forceExit

 PASS  src/test/api.test.js
 PASS  src/test/auth.test.js

Test Suites: 2 passed, 2 total
Tests:       10 passed, 10 total
Snapshots:   0 total
Time:        1.589s, estimated 2s
Ran all test suites.
</code>```

After read the jest documentation (cli article) I cant found how to see the details, like I see when testing 1 file,  but when testing more than 1 file.

Is it posible? How to do it?

答:
You're probably getting npm --verbose results which look different. To get jest --verbose, add two hyphens to your command: -- --verbose. I had the same problem and it worked for me.

I got the solution from here: Is there an option to show all test descriptions when I run jest tests?

Body:
Im testing my app.
When I run 'npm test' I want to see in the terminal all tests.
I have one file called auth.test.js with all my tests.

So my output when i run npm test is this one:

> jest --forceExit

 PASS  src/test/auth.test.js
  /LOGIN testing
    ✓ Should not login a unexistent username. (22ms)
    ✓ Should not login with incorrect credentials. (63ms)
    ✓ Should not login with empty fields. (2ms)
    ✓ Should login a moked user. (67ms)
  /SIGNUP testing
    ✓ Should not sign up a new user with invalid password. (3ms)
    ✓ Should not sign up a new user with invalid username. (2ms)
    ✓ Should sign up a new user. (72ms)
    ✓ Should not sign up a existing user. (4ms)
    ✓ Should not sign up with empty fields. (3ms)

Test Suites: 1 passed, 1 total
Tests:       9 passed, 9 total
Snapshots:   0 total
Time:        1.114s, estimated 2s
Ran all test suites.

Thats fine. I can see all tests with details.

Now, I want to add a new file with tests, called api.tests.js.

Then, when I run 'npm test' i see this output:

> jest --forceExit

 PASS  src/test/api.test.js
 PASS  src/test/auth.test.js

Test Suites: 2 passed, 2 total
Tests:       10 passed, 10 total
Snapshots:   0 total
Time:        1.589s, estimated 2s
Ran all test suites.

After read the jest documentation (cli article) I cant found how to see the details, like I see when testing 1 file,  but when testing more than 1 file.

Is it posible? How to do it?


问:
react-router is not rendering anything
I created my app with create-react-app and trying to use react-router on it. but it's not working at all.

Here's my Header.js.

```<code>  import React, { Component } from 'react';

class Header extends Component {
    render() {
        return (
          <nav>
                <div className="nav-wrapper blue darken-1">
                    <a className="brand-logo center">Testing</a>

                    <div className="right">
                        <ul>
                            <li>
                                <a><i className="material-icons">vpn_key</i></a>
                            </li>
                            <li>
                                <a><i className="material-icons">lock_open</i></a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        );
    }
}

export default Header;
</code>```

my App.js.

```<code>import React, { Component } from 'react';
import Header from './Header';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="Header">
        <Header />
        {this.props.children}
        </div>
      </div>
    );
  }
};

export default App;
</code>```

and my index.js here.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './App';
import Home from './Home';
import Login from './Login';
import Register from './Register';

ReactDOM.render((
  <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Home}/>
            <Route path="/home" component={Home}/>
            <Route path="/login" component={Login}/>
            <Route path="/register" component={Register}/>
        </Route>
    </Router>),
  document.getElementById('root')
);
</code>```

Don't worry about Home, Login, Register thing on index.js. They are super fine.

Am I doing something wrong?

答:
The correct format is</p>
```<code>import React from 'react';
import { BrowserRouter as Router, Routes, Route,  } from "react-
router-dom";
import './App.css';
import Home from './components/Pages/Home';

function App() {
return (
 <>
 <Router>
    <Routes>
    <Route exact path='/' element={<Home/>}/>
    </Routes>
  </Router>
 </>
)}
export default App;
</code>```

Title: react-router is not rendering anything

Body:
I created my app with create-react-app and trying to use react-router on it. but it's not working at all.

Here's my Header.js.

  import React, { Component } from 'react';

class Header extends Component {
    render() {
        return (

                    Testing

                                vpn_key

                                lock_open

        );
    }
}

export default Header;

my App.js.

import React, { Component } from 'react';
import Header from './Header';

class App extends Component {
  render() {
    return (

        {this.props.children}

    );
  }
};

export default App;

and my index.js here.

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './App';
import Home from './Home';
import Login from './Login';
import Register from './Register';

ReactDOM.render((
  <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Home}/>
            <Route path="/home" component={Home}/>
            <Route path="/login" component={Login}/>
            <Route path="/register" component={Register}/>
        </Route>
    </Router>),
  document.getElementById('root')
);

Don't worry about Home, Login, Register thing on index.js. They are super fine.

Am I doing something wrong?

Body:
The correct format is

import React from 'react';
import { BrowserRouter as Router, Routes, Route,  } from "react-
router-dom";
import './App.css';
import Home from './components/Pages/Home';

function App() {
return (
 <>
 <Router>
    <Routes>
    <Route exact path='/' element={<Home/>}/>
    </Routes>
  </Router>
 </>
)}
export default App;


问:
How can I hide file extensions in PHP?
I'm using the jquery plugin jqueryFileTree with the PHP connector (slightly modified to give directories individual classes) to show the contents of a directory. I want to, however, hide all file extensions. Has anyone done something similar? I can think of one or two ways of implementing it but they seem overly-complicated...

Is there a relatively simple way of doing this in PHP?

答:
Looking at the PHP connector code, you want to replace this:

```<code>// All files
foreach( $files as $file ) {
    if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) ) {
        $ext = preg_replace('/^.*\./', '', $file);
        echo "<li class=\"file ext_$ext\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "\">" . htmlentities($file) . "</a></li>";
    }
}
</code>```

With this:

```<code>// All files
foreach( $files as $file ) {
    if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) ) {
        $parts = explode(".", $file);
        $ext = array_pop($parts);
        $name = implode(".", $parts);
        echo "<li class=\"file ext_$ext\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "\">" . htmlentities($name) . "</a></li>";
    }
}
</code>```

Please note that the code in this provided connector script is not all that safe and you should take steps to prevent users abusing it to get access to sensitive folders.

OwnerDisplayName: Sean

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

Title: How can I hide file extensions in PHP?

Body:
Looking at the PHP connector code, you want to replace this:

// All files
foreach( $files as $file ) {
    if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) ) {
        $ext = preg_replace('/^.*\./', '', $file);
        echo "<li class=\"file ext_$ext\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "\">" . htmlentities($file) . "</a></li>";
    }
}

With this:

// All files
foreach( $files as $file ) {
    if( file_exists($root . $_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($root . $_POST['dir'] . $file) ) {
        $parts = explode(".", $file);
        $ext = array_pop($parts);
        $name = implode(".", $parts);
        echo "<li class=\"file ext_$ext\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file) . "\">" . htmlentities($name) . "</a></li>";
    }
}

Please note that the code in this provided connector script is not all that safe and you should take steps to prevent users abusing it to get access to sensitive folders.

OwnerDisplayName: Paolo Bergantino


问:
What PHP function(s) should I use to cut off the end of a string?
I have a filename stored with the directory as a value.

Ex. /var/www/remove_this.php

In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.

There are so many string editing functions, I don't know a good approach. Thanks!

答:
You could use string functions, but for this case PHP has some smarter directory functions:

```<code>$dir = dirname('/var/www/remove_this.php'); // /var/www
</code>```

pathinfo is an excellent one as well.

Body:
You could use string functions, but for this case PHP has some smarter directory functions:

$dir = dirname('/var/www/remove_this.php'); // /var/www

pathinfo is an excellent one as well.


问:
Function called on viewController close (when application exit)?
I am looking for a function which is called on a UIViewController when the application exits.

I tried it out with viewWillDisappear and with applicationWillTerminate but nothing works.

I want to save my settings from the UIViewController in this function.

答:
Swift 5.5

Use For App Enter Background

```<code>NotificationCenter.default.addObserver(self, selector: #selector(appResignActiveNotify), name: UIApplication.willResignActiveNotification, object: nil)

 @objc func appResignActiveNotify() {
       //called when App enter background
   }
</code>```

For App Terminate

```<code>NotificationCenter.default.addObserver(self, selector: #selector(appTerminateNotify), name: UIApplication.willTerminateNotification, object: nil)

  @objc func appTerminateNotify() {
       //called when Terminate
   }
</code>```

Body:
Swift 5.5

Use For App Enter Background

NotificationCenter.default.addObserver(self, selector: #selector(appResignActiveNotify), name: UIApplication.willResignActiveNotification, object: nil)

 @objc func appResignActiveNotify() {
       //called when App enter background
   }

For App Terminate

NotificationCenter.default.addObserver(self, selector: #selector(appTerminateNotify), name: UIApplication.willTerminateNotification, object: nil)

  @objc func appTerminateNotify() {
       //called when Terminate
   }


问:
How can you log HTTP responses in node?
You can use NODE_DEBUG=http to log requests, is there a similar way to log responses?

答:
```<code>const logRequestStart = (req: Request, res: Response, next: NextFunction) => {
    console.info(`${req.method} ${req.originalUrl}`)
    next()
}

app.use(logRequestStart)
</code>```

click here

Title: How can you log HTTP responses in node?

Body:
const logRequestStart = (req: Request, res: Response, next: NextFunction) => {
    console.info(`${req.method} ${req.originalUrl}`)
    next()
}

app.use(logRequestStart)

click here


问:
C# ternary operator for optional string parameter
What is the correct/best way to handle the string as optional parameter in ternary operator:

```<code>public static void method(string s1, string s2="")
{
    var str = !string.IsNullOrEmpty(s2) ? s2.Equals("abc") ? "abcuser" : "xyzuser" : "xyzuser";
    Console.WriteLine(str);
}
</code>```

OR

```<code>public static void method(string s1, string s2="")
{
    var str = !string.IsNullOrEmpty(s2) && s2.Equals("abc") ? "abcuser" : "xyzuser";
    Console.WriteLine(str);
}
</code>```

答:
When creating a ternary operator, it's important that you keep them as clean and simple as possible so it's easier for other developers to read. In this instance, I can't see a use for the "s1" parameter. If this is your entire method, I recommend removing it and keeping it simple. Your "s2" parameter must equal "abc" to be accepted. Hence, a null check is not required. However, if you ever need to use a check like this, I recommend using IsNullOrWhiteSpace() because it indicates whether a specified string is null, empty, or consists only of white-spaced characters. This means it will check if the string contains empty space as well. E.g. if "s2" = "   ", IsNullOrEmpty() wouldn't pick that up. I will leave a code example below, with a commented out line using this string method to check for white space. However, in this instance, I suggest you only use the smaller line.

```<code>
public static void method(string s1, string s2 = "") {
     //var str = !string.IsNullOrWhiteSpace(s2) && s2.Equals("abc") ? "abcuser"
       : "xyzuser";
       var str = s2 == "abc" ? "abcuser" : "xyzuser";
       Console.WriteLine(str);
}
</code>```

Too make it cleaner and more optimized, if you are not using that var variable again, you could just do this.

```<code>public static void method(string s1, string s2 = "") {
            Console.WriteLine(s2 == "abc" ? "abcuser" : "xyzuser");
        }
</code>```

Or another alternative would be to return this value as a string

```<code>public static string method(string s2 = "") {
            return s2 == "abc" ? "abcuser" : "xyzuser";
        }
</code>```

Body:
What is the correct/best way to handle the string as optional parameter in ternary operator:

public static void method(string s1, string s2="")
{
    var str = !string.IsNullOrEmpty(s2) ? s2.Equals("abc") ? "abcuser" : "xyzuser" : "xyzuser";
    Console.WriteLine(str);
}

OR

public static void method(string s1, string s2="")
{
    var str = !string.IsNullOrEmpty(s2) && s2.Equals("abc") ? "abcuser" : "xyzuser";
    Console.WriteLine(str);
}

Body:
When creating a ternary operator, it's important that you keep them as clean and simple as possible so it's easier for other developers to read. In this instance, I can't see a use for the "s1" parameter. If this is your entire method, I recommend removing it and keeping it simple. Your "s2" parameter must equal "abc" to be accepted. Hence, a null check is not required. However, if you ever need to use a check like this, I recommend using IsNullOrWhiteSpace() because it indicates whether a specified string is null, empty, or consists only of white-spaced characters. This means it will check if the string contains empty space as well. E.g. if "s2" = "   ", IsNullOrEmpty() wouldn't pick that up. I will leave a code example below, with a commented out line using this string method to check for white space. However, in this instance, I suggest you only use the smaller line.

public static void method(string s1, string s2 = "") {
     //var str = !string.IsNullOrWhiteSpace(s2) && s2.Equals("abc") ? "abcuser"
       : "xyzuser";
       var str = s2 == "abc" ? "abcuser" : "xyzuser";
       Console.WriteLine(str);
}

Too make it cleaner and more optimized, if you are not using that var variable again, you could just do this.

public static void method(string s1, string s2 = "") {
            Console.WriteLine(s2 == "abc" ? "abcuser" : "xyzuser");
        }

Or another alternative would be to return this value as a string

public static string method(string s2 = "") {
            return s2 == "abc" ? "abcuser" : "xyzuser";
        }


问:
Winapi CreateProcess File Permissions
I'm currently writing some software that has two different programs using the winapi (a parser and an interpreter). I would like to call the parser from the interpreter, so I am using the CreateProcessA function. However, when the parser tries to open a file, it throws a Permission Denied error, and I'm not too sure why.

Calling the parser on its own, and not from the interpreter, works perfectly fine.

According to CreateProcessA, "The new process runs in the security context of the calling process," so it seems like this other program shouldn't have any issues with permissions since I can open files from the interpreter.

Is there something that I'm missing with CreateProcessA that would make it change file permissions for the child process?

Here is a snippet of code for the interpreter (note that I've left out error checking to make the code simpler to show here):

```<code>// These are just used to open pipes so I can extract stdout
SECURITY_ATTRIBUTES sec = {0};
sec.nLength = sizeof(SECURITY_ATTRIBUTES);
sec.bInheritHandle = TRUE;
sec.lpSecurityDescriptor = NULL;

HANDLE stdout_rd, stdout_wr;

CreatePipe(&stdout_rd, &stdout_wr, &sec, 0);
SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0);

STARTUPINFO startInfo = {0};
startInfo.cb = sizeof(startInfo);
startInfo.hStdError = stdout_wr;
startInfo.hStdOutput = stdout_wr;
startInfo.hStdInput = NULL;
startInfo.dwFlags |= STARTF_USESTDHANDLES;

PROCESS_INFORMATION processInfo = {0};

char *command = "parser /path/to/file.txt";
CreateProcessA(NULL, command, NULL, NULL, TRUE,
    NORMAL_PRIORITY_CLASS, NULL, NULL, &startInfo, &processInfo);

// Do more stuff to print out stdout from child process
</code>```

Here is a snippet of code from the parser:

```<code>int main(int argc, char **argv) {
    // This call throws the error:
    // Error: Permission denied

    FILE *file = fopen(argv[1], "rb");
    if (!file) {
        printf("Error: %s\n", strerror(errno));
    }

    // Parse File
}
</code>```

Here is a snippet of code from the interpreter that opens and closes the file.

```<code>HANDLE file = CreateFileA("/path/to/file.txt", GENERIC_READ,
    0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

FILETIME writeTime = {0};
GetFileTime(file, NULL, NULL, &writeTime);

CloseHandle(file);
</code>```

Thank you!

答:
I dont think that problem is in the file permissions. If you could write file somewhere, you clearly should be able to read it with the same access token. You could get Access Denied error because file is still open by the interpreter process in the exclusive mode. You could either check that file is closed before calling CreateProcess, or use CreateFile to read and write with FILE_SHARE_* flags. However it could lead to other errors, if interpreter does not complete all file write operations before parser tries to use it.

As an alternative to files in this scenario you could use memory mapped files (CreateFileMapping, MapViewOfFile), to share data buffers between different processes.

Title: Winapi CreateProcess File Permissions

Body:
I'm currently writing some software that has two different programs using the winapi (a parser and an interpreter). I would like to call the parser from the interpreter, so I am using the CreateProcessA function. However, when the parser tries to open a file, it throws a Permission Denied error, and I'm not too sure why.

Calling the parser on its own, and not from the interpreter, works perfectly fine.

According to CreateProcessA, "The new process runs in the security context of the calling process," so it seems like this other program shouldn't have any issues with permissions since I can open files from the interpreter.

Is there something that I'm missing with CreateProcessA that would make it change file permissions for the child process?

Here is a snippet of code for the interpreter (note that I've left out error checking to make the code simpler to show here):

// These are just used to open pipes so I can extract stdout
SECURITY_ATTRIBUTES sec = {0};
sec.nLength = sizeof(SECURITY_ATTRIBUTES);
sec.bInheritHandle = TRUE;
sec.lpSecurityDescriptor = NULL;

HANDLE stdout_rd, stdout_wr;

CreatePipe(&stdout_rd, &stdout_wr, &sec, 0);
SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0);

STARTUPINFO startInfo = {0};
startInfo.cb = sizeof(startInfo);
startInfo.hStdError = stdout_wr;
startInfo.hStdOutput = stdout_wr;
startInfo.hStdInput = NULL;
startInfo.dwFlags |= STARTF_USESTDHANDLES;

PROCESS_INFORMATION processInfo = {0};

char *command = "parser /path/to/file.txt";
CreateProcessA(NULL, command, NULL, NULL, TRUE,
    NORMAL_PRIORITY_CLASS, NULL, NULL, &startInfo, &processInfo);

// Do more stuff to print out stdout from child process

Here is a snippet of code from the parser:

int main(int argc, char **argv) {
    // This call throws the error:
    // Error: Permission denied

    FILE *file = fopen(argv[1], "rb");
    if (!file) {
        printf("Error: %s\n", strerror(errno));
    }

    // Parse File
}

Here is a snippet of code from the interpreter that opens and closes the file.

HANDLE file = CreateFileA("/path/to/file.txt", GENERIC_READ,
    0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

FILETIME writeTime = {0};
GetFileTime(file, NULL, NULL, &writeTime);

CloseHandle(file);

Thank you!


问:
Calculate the duration from start date and end date in SQL
I am using SQL Server.

```<code>select DISTINCT caseNumber, dateStarted,dateStopped from patientView where dateStarted !='' and dateStopped != '';
</code>```

We get the following output,

CaseNumber
dateStarted
dateStopped

1
2022-01-01
2022-01-04

1
2022-01-05
2022-01-19

2
2022-01-03
2022-01-10

4
2022-01-05
2022-01-11

4
2022-01-13
2022-01-14

4
2022-01-21
2022-01-23

5
2022-01-15
2022-01-16

5
2022-01-17
2022-01-24

5
2022-01-24
2022-01-26

8
2022-01-17
2022-01-20

8
2022-01-21
2022-01-28

11
2022-01-18
2022-01-25

11
2022-01-26
2022-01-27

I want to calculate the duration for each caseNumber. For eg. caseNumber 1 has 2 rows and hence total duration would be 18days.

答:
I would suggest using the group by keyword to group redundant case numbers and take the min for the startdates and max for stopdates. You can do something like:

```<code>SELECT caseNumber, max(dateStopped)-min(dateStarted)
from patientView
where dateStarted != '' and dateStopped != ''
GROUP BY caseNumber;
</code>```

Body:
I am using SQL Server.

select DISTINCT caseNumber, dateStarted,dateStopped from patientView where dateStarted !='' and dateStopped != '';

We get the following output,

CaseNumber
dateStarted
dateStopped

1
2022-01-01
2022-01-04

1
2022-01-05
2022-01-19

2
2022-01-03
2022-01-10

4
2022-01-05
2022-01-11

4
2022-01-13
2022-01-14

4
2022-01-21
2022-01-23

5
2022-01-15
2022-01-16

5
2022-01-17
2022-01-24

5
2022-01-24
2022-01-26

8
2022-01-17
2022-01-20

8
2022-01-21
2022-01-28

11
2022-01-18
2022-01-25

11
2022-01-26
2022-01-27

I want to calculate the duration for each caseNumber. For eg. caseNumber 1 has 2 rows and hence total duration would be 18days.

Body:
I would suggest using the group by keyword to group redundant case numbers and take the min for the startdates and max for stopdates. You can do something like:

SELECT caseNumber, max(dateStopped)-min(dateStarted)
from patientView
where dateStarted != '' and dateStopped != ''
GROUP BY caseNumber;


问:
How to override div onClick event when button is clicked?
I am trying to stop the parent div from executing an onClick event when the child Delete button is clicked.

```<code><div>
    {notes.map((val) => {
       return
      <div key={val.id} onClick={() => Logic.selectNote(val.note, val.id)} className="editorDiv">
      <Delete className="delBtn" onClick={(e) => del(e, val.id)}></Delete>
      <ReactQuill className="note" value={Logic.limitDisplayText(val.note)} readOnly={true}  /></div>
    })}
</div>
</code>```

I tried to implement event.stopPropogation however, it gives me an error.

```<code>function del(e, noteId) {
        e.stopPropogation()
        localStorage.removeItem(noteID)
    }
</code>```

答: In case anyone has the same problem as me, simply use e.stopPropagation(). This stops the click event from bubbling up to the other HTML elements.

Body:
I am trying to stop the parent div from executing an onClick event when the child Delete button is clicked.

    {notes.map((val) => {
       return

 Logic.selectNote(val.note, val.id)} className="editorDiv">
      <Delete className="delBtn" onClick={(e) => del(e, val.id)}></Delete>
      <ReactQuill className="note" value={Logic.limitDisplayText(val.note)} readOnly={true}  />

    })}

I tried to implement event.stopPropogation however, it gives me an error.

function del(e, noteId) {
        e.stopPropogation()
        localStorage.removeItem(noteID)
    }


问:
Heroku server for my app keeps on crashing
I deployed a react app with the server being hosted on Heroku, and the backend/Heroku keeps on crashing after a few page loads or messages I send on the app.
To clarify, the app works initially with no signs of impending error, and then...crash.
I made numerous changes to my code to try and find the problem. Nothing. Thanks in advance for any help.</p>

答:
createPool

Just in case this helps anyone in the future...I set up mySQL DB using createConnection instead of createPool. If I am not mistaken, pool dynamically creates connections so that the server does not crash when lots of users connect to it.


问:
How can I push values into nested array with JavaScript?
I have the following code and I'm attempting to push randomly generated numbers into the data array. I'm just not quite sure on how to access the array. I know my code is probably very sloppy and inefficient, but I'm trying my best to learn and got stuck on this. I'd really appreciate any help.</p>
```<code><script>
  var balance = 0;

  function nextDay() {
    var dayCount = 0;
    if (dayCount < 5) {
      randNum = Math.random() * (max - min) + min;
      console.log(randNum);
      max = randNum + 50;
      min = randNum - 50;
      dayCount++;
    }
  }

  function sell() {
    balance = balance + randNum;
    console.log("current balance:" + balance);
    randNum = 0;
    max = randNum + 50;
    min = randNum - 50;
  }

  const startingValues = [];
  function getStartingValues() {
    var max = 100;
    var min = -100;
    for (let startingCount = 0; startingCount < 8; startingCount++) {
      var randNum = Math.random() * (max - min) + min;
      max = randNum + 500;
      min = randNum - 100;
      data.datasets[3].data.push(randNum);
      console.log(startingValues[startingCount]);
    }
  }
  getStartingValues();

  const labels = ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6"];

  const data = {
    labels: labels,
    datasets: [
      {
        label: "graph",
        backgroundColor: "rgb(255, 99, 132)",
        borderColor: "rgb(255, 99, 132)",
        data: [],
      },
    ],
  };

  const config = {
    type: "line",
    data: data,
    options: {},
  };
</script>
</code>```

答: Hello and welcome to stackoverflow Jacob. The issue seems to be at this line of code data.datasets[3].data.push(randNum);. You are accessing the datasets property which has an array as a value. You are trying to access index 3 in this array which does not exist. On closer inspection we realize that the array contains only one element which is an object. So, instead you should be doing this data.datasets[0].data.push(randNum); which allows you to access the first element in the array which is at index 0. I hope that makes sense.


问:
How to tell why a cookie is not being sent?
I'm using chrome and I'm wondering if there is either an extension or a method to tell why a cookie is not being sent.

I have one request I'm making to http://dev/login and it's returning,

```<code>Set-Cookie:DevId=cffbc7e688864b6811f676e181bc29e6; domain=dev; path=/; expires=Tue, 16-Jun-2015 21:27:43 GMT
</code>```

However, on a post to http://dev/Base/User/home/ I'm not sending the DevId cookie. I'd love to know why the cookie isn't being sent if anyone happens to know. But, moreover, I'd love to know how I can tell why and how to better debug this problem in the future.

Here are some requests, as captured from Chrome's Dev tools

So here is my response from /login (notice Set-Cookie header),

```<code>HTTP/1.1 200 OK
Date: Tue, 16 Jun 2015 19:57:43 GMT
Server: Apache
Pragma: no-cache
Cache-control: no-cache, max-age=0
Set-Cookie: DevId=cffbc7e688864b6811f676e181bc29e6; domain=dev; path=/; expires=Tue, 16-Jun-2015 21:27:43 GMT
Cache-Control: max-age=0
Expires: Tue, 16 Jun 2015 19:57:43 GMT
Keep-Alive: timeout=10, max=10
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=ISO-8859-1
</code>```

And here is my post to /Base/User/home/1 (notice no cookie),

```<code>POST /Base/User/home/ HTTP/1.1
Host: dev
Connection: keep-alive
Content-Length: 0
Origin: http://dev
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/43.0.2357.81 Chrome/43.0.2357.81 Safari/537.36
Content-type: application/x-www-form-urlencoded; charset=UTF-8
Accept: text/javascript, text/html, application/xml, text/xml, */*
X-Prototype-Version: 1.7.2
X-Requested-With: XMLHttpRequest
Referer: http://dev/user/1/home
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
</code>```

答:
As of 2022 in Chrome...

In the Developer Tools > Network Tab > Headers > Response you can see why cookies are not set.

Body:
I'm using chrome and I'm wondering if there is either an extension or a method to tell why a cookie is not being sent.

I have one request I'm making to http://dev/login and it's returning,

Set-Cookie:DevId=cffbc7e688864b6811f676e181bc29e6; domain=dev; path=/; expires=Tue, 16-Jun-2015 21:27:43 GMT

However, on a post to http://dev/Base/User/home/ I'm not sending the DevId cookie. I'd love to know why the cookie isn't being sent if anyone happens to know. But, moreover, I'd love to know how I can tell why and how to better debug this problem in the future.

Here are some requests, as captured from Chrome's Dev tools

So here is my response from /login (notice Set-Cookie header),

HTTP/1.1 200 OK
Date: Tue, 16 Jun 2015 19:57:43 GMT
Server: Apache
Pragma: no-cache
Cache-control: no-cache, max-age=0
Set-Cookie: DevId=cffbc7e688864b6811f676e181bc29e6; domain=dev; path=/; expires=Tue, 16-Jun-2015 21:27:43 GMT
Cache-Control: max-age=0
Expires: Tue, 16 Jun 2015 19:57:43 GMT
Keep-Alive: timeout=10, max=10
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=ISO-8859-1

And here is my post to /Base/User/home/1 (notice no cookie),

POST /Base/User/home/ HTTP/1.1
Host: dev
Connection: keep-alive
Content-Length: 0
Origin: http://dev
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/43.0.2357.81 Chrome/43.0.2357.81 Safari/537.36
Content-type: application/x-www-form-urlencoded; charset=UTF-8
Accept: text/javascript, text/html, application/xml, text/xml, */*
X-Prototype-Version: 1.7.2
X-Requested-With: XMLHttpRequest
Referer: http://dev/user/1/home
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8


问:
How to resolve 'getUserByAccount is not a function' in next-auth?
I've updated Nextjs to it's newest version and also updated next-auth and the prisma adapter as specified by the docs.

However, when I try to authenticate in the app with signIn I get the following error with the latest updates:

```<code>[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error getUserByAccount is not a function {
  message: 'getUserByAccount is not a function',
  stack: 'TypeError: getUserByAccount is not a function\n' +
    '    at Object.callback (/home/.../node_modules/next-auth/core/routes/callback.js:81:39)\n' +
    '    at runMicrotasks (<anonymous>)\n' +
    '    at processTicksAndRejections (internal/process/task_queues.js:95:5)\n' +
    '    at async NextAuthHandler (/home/.../node_modules/next-auth/core/index.js:103:28)\n' +
    '    at async NextAuthNextHandler (/home/.../node_modules/next-auth/next/index.js:40:7)\n' +
    '    at async [...]/node_modules/next-auth/next/index.js:80:32\n' +
    '    at async Object.apiResolver (/home/.../node_modules/next/dist/server/api-utils.js:102:9)\n' +
    '    at async DevServer.handleApiRequest (/home/.../node_modules/next/dist/server/next-server.js:1014:9)\n' +
    '    at async Object.fn (/home/.../node_modules/next/dist/server/next-server.js:901:37)\n' +
    '    at async Router.execute (/home/.../node_modules/next/dist/server/router.js:210:32)',
  name: 'TypeError'
}
</code>```

Is there something I'm doing wrong, or is there an incompatibility I'm missing?

Relevant package.json:

```<code>...
    "@next-auth/prisma-adapter": "^0.5.2-next.19",
    "next": "^12.0.3",
    "next-auth": "4.0.0-beta.6",
    "prisma": "^3.4.1",
...
</code>```

[...nextauth].ts:

```<code>import NextAuth from 'next-auth';
import CognitoProvider from 'next-auth/providers/cognito';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    CognitoProvider({
      clientId: process.env.COGNITO_CLIENT_ID,
      clientSecret: process.env.COGNITO_CLIENT_SECRET,
      issuer: process.env.COGNITO_ISSUER,
    }),
  ],

  callbacks: {
    async session({ session, user }) {
      session.userId = user.id;
      session.role = user.role;
      return Promise.resolve(session);
    },
  },
});
</code>```

答:
Finally resolved the problem. Since next-auth has moved to monorepo, updating package was not enough, you need to uninstall it first then install it again.

Run:

```<code>npm uninstall next-auth @next-auth/prisma-adapter
</code>```

then:

```<code>npm install @next-auth/prisma-adapter
</code>```

This fixed it for me.

Body:
I've updated Nextjs to it's newest version and also updated next-auth and the prisma adapter as specified by the docs.

However, when I try to authenticate in the app with signIn I get the following error with the latest updates:

[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error getUserByAccount is not a function {
  message: 'getUserByAccount is not a function',
  stack: 'TypeError: getUserByAccount is not a function\n' +
    '    at Object.callback (/home/.../node_modules/next-auth/core/routes/callback.js:81:39)\n' +
    '    at runMicrotasks (<anonymous>)\n' +
    '    at processTicksAndRejections (internal/process/task_queues.js:95:5)\n' +
    '    at async NextAuthHandler (/home/.../node_modules/next-auth/core/index.js:103:28)\n' +
    '    at async NextAuthNextHandler (/home/.../node_modules/next-auth/next/index.js:40:7)\n' +
    '    at async [...]/node_modules/next-auth/next/index.js:80:32\n' +
    '    at async Object.apiResolver (/home/.../node_modules/next/dist/server/api-utils.js:102:9)\n' +
    '    at async DevServer.handleApiRequest (/home/.../node_modules/next/dist/server/next-server.js:1014:9)\n' +
    '    at async Object.fn (/home/.../node_modules/next/dist/server/next-server.js:901:37)\n' +
    '    at async Router.execute (/home/.../node_modules/next/dist/server/router.js:210:32)',
  name: 'TypeError'
}

Is there something I'm doing wrong, or is there an incompatibility I'm missing?

Relevant package.json:

...
    "@next-auth/prisma-adapter": "^0.5.2-next.19",
    "next": "^12.0.3",
    "next-auth": "4.0.0-beta.6",
    "prisma": "^3.4.1",
...

[...nextauth].ts:

import NextAuth from 'next-auth';
import CognitoProvider from 'next-auth/providers/cognito';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    CognitoProvider({
      clientId: process.env.COGNITO_CLIENT_ID,
      clientSecret: process.env.COGNITO_CLIENT_SECRET,
      issuer: process.env.COGNITO_ISSUER,
    }),
  ],

  callbacks: {
    async session({ session, user }) {
      session.userId = user.id;
      session.role = user.role;
      return Promise.resolve(session);
    },
  },
});

Body:
Finally resolved the problem. Since next-auth has moved to monorepo, updating package was not enough, you need to uninstall it first then install it again.

Run:

npm uninstall next-auth @next-auth/prisma-adapter

then:

npm install @next-auth/prisma-adapter

This fixed it for me.


问:
Sqlite3 datetime and julianDay function's don't recognize midnight hour and minute

sqlite> select datetime('2022-02-10 01:02:03');

2022-02-10 01:02:03

sqlite> select datetime('2022-02-10 0:00:00');

sqlite> select julianDay('2022-02-10 01:02:03');

2459620.54309028

sqlite> select julianDay('2022-02-10 0:00:00');

答: Needs 00 instead of a single 0 for hour.</p>


问:
How can I open a single changeset in TFS from within Visual Studio
Someone emailed me a TFS changeset ID and now I am trying to open this single changeset.  Is there an easy was to do this from within Visual Studio (VS 2008 if it matters)?</p>

答:
You don't need to remember Ctrl + G shortcut, just do as below.

Open the source Control Explorer -> Right Click -> Find in Source Control -> Changeset
Then a dialog box will appear where u can specify your changeset number hit find. And it will appear in results section at the bottom, then you could go into all its details.


问:
How do I convert this code so the functions can take a variable?
I am trying to change the color of nav bar elements when the mouse goes over them.

This piece of code does that but for only the first button:

```<code>let navOne = document.getElementById("nav1");

function mouseOn() {
    nav1.style.color = "red";
}

function mouseOff() {
    nav1.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn);
navOne.addEventListener('mouseout', mouseOff);
</code>```

I have been trying to convert the code so the functions work for multiple buttons, but cannot seem to get it to work. Here is the code so far:

```<code>let navOne = document.getElementById("nav1");

function mouseOn(navButton) {
    navButton.style.color = "red";
}

function mouseOff(navButton) {
    navButton.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn(navOne));
navOne.addEventListener('mouseout', mouseOff(navOne));
</code>```

It has no errors, but does not cause any color change when I move my mouse button over the nav1 element.

Any help is greatly appreciated.

答:
You can have the event handler functions take advantage of the event parameter that is passed in:

function mouseOn(e) {
  e.target.style.color = "red";
}

function mouseOff(e) {
  e.target.style.color = "black";
}

for (let navItem of document.querySelectorAll('nav a')) {
  navItem.addEventListener('mouseover', mouseOn);
  navItem.addEventListener('mouseout', mouseOff);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}</code>```

  Nav One
  Nav Two
```
</div>
</div>
</p>
<p>However, using a css <code>:hover</code> pseudo-attribute would be the preferred approach nowadays. No JS code needed.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}

nav a:hover {
  color: red;
}</code>```

  Nav One
  Nav Two
```

Body:
I am trying to change the color of nav bar elements when the mouse goes over them.

This piece of code does that but for only the first button:

let navOne = document.getElementById("nav1");

function mouseOn() {
    nav1.style.color = "red";
}

function mouseOff() {
    nav1.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn);
navOne.addEventListener('mouseout', mouseOff);

I have been trying to convert the code so the functions work for multiple buttons, but cannot seem to get it to work. Here is the code so far:

let navOne = document.getElementById("nav1");

function mouseOn(navButton) {
    navButton.style.color = "red";
}

function mouseOff(navButton) {
    navButton.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn(navOne));
navOne.addEventListener('mouseout', mouseOff(navOne));

It has no errors, but does not cause any color change when I move my mouse button over the nav1 element.

Any help is greatly appreciated.

Body:
You can have the event handler functions take advantage of the event parameter that is passed in:

function mouseOn(e) {
  e.target.style.color = "red";
}

function mouseOff(e) {
  e.target.style.color = "black";
}

for (let navItem of document.querySelectorAll('nav a')) {
  navItem.addEventListener('mouseover', mouseOn);
  navItem.addEventListener('mouseout', mouseOff);
}

nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}

<nav>
  <a href="#" id="nav1">Nav One</a>
  <a href="#" id="nav2">Nav Two</a>
</nav>

However, using a css :hover pseudo-attribute would be the preferred approach nowadays. No JS code needed.

nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}

nav a:hover {
  color: red;
}

<nav>
  <a href="#">Nav One</a>
  <a href="#">Nav Two</a>
</nav>


问:
Concatenate two string literals
I am reading Accelerated C++ by Koenig. He writes that "the new idea is that we can use + to concatenate a string and a string literal - or, for that matter, two strings (but not two string literals).

Fine, this makes sense I suppose. Now onto two separate exercises meant to illuminate this .

Are the following definitions valid?

```<code>const string hello = "Hello";

const string message = hello + ",world" + "!";
</code>```

Now, I tried to execute the above and it worked! So I was happy.

Then I tried to do the next exercise;

```<code>const string exclam = "!";

const string message = "Hello" + ",world" + exclam;
</code>```

This did not work. Now I understand it has something to do with the fact that you cannot concatenate two string literals, but I don't understand the semantic difference between why I managed to get the first example to work (isn't ",world" and "!" two string literals? Shouldn't this not have worked?) but not the second.

答:
if we write
string s = "hello" + "world!";
RHS has following type
const char [6] + const char [7]

Now both are built in data types.
ie, they are not std::string types any more.

So, now operator overloading of built in types
as defined by compiler applies.
ie - no more operator + overloaded by std::string.

now let us  turn to how compiler overloads

binary operator for two operands of const char * type.

it turns out, compiler did not overload for this case, as it is meaning less.

ie, adding two 'const char *' is semantically wrong as result would be another const char * in run time.
There can be many reason why above does not make sense.

Hence over all, there is one generic rule for any operator overloading. it is :
overloading any operator when all operands of that operator are built-in only. Compiler designers would take of such cases. In our exact question, std::string can't overload two 'const literals'  because of this rule, and compiler choose to not to implement the + binary operator for its meaninglessness.

if we like the string literal form and we can a "s" operator as below.
std::string p = "hello"s + "world!"s;

just suffix with s, the meaning changes.
(s overloaded operator)

Title: Concatenate two string literals

Body:
I am reading Accelerated C++ by Koenig. He writes that "the new idea is that we can use + to concatenate a string and a string literal - or, for that matter, two strings (but not two string literals).

Fine, this makes sense I suppose. Now onto two separate exercises meant to illuminate this .

Are the following definitions valid?

const string hello = "Hello";

const string message = hello + ",world" + "!";

Now, I tried to execute the above and it worked! So I was happy.

Then I tried to do the next exercise;

const string exclam = "!";

const string message = "Hello" + ",world" + exclam;

This did not work. Now I understand it has something to do with the fact that you cannot concatenate two string literals, but I don't understand the semantic difference between why I managed to get the first example to work (isn't ",world" and "!" two string literals? Shouldn't this not have worked?) but not the second.


问:
How to fix 'Tweet' object has no attribute 'retweetCount'
Using snscrape for this example.
With python 3.8 and snscrape 0.3.4

```<code>import snscrape.modules.twitter as sntwitter

keyword = '(COVID19)'

tdf = None

for i, tweet in enumerate(sntwitter.TwitterSearchScraper(keyword + ' since:2021-08-01 lang:pt').get_items()) :

    if i >50:
        break
    print(tweet.date.date())
    print(tweet.retweetCount)
    print(tweet.renderedContent)
</code>```

I get this:

```<code>AttributeError: 'Tweet' object has no attribute 'retweetCount'
</code>```

Thanks for your help.

答:
The Error is with the version of snscrape you are using

Try using -

```<code>!pip install snscrape==0.4.3.20220106
            OR
!pip3 install snscrape==0.4.3.20220106
</code>```

Body:
Using snscrape for this example.
With python 3.8 and snscrape 0.3.4

import snscrape.modules.twitter as sntwitter

keyword = '(COVID19)'

tdf = None

for i, tweet in enumerate(sntwitter.TwitterSearchScraper(keyword + ' since:2021-08-01 lang:pt').get_items()) :

    if i >50:
        break
    print(tweet.date.date())
    print(tweet.retweetCount)
    print(tweet.renderedContent)

I get this:

AttributeError: 'Tweet' object has no attribute 'retweetCount'

Thanks for your help.

Body:
The Error is with the version of snscrape you are using

Try using -

!pip install snscrape==0.4.3.20220106
            OR
!pip3 install snscrape==0.4.3.20220106


问:
Sharing utility objects between domain and repository
I'm currently building a framework that uses a MySQL database. I can't use the MySQL implementation of the entity framework, so I'm trying to figure out the best way of generalising search and paging functionality.

The simplest solution would be to have repository methods with signatures such as:

```<code>IList<Blah> GetSomething(string _query,
                         int _page,
                         int _pageSize,
                         out int _numPages)
</code>```

but this seems slightly anti-OOD.

An idea I had was to create a utility dll with an ISearchParameter and an IPaging object that both the domain level and repository level could access, this would avoid having to recreate these two interfaces and implimentations of them in each domain and repository.

```<code>public interface ISearchParameters
{
    Direction Direction { get; set; }
    string DirectionField { get; set; }
    string Query { get; set; }
    IList<string> SearchFields { get; set; }
}

public interface IPaging
{
    int CurrentPage { get; set; }
    int PageSize { get; set; }
    int NumberOfPages { get; set; }

    int GetQueryPage();
}
</code>```

I'd usually map DTOs from the repositories to domain objects, but if both levels referenced this utility .dll, would it be bad design to pass ISearchParameter objects between these two levels without mapping? If so, are there any better solutions?

答:
In my opinion this is a perfectly suitable solution. In my projects I use jqGrid a lot, which ofcourse also has search, ordering and paging. I use a gridParameters object (defined in my infrastructure layer), which is passed from the controller (UI) to the business layer and the data layer.
The objects don't contain any business rules, so i don't see any problems with this approach.</p>

Body:
I'm currently building a framework that uses a MySQL database. I can't use the MySQL implementation of the entity framework, so I'm trying to figure out the best way of generalising search and paging functionality.

The simplest solution would be to have repository methods with signatures such as:

IList<Blah> GetSomething(string _query,
                         int _page,
                         int _pageSize,
                         out int _numPages)

but this seems slightly anti-OOD.

An idea I had was to create a utility dll with an ISearchParameter and an IPaging object that both the domain level and repository level could access, this would avoid having to recreate these two interfaces and implimentations of them in each domain and repository.

public interface ISearchParameters
{
    Direction Direction { get; set; }
    string DirectionField { get; set; }
    string Query { get; set; }
    IList<string> SearchFields { get; set; }
}

public interface IPaging
{
    int CurrentPage { get; set; }
    int PageSize { get; set; }
    int NumberOfPages { get; set; }

    int GetQueryPage();
}

I'd usually map DTOs from the repositories to domain objects, but if both levels referenced this utility .dll, would it be bad design to pass ISearchParameter objects between these two levels without mapping? If so, are there any better solutions?


问:
how to use enter key after cell edit in DataGridView c#
im trying to go next cell in datagridview after typing in the cell but it go to next row in same Column
** if not typing any thing in cell it working fine
how can solve that</p>
```<code>private void dgvacc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                int row = dgvacc.CurrentCell.RowIndex;
                int col = dgvacc.CurrentCell.ColumnIndex;

                try
                {
                    if (col < dgvacc.Columns.Count - 1)
                    {
                        dgvacc.CurrentCell = dgvacc.Rows[row -1].Cells[col + 1];
                        dgvacc.Focus();
                    }
                    else if (col == dgvacc.Columns.Count - 1)
                    {

                        dgvacc.CurrentCell = dgvacc.Rows[row].Cells[0];
                        dgvacc.Focus();
                    }
                }
                catch (Exception)
                {

                }
            }

        }

</code>```

答:
thanks for all
i found the the answer and it solve it - thanks again</p>
```<code>private DataGridViewCell dgvEndEditCell;
        private bool _EnterMoveNext = true;

        [System.ComponentModel.DefaultValue(true)]
        public bool OnEnterKeyMoveNext
        {
            get
            {
                return this._EnterMoveNext;
            }
            set
            {
                this._EnterMoveNext = value;
            }
        }

private void dgvacc_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                int iColumn = dgvacc.CurrentCell.ColumnIndex;
                int iRow = dgvacc.CurrentCell.RowIndex;
                if (iColumn == dgvacc.Columns.Count - 1 && iRow != dgvacc.Rows.Count - 1)
                {
                    dgvacc.CurrentCell = dgvacc[0, iRow + 1];
                }
                else if (iColumn == dgvacc.Columns.Count - 1 && iRow == dgvacc.Rows.Count - 1)
                {
                }
                else
                {
                    dgvacc.CurrentCell = dgvacc[iColumn + 1, iRow];
                }
            }

        }

private void dgvacc_SelectionChanged(object sender, EventArgs e)
        {
            if (this._EnterMoveNext && MouseButtons == 0)
            {
                if (this.dgvEndEditCell != null && dgvacc.CurrentCell != null)
                {
                    if (dgvacc.CurrentCell.RowIndex == this.dgvEndEditCell.RowIndex + 1
                        && dgvacc.CurrentCell.ColumnIndex == this.dgvEndEditCell.ColumnIndex)
                    {
                        int iColNew;
                        int iRowNew;
                        if (this.dgvEndEditCell.ColumnIndex >= dgvacc.ColumnCount - 1)
                        {
                            iColNew = 0;
                            iRowNew = dgvacc.CurrentCell.RowIndex;
                        }
                        else
                        {
                            iColNew = this.dgvEndEditCell.ColumnIndex + 1;
                            iRowNew = this.dgvEndEditCell.RowIndex;
                        }
                        dgvacc.CurrentCell = dgvacc[iColNew, iRowNew];
                    }
                }
                this.dgvEndEditCell = null;
            }

        }

</code>```

Body:
im trying to go next cell in datagridview after typing in the cell but it go to next row in same Column
** if not typing any thing in cell it working fine
how can solve that

private void dgvacc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                int row = dgvacc.CurrentCell.RowIndex;
                int col = dgvacc.CurrentCell.ColumnIndex;

                try
                {
                    if (col < dgvacc.Columns.Count - 1)
                    {
                        dgvacc.CurrentCell = dgvacc.Rows[row -1].Cells[col + 1];
                        dgvacc.Focus();
                    }
                    else if (col == dgvacc.Columns.Count - 1)
                    {

                        dgvacc.CurrentCell = dgvacc.Rows[row].Cells[0];
                        dgvacc.Focus();
                    }
                }
                catch (Exception)
                {

                }
            }

        }

Body:
thanks for all
i found the the answer and it solve it - thanks again

private DataGridViewCell dgvEndEditCell;
        private bool _EnterMoveNext = true;

        [System.ComponentModel.DefaultValue(true)]
        public bool OnEnterKeyMoveNext
        {
            get
            {
                return this._EnterMoveNext;
            }
            set
            {
                this._EnterMoveNext = value;
            }
        }

private void dgvacc_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                int iColumn = dgvacc.CurrentCell.ColumnIndex;
                int iRow = dgvacc.CurrentCell.RowIndex;
                if (iColumn == dgvacc.Columns.Count - 1 && iRow != dgvacc.Rows.Count - 1)
                {
                    dgvacc.CurrentCell = dgvacc[0, iRow + 1];
                }
                else if (iColumn == dgvacc.Columns.Count - 1 && iRow == dgvacc.Rows.Count - 1)
                {
                }
                else
                {
                    dgvacc.CurrentCell = dgvacc[iColumn + 1, iRow];
                }
            }

        }

private void dgvacc_SelectionChanged(object sender, EventArgs e)
        {
            if (this._EnterMoveNext && MouseButtons == 0)
            {
                if (this.dgvEndEditCell != null && dgvacc.CurrentCell != null)
                {
                    if (dgvacc.CurrentCell.RowIndex == this.dgvEndEditCell.RowIndex + 1
                        && dgvacc.CurrentCell.ColumnIndex == this.dgvEndEditCell.ColumnIndex)
                    {
                        int iColNew;
                        int iRowNew;
                        if (this.dgvEndEditCell.ColumnIndex >= dgvacc.ColumnCount - 1)
                        {
                            iColNew = 0;
                            iRowNew = dgvacc.CurrentCell.RowIndex;
                        }
                        else
                        {
                            iColNew = this.dgvEndEditCell.ColumnIndex + 1;
                            iRowNew = this.dgvEndEditCell.RowIndex;
                        }
                        dgvacc.CurrentCell = dgvacc[iColNew, iRowNew];
                    }
                }
                this.dgvEndEditCell = null;
            }

        }