来源: stackexchange

问:
Php for each data to display in a comma seperated list with no space
Currently i am displaying id's of users to display in a single line with a comma delimiter, the problem is it is having unwanted space between comma's

Showing like this
1, 6, 10

Should be like this
1,6,10

<?php foreach ( $students as $student ) {

          $process = '';
          $result = 0;
          $student = learn_press_get_user( $student->ID );
          $data = $student->get_course_data($course->get_id());
          $status = $student->get_course_status($course->get_id());
          $result = $data->get_results();
   ?>

  <?php if ( $status ) {
  $process = ( $status == 'finished' ) ? 'finished' : 'in-progress';
  } ?>

       <?php echo $student->get_id(); ?>,
        <?php } ?>

```

答:
Last php tag over closing div, has a space before it.

```<code> <?php } ?>
</code>```

Try writing loop within one php snippet.

ContentLicense: CC BY-SA 4.0

Body:
Last php tag over closing div, has a space before it.

 <?php } ?>

Try writing loop within one php snippet.


问:
DJI Windows SDK - Example code is not retrieving files on the SDK
I am using the latest version of Windows SDK and connecting with Mavic 2 Pro, which has been updated to latest firmware. I have plugged on the Mavic a Lexar MicroSD of 16GB and 633x.

I am able to run the example code an connect to the Drone and get name, velocity updates and video. However when I try to get the files on the drone, using the playback. when I am on the play back window, I set the workmode button is on green, which checking on the variables is set on TRANSCODE mode. Then I click on Reload button and I get the messages REQUEST_TIMEOUT: The image

I have tried also with a SanDisk MicroSD of 32GB Ultra with same results. I have debug the code and seen that the function is called.

答:
There are few possibilities

Here is a checklist, cross them out 1 by 1 to rule out the issue.
Here is a checklist, cross them out 1 by 1 to rule out the issue.

USB Authority Configuration in UWP

Connection sequence
Make sure that before connecting using your cable, your P4P V2.0 remote controller is off.

Connect the remote controller to your computer using Micro-USB cable.

Turn on your remote controller.

Make sure you have not open the DJI software like DJI Assistant 2.

DJI Windows SDK Applications are not able to communicate with the aircrafts at the same time.

3 Make sure that you have installed DJI Assistant 2 and have enabled all the driver intallation while installing DJI Assistant 2.

4 WinUSB Driver

5 Make sure all dll are in the correct place e.g. DJIwindowsSDK.dll pthread_dll.dll and libcrypto-1.1.dll

6 Make sure the account that used for App Key registration is same as DJI app account

If you still cant solve it by then, send your question and your attempts to dev@dji.com for help. If you know someone in DJI or you have a premium support account, you can get faster respond(within 24 hours)


问:
Numpy - Raise negative elements to non-integer power
```<code>import numpy as np
from scipy import stats

np.random.seed(42)
data = sorted(stats.norm.rvs(size=1000))
</code>```

I want to raise data to the power of 3/4.

I tried:

```<code>np.power(data, 3/4) # doesn't work because power is not integer
np.float_power(data, 3/4) # returns nan for negative elements
scipy.linalg.fractional_matrix_power(data, 3/4) # doesn't work because data is 1D array, not matrix
</code>```

How can I do this using numpy?

答:
```<code>np.power(data, 3./4)
</code>```

will result in a float for the power. Since 3/4 will return an int.

Body:
import numpy as np
from scipy import stats

np.random.seed(42)
data = sorted(stats.norm.rvs(size=1000))

I want to raise data to the power of 3/4.

I tried:

np.power(data, 3/4) # doesn't work because power is not integer
np.float_power(data, 3/4) # returns nan for negative elements
scipy.linalg.fractional_matrix_power(data, 3/4) # doesn't work because data is 1D array, not matrix

How can I do this using numpy?

Body:
np.power(data, 3./4)

will result in a float for the power. Since 3/4 will return an int.


问:
Make table automatically update row
I have a database with the following columns:

```<code>CurrentCredits, CreditsPerDate, RefillDate, RefillFrequency, RefillDayMonth
</code>```

I'd like to make it automatically update the CreditsPerDate and RefillDate depending on the frequency selected.

For example,

```<code>if RefillFrequency = 5 and RefillDayMonth = "day" and CreditsPerMonth = 2
</code>```

I want it to update CurrentCredits and RefillDate every 5 days such that

```<code>CurrentCredits = CurrentCredits + CreditsPerMonth and
RefillDate = RefillDate + the frequency date (here add 5 days)
</code>```

答:
Did you try with a SQL job?. Here you have an example: how to schedule a job for sql query

Inside your job you can create a update or command with stored procedure like

```<code>exec (your stored procedure name) (and possibly add parameters)
</code>```

just updating your parameters and values.

Let us know if this helps.

Regards.

Title: Make table automatically update row

Body:
I have a database with the following columns:

CurrentCredits, CreditsPerDate, RefillDate, RefillFrequency, RefillDayMonth

I'd like to make it automatically update the CreditsPerDate and RefillDate depending on the frequency selected.

For example,

if RefillFrequency = 5 and RefillDayMonth = "day" and CreditsPerMonth = 2

I want it to update CurrentCredits and RefillDate every 5 days such that

CurrentCredits = CurrentCredits + CreditsPerMonth and
RefillDate = RefillDate + the frequency date (here add 5 days)

Body:
Did you try with a SQL job?. Here you have an example: how to schedule a job for sql query

Inside your job you can create a update or command with stored procedure like

exec (your stored procedure name) (and possibly add parameters)

just updating your parameters and values.

Let us know if this helps.

Regards.


问:
can't bind to port 8080 with traefik's dashboard
I have the following traefik config file:

```<code>debug = true
logLevel = "DEBUG"

[entryPoints]
  [entryPoints.http]
    address = ":80"
    compress = true

  [entryPoints.dashboard]
    address=":81"
    [entryPoints.dashboard.auth]
      [entryPoints.dashboard.auth.basic]
        users = [
          "admin:-------"
        ]

[traefikLog]

[accessLog]

[api]
dashboard = true
entryPoint = "dashboard"

[ping]

[docker]
</code>```

and the following routing in docker-compose:

```<code>- ‘5080:80’
- ‘5443:443’
- ‘5000:81’
</code>```

this works as exepected and the dashboard is accessible from the outside on port 5000.

The problem arises when I change the dashboard port to 8080 and reflect it in the mapping ('5000:8080')

I get the following errors:

```<code>level=error msg="Error opening listener listen tcp :8080: bind: address already in use"
level=fatal msg="Error preparing server: listen tcp :8080: bind: address already in use"
</code>```

The problem is that I don't see 8080 being in use:

```<code>[root@ns3106050 ~]# lsof -i -P -n | grep LISTEN
sshd      1276   root    3u  IPv4    515      0t0  TCP *:22 (LISTEN)
sshd      1276   root    4u  IPv6    517      0t0  TCP *:22 (LISTEN)
dockerd   1277   root    6u  IPv6   5955      0t0  TCP *:2376 (LISTEN)
docker-pr 5425   root    4u  IPv6  24484      0t0  TCP *:5443 (LISTEN)
docker-pr 5436   root    4u  IPv6  24492      0t0  TCP *:5000 (LISTEN)
docker-pr 5447   root    4u  IPv6  22391      0t0  TCP *:5080 (LISTEN)
</code>```

what could I have missed?

答: Make sure you don't have --api flag specified for traefik command in docker-compose file. CLI and toml configurations don't work together.

Body:
I have the following traefik config file:

debug = true
logLevel = "DEBUG"

[entryPoints]
  [entryPoints.http]
    address = ":80"
    compress = true

  [entryPoints.dashboard]
    address=":81"
    [entryPoints.dashboard.auth]
      [entryPoints.dashboard.auth.basic]
        users = [
          "admin:-------"
        ]

[traefikLog]

[accessLog]

[api]
dashboard = true
entryPoint = "dashboard"

[ping]

[docker]

and the following routing in docker-compose:

- ‘5080:80’
- ‘5443:443’
- ‘5000:81’

this works as exepected and the dashboard is accessible from the outside on port 5000.

The problem arises when I change the dashboard port to 8080 and reflect it in the mapping ('5000:8080')

I get the following errors:

level=error msg="Error opening listener listen tcp :8080: bind: address already in use"
level=fatal msg="Error preparing server: listen tcp :8080: bind: address already in use"

The problem is that I don't see 8080 being in use:

[root@ns3106050 ~]# lsof -i -P -n | grep LISTEN
sshd      1276   root    3u  IPv4    515      0t0  TCP *:22 (LISTEN)
sshd      1276   root    4u  IPv6    517      0t0  TCP *:22 (LISTEN)
dockerd   1277   root    6u  IPv6   5955      0t0  TCP *:2376 (LISTEN)
docker-pr 5425   root    4u  IPv6  24484      0t0  TCP *:5443 (LISTEN)
docker-pr 5436   root    4u  IPv6  24492      0t0  TCP *:5000 (LISTEN)
docker-pr 5447   root    4u  IPv6  22391      0t0  TCP *:5080 (LISTEN)

what could I have missed?


答:
There is no need to call, say, np.power explicitly; by performing your computations before using sorted (or even using np.sort instead), we can just use operators:

```<code>np.sort(data ** (3 / 4))
</code>```

Necessarily, this will give nan values because a root of a negative number will be complex, and your array can only handle floats.

The solution is therefore to cast it to dtype np.complex:

```<code>data = np.sort(stats.norm.rvs(size=10).astype(np.complex) ** (3 / 4))
print(data)
</code>```

Output:

```<code>[-1.18840462+1.18840462j -0.10707968+0.10707968j -0.09787584+0.09787584j
 -0.05992208+0.05992208j  0.10880864+0.j          0.1484953 +0.j
  0.45161317+0.j          0.78783041+0.j          0.79189574+0.j
  0.93656538+0.j        ]
</code>```

Title: Numpy - Raise negative elements to non-integer power

Body:
There is no need to call, say, np.power explicitly; by performing your computations before using sorted (or even using np.sort instead), we can just use operators:

np.sort(data ** (3 / 4))

Necessarily, this will give nan values because a root of a negative number will be complex, and your array can only handle floats.

The solution is therefore to cast it to dtype np.complex:

data = np.sort(stats.norm.rvs(size=10).astype(np.complex) ** (3 / 4))
print(data)

Output:

[-1.18840462+1.18840462j -0.10707968+0.10707968j -0.09787584+0.09787584j
 -0.05992208+0.05992208j  0.10880864+0.j          0.1484953 +0.j
  0.45161317+0.j          0.78783041+0.j          0.79189574+0.j
  0.93656538+0.j        ]


问:
Update, select atomic. GORM ORM
Can I do something like this in gorm , psql?

UPDATE job SET status = 'RUNNING' WHERE status = 'PENDING' RETURNING *
```

I want to get all rows that were changed by the update with a single atomic operation. If there are other solutions please write it.

答:
It's possible having only a little downside as far as I know

Assuming your model is called Job, you can do something like this...

var jobs []Job
db.Find(&jobs).Where("status = ?", StatusPending).Update("status", StatusRunning)
```

The lines affect will be in the jobs var, but I have to say that you will receive the lines how they were BEFORE the Update, so the status of the models will be 'PENDING'

Title: Update, select atomic. GORM ORM

Body:
Can I do something like this in gorm , psql?

UPDATE job SET status = 'RUNNING' WHERE status = 'PENDING' RETURNING *

I want to get all rows that were changed by the update with a single atomic operation. If there are other solutions please write it.

Body:
It's possible having only a little downside as far as I know

Assuming your model is called Job, you can do something like this...

var jobs []Job
db.Find(&jobs).Where("status = ?", StatusPending).Update("status", StatusRunning)

The lines affect will be in the jobs var, but I have to say that you will receive the lines how they were BEFORE the Update, so the status of the models will be 'PENDING'


问:
Sorting JSON array by date value stopping after one iteration
So i'm trying to sort a JSON array by the date key, currently the problem seems to be the function stops after one sort (or just is plain wrong).

The following is my sort js

```<code>  function sortByDate() {
        result = gloresult
        var newA = result.sort(function(a,b){
          return Number(new Date(a.Date)) - Number(new Date(b.Date));
        });

       console.log(newA)

      }
</code>```

Input Json file

```<code>gloresult = [
    {
        "Heading": "A",
        "Topic A": "Ball Valve",
        "Date": "2/05/2019"
    },
    {
        "Heading": "B",
        "Topic A": "ABS",
        "Date": "1/05/2019"
    },
    {
        "Heading": "C",
        "Topic A": "Acrylic",
        "Date": "21/05/2019"
    },
    {
        "Heading": "D",
        "Topic A": "Adaptor Fitting",
        "Date": "21/05/2019"
    },
    {
        "Heading": "E",
        "Topic A": "Air Gap",
        "Date": "4/05/2019"
    },
    {
        "Heading": "F",
        "Topic A": "Stuff",
        "Date": "21/03/2019"
    },
    {
        "Heading": "G",
        "Topic A": "Stuff",
        "Date": "21/04/2019"
    },
    {
        "Heading": "H",
        "Topic A": "Stuff",
        "Date": "21/05/2021"
    }

]
</code>```

Output Json file

```<code>[
    {
        "Heading": "B",
        "Topic A": "ABS",
        "Date": "1/05/2019"

    },
    {
        "Heading": "A",
        "Topic A": "Ball Valve",
        "Date": "2/05/2019"

    },
    {
        "Heading": "C",
        "Topic A": "Acrylic",
        "Date": "21/05/2010"

    },
    {
        "Heading": "D",
        "Topic A": "Adaptor Fitting",
        "Date": "21/05/2019"

    },
    {
        "Heading": "E",
        "Topic A": "Air Gap",
        "Date": "4/05/2019"

    },
    {
        "Heading": "F",
        "Topic A": "Stuff",
        "Date": "21/03/2019"

    },
    {
        "Heading": "G",
        "Topic A": "Stuff",
        "Date": "21/04/2019"

    },
    {
        "Heading": "H",
        "Topic A": "Stuff",
        "Date": "21/05/2021"
    }
]
</code>```

As you can see only A and B have changed places and the result have remained completely the same. I'm not sure if this is because i'm calling the function when a user selects a button on a html page.

答:
It was a little tricky, but it's works !

var
  gloresult = [ { "Heading": "A", "Topic A": "Ball Valve",      "Date": "2/05/2019"   }
              , { "Heading": "B", "Topic A": "ABS",             "Date": "1/05/2019"   }
              , { "Heading": "C", "Topic A": "Acrylic",         "Date": "21/05/2019"  }
              , { "Heading": "D", "Topic A": "Adaptor Fitting", "Date": "21/05/2019"  }
              , { "Heading": "E", "Topic A": "Air Gap",         "Date": "4/05/2019"   }
              , { "Heading": "F", "Topic A": "Stuff",           "Date": "21/03/2019"  }
              , { "Heading": "G", "Topic A": "Stuff",           "Date": "21/04/2019"  }
              , { "Heading": "H", "Topic A": "Stuff",           "Date": "21/05/2021"  }
              ];

gloresult.sort((a, b)=>{
  let
    aa = a.Date.split('/').reverse().map(d=>('0000'+d).slice(-4)).join('-'),
    bb = b.Date.split('/').reverse().map(d=>('0000'+d).slice(-4)).join('-');
  return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

// for (let x of gloresult ) console.log ( x.Date );
for (let x of gloresult ) console.log ( JSON.stringify( x ) );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Body:
So i'm trying to sort a JSON array by the date key, currently the problem seems to be the function stops after one sort (or just is plain wrong).

The following is my sort js

  function sortByDate() {
        result = gloresult
        var newA = result.sort(function(a,b){
          return Number(new Date(a.Date)) - Number(new Date(b.Date));
        });

       console.log(newA)

      }

Input Json file

gloresult = [
    {
        "Heading": "A",
        "Topic A": "Ball Valve",
        "Date": "2/05/2019"
    },
    {
        "Heading": "B",
        "Topic A": "ABS",
        "Date": "1/05/2019"
    },
    {
        "Heading": "C",
        "Topic A": "Acrylic",
        "Date": "21/05/2019"
    },
    {
        "Heading": "D",
        "Topic A": "Adaptor Fitting",
        "Date": "21/05/2019"
    },
    {
        "Heading": "E",
        "Topic A": "Air Gap",
        "Date": "4/05/2019"
    },
    {
        "Heading": "F",
        "Topic A": "Stuff",
        "Date": "21/03/2019"
    },
    {
        "Heading": "G",
        "Topic A": "Stuff",
        "Date": "21/04/2019"
    },
    {
        "Heading": "H",
        "Topic A": "Stuff",
        "Date": "21/05/2021"
    }

]

Output Json file

[
    {
        "Heading": "B",
        "Topic A": "ABS",
        "Date": "1/05/2019"

    },
    {
        "Heading": "A",
        "Topic A": "Ball Valve",
        "Date": "2/05/2019"

    },
    {
        "Heading": "C",
        "Topic A": "Acrylic",
        "Date": "21/05/2010"

    },
    {
        "Heading": "D",
        "Topic A": "Adaptor Fitting",
        "Date": "21/05/2019"

    },
    {
        "Heading": "E",
        "Topic A": "Air Gap",
        "Date": "4/05/2019"

    },
    {
        "Heading": "F",
        "Topic A": "Stuff",
        "Date": "21/03/2019"

    },
    {
        "Heading": "G",
        "Topic A": "Stuff",
        "Date": "21/04/2019"

    },
    {
        "Heading": "H",
        "Topic A": "Stuff",
        "Date": "21/05/2021"
    }
]

As you can see only A and B have changed places and the result have remained completely the same. I'm not sure if this is because i'm calling the function when a user selects a button on a html page.

Body:
It was a little tricky, but it's works !

var
  gloresult = [ { "Heading": "A", "Topic A": "Ball Valve",      "Date": "2/05/2019"   }
              , { "Heading": "B", "Topic A": "ABS",             "Date": "1/05/2019"   }
              , { "Heading": "C", "Topic A": "Acrylic",         "Date": "21/05/2019"  }
              , { "Heading": "D", "Topic A": "Adaptor Fitting", "Date": "21/05/2019"  }
              , { "Heading": "E", "Topic A": "Air Gap",         "Date": "4/05/2019"   }
              , { "Heading": "F", "Topic A": "Stuff",           "Date": "21/03/2019"  }
              , { "Heading": "G", "Topic A": "Stuff",           "Date": "21/04/2019"  }
              , { "Heading": "H", "Topic A": "Stuff",           "Date": "21/05/2021"  }
              ];

gloresult.sort((a, b)=>{
  let
    aa = a.Date.split('/').reverse().map(d=>('0000'+d).slice(-4)).join('-'),
    bb = b.Date.split('/').reverse().map(d=>('0000'+d).slice(-4)).join('-');
  return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

// for (let x of gloresult ) console.log ( x.Date );
for (let x of gloresult ) console.log ( JSON.stringify( x ) );

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
A memory-efficient SHA1 implementation
I'm working with a very restrictive embedded processor, which only has 128 bytes of ram. I'd like to implement SHA1 on it. RFC3174 describes, in 'method 2', a way of implementing SHA1 that doesn't require allocating an array of 80 32-bit words (which, at 320 bytes, is obviously not practical), and seems like it ought to be usable on my processor. I'm unable to find any implementations of 'method 2', though, and the sample code in the RFC only implements the default method.

Is anyone aware of a memory-efficient implementation of SHA1 in C or C++?

答:
I have implemented SHA-1 for several memory-constrained environments. You can get by with

```<code>DWORD W[16] ;        // instead of H[80]
DWORD H[5] ;         // Intermediate hash value
DWORD BitCount[2] ;  // Probably a single DWORD is enough here
</code>```

plus a few bytes of housekeeping. W is updated on the fly, as a circular buffer, instead of being generated at the start of each round.

ContentLicense: CC BY-SA 3.0

Title: A memory-efficient SHA1 implementation

Body:
I have implemented SHA-1 for several memory-constrained environments. You can get by with

DWORD W[16] ;        // instead of H[80]
DWORD H[5] ;         // Intermediate hash value
DWORD BitCount[2] ;  // Probably a single DWORD is enough here

plus a few bytes of housekeeping. W is updated on the fly, as a circular buffer, instead of being generated at the start of each round.


问:
How to use custom functional components within Material-UI Menu
I am using Material-UI to design a react app that I'm building. I am trying to use my own custom functional component inside the <Menu> component and I'm getting a strange error:

```<code>Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?

Check the render method of ForwardRef(Menu).
    in TextDivider (at Filter.js:32)
</code>```

The JSX where this occurs looks like this: (Line 32 is the TextDivider component)

```<code><Menu>
    <TextDivider text="Filter Categories" />
    <MenuItem>...</MenuItem>
</Menu>
</code>```

Where TextDivider is:

```<code>const TextDivider = ({ text }) => {
    const [width, setWidth] = useState(null);
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };

    const hrStyle = {
        width: `calc(100% - ${width}px)`,
        marginRight: 0,
        marginLeft: 0
    };

    const spanStyle = {
        color: '#555',
        whiteSpace: 'nowrap'
    };

    const ref = createRef();
    useEffect(() => {
        if (ref.current) {
            const width = ref.current.getBoundingClientRect().width + 35;
            console.log('width', width);
            setWidth(width);
        }
    }, [ref.current]);

    return (
        <div style={style}>
            <span ref={ref} style={spanStyle}>{ text }</span>
            <Divider className="divider-w-text" style={ hrStyle }/>
        </div>
    );
};
</code>```

The strange part is that this component renders perfectly fine when set by itself in a regular container, but it seems to throw this error only when being rendered inside the <Menu> component.

Furthermore, I found it really strange that this error goes away completely if I just wrap TextDivider in a div like so:

```<code><Menu>
    <div>
        <TextDivider text="Filter Categories" />
    </div>
    <MenuItem>...</MenuItem>
</Menu>
</code>```

However, this feels like duct tape to me, and I'd rather understand the underlying problem of why I can't just render this component within the Menu. I'm not using any kind of Material-UI ref within my functional component and I'm not placing a ref on the <Divider> component within my <TextDivider> component so I don't understand why it's throwing this error.

Any insight into why this behavior is happening would be greatly appreciated.

I've tried using the useCallback hook, createRef(), useRef(), and read everything I could find on using hooks within a functional component. The error itself seems misleading because even the react docs themselves show using functional components refs here: https://reactjs.org/docs/hooks-reference.html#useref

答:
Menu uses the first child of the Menu as the "content anchor" for the Popover component used internally by Menu. The "content anchor" is the DOM element within the menu that Popover attempts to line up with the anchor element (the element outside of the menu that is the reference point for positioning the menu).

In order to leverage the first child as the content anchor, Menu adds a ref to it (using cloneElement). In order to not get the error you received (and for the positioning to work correctly), your function component needs to forward the ref to one of the components it renders (generally the outermost component — a div in your case).

When you use a div as the direct child of Menu, you don’t get the error because the div can receive a ref successfully.

The documentation SakoBu referred to contains details about how to forward refs to function components.

The result should look something like the following (but I’m answering this on my phone, so sorry if any syntax errors):

```<code>const TextDivider = React.forwardRef(({ text }, ref) => {
    const [width, setWidth] = useState(null);
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };

    const hrStyle = {
        width: `calc(100% - ${width}px)`,
        marginRight: 0,
        marginLeft: 0
    };

    const spanStyle = {
        color: '#555',
        whiteSpace: 'nowrap'
    };
    // Separate bug here.
    // This should be useRef instead of createRef.
    // I’ve also renamed this ref for clarity, and used "ref" for the forwarded ref.
    const spanRef = React.useRef();
    useEffect(() => {
        if (spanRef.current) {
            const width = spanRef.current.getBoundingClientRect().width + 35;
            console.log('width', width);
            setWidth(width);
        }
    }, [spanRef.current]);

    return (
        <div ref={ref} style={style}>
            <span ref={spanRef} style={spanStyle}>{ text }</span>
            <Divider className="divider-w-text" style={ hrStyle }/>
        </div>
    );
});
</code>```

You may also find the following answer useful:

What's the difference between `useRef` and `createRef`?

Body:
I am using Material-UI to design a react app that I'm building. I am trying to use my own custom functional component inside the <Menu> component and I'm getting a strange error:

Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?

Check the render method of ForwardRef(Menu).
    in TextDivider (at Filter.js:32)

The JSX where this occurs looks like this: (Line 32 is the TextDivider component)

<Menu>
    <TextDivider text="Filter Categories" />
    <MenuItem>...</MenuItem>
</Menu>

Where TextDivider is:

const TextDivider = ({ text }) => {
    const [width, setWidth] = useState(null);
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };

    const hrStyle = {
        width: `calc(100% - ${width}px)`,
        marginRight: 0,
        marginLeft: 0
    };

    const spanStyle = {
        color: '#555',
        whiteSpace: 'nowrap'
    };

    const ref = createRef();
    useEffect(() => {
        if (ref.current) {
            const width = ref.current.getBoundingClientRect().width + 35;
            console.log('width', width);
            setWidth(width);
        }
    }, [ref.current]);

    return (

            { text }
            <Divider className="divider-w-text" style={ hrStyle }/>

    );
};

The strange part is that this component renders perfectly fine when set by itself in a regular container, but it seems to throw this error only when being rendered inside the <Menu> component.

Furthermore, I found it really strange that this error goes away completely if I just wrap TextDivider in a div like so:

<Menu>

        <TextDivider text="Filter Categories" />

    <MenuItem>...</MenuItem>
</Menu>

However, this feels like duct tape to me, and I'd rather understand the underlying problem of why I can't just render this component within the Menu. I'm not using any kind of Material-UI ref within my functional component and I'm not placing a ref on the <Divider> component within my <TextDivider> component so I don't understand why it's throwing this error.

Any insight into why this behavior is happening would be greatly appreciated.

I've tried using the useCallback hook, createRef(), useRef(), and read everything I could find on using hooks within a functional component. The error itself seems misleading because even the react docs themselves show using functional components refs here: https://reactjs.org/docs/hooks-reference.html#useref

Body:
Menu uses the first child of the Menu as the "content anchor" for the Popover component used internally by Menu. The "content anchor" is the DOM element within the menu that Popover attempts to line up with the anchor element (the element outside of the menu that is the reference point for positioning the menu).

In order to leverage the first child as the content anchor, Menu adds a ref to it (using cloneElement). In order to not get the error you received (and for the positioning to work correctly), your function component needs to forward the ref to one of the components it renders (generally the outermost component — a div in your case).

When you use a div as the direct child of Menu, you don’t get the error because the div can receive a ref successfully.

The documentation SakoBu referred to contains details about how to forward refs to function components.

The result should look something like the following (but I’m answering this on my phone, so sorry if any syntax errors):

const TextDivider = React.forwardRef(({ text }, ref) => {
    const [width, setWidth] = useState(null);
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };

    const hrStyle = {
        width: `calc(100% - ${width}px)`,
        marginRight: 0,
        marginLeft: 0
    };

    const spanStyle = {
        color: '#555',
        whiteSpace: 'nowrap'
    };
    // Separate bug here.
    // This should be useRef instead of createRef.
    // I’ve also renamed this ref for clarity, and used "ref" for the forwarded ref.
    const spanRef = React.useRef();
    useEffect(() => {
        if (spanRef.current) {
            const width = spanRef.current.getBoundingClientRect().width + 35;
            console.log('width', width);
            setWidth(width);
        }
    }, [spanRef.current]);

    return (
        <div ref={ref} style={style}>
            <span ref={spanRef} style={spanStyle}>{ text }</span>
            <Divider className="divider-w-text" style={ hrStyle }/>
        </div>
    );
});

You may also find the following answer useful:

What's the difference between `useRef` and `createRef`?


问:
SQLAlchemy / Alembic raw SQL for adding index
I'd like to use the following raw SQL to create an index in PostgreSQL:

```<code>CREATE INDEX ix_action_date ON events_map ((action ->> 'action'), date, map_id);
</code>```

I tried to put this line into the model class's __table_args__ part, but I couldn't. Then I simply solved it by using raw SQL in Alembic migration.

```<code>conn = op.get_bind()
conn.execute(text("CREATE INDEX ..."))
</code>```

and just using a dummy index in __table_args__ like:

```<code>Index('ix_action_date')
</code>```

My only problem is that Alembic doesn't accept the dummy index with the same name, and every time I run a revision --autogenerate, it tells me the following:

```<code>SAWarning: Skipped unsupported reflection of expression-based index ix_action_date
  % idx_name)
</code>```

and then it adds the autogenerated index to the migration file:

```<code>op.create_index('ix_action_date', 'events_map', [], unique=False)
</code>```

My question is:

How can I write raw SQL into a __table_args__ Index?

How can I really make my dummy index concept work ? I mean an index which is only compared by name?

答:
How can I write raw SQL into a __table_args__ Index?

To specify formula indexes, you have to provide a text element for the expression

example:

```<code>class EventsMap(Base):
    __tablename__ = 'events_map'
    __table_args__ = (Index('ix_action_date', text("(action->>'action'), date, map_id")),)
    map_id = Column(Integer, primary_key=True)
    date = Column(DateTime)
    action = Column(JSONB)
</code>```

How can I really make my dummy index concept work ? I mean an index which is only compared by name?

It seems unnecessary to make your dummy index concept work. Either specify the full index expression in the __table_args__ as I've shown above, or omit it completely from the model & delegate index creation as a database migration handled by sqlalchemy.

Body:
I'd like to use the following raw SQL to create an index in PostgreSQL:

CREATE INDEX ix_action_date ON events_map ((action ->> 'action'), date, map_id);

I tried to put this line into the model class's __table_args__ part, but I couldn't. Then I simply solved it by using raw SQL in Alembic migration.

conn = op.get_bind()
conn.execute(text("CREATE INDEX ..."))

and just using a dummy index in __table_args__ like:

Index('ix_action_date')

My only problem is that Alembic doesn't accept the dummy index with the same name, and every time I run a revision --autogenerate, it tells me the following:

SAWarning: Skipped unsupported reflection of expression-based index ix_action_date
  % idx_name)

and then it adds the autogenerated index to the migration file:

op.create_index('ix_action_date', 'events_map', [], unique=False)

My question is:

How can I write raw SQL into a __table_args__ Index?

How can I really make my dummy index concept work ? I mean an index which is only compared by name?

Body:
How can I write raw SQL into a __table_args__ Index?

To specify formula indexes, you have to provide a text element for the expression

example:

class EventsMap(Base):
    __tablename__ = 'events_map'
    __table_args__ = (Index('ix_action_date', text("(action->>'action'), date, map_id")),)
    map_id = Column(Integer, primary_key=True)
    date = Column(DateTime)
    action = Column(JSONB)

How can I really make my dummy index concept work ? I mean an index which is only compared by name?

It seems unnecessary to make your dummy index concept work. Either specify the full index expression in the __table_args__ as I've shown above, or omit it completely from the model & delegate index creation as a database migration handled by sqlalchemy.


问:
Angular Json to class
I want to create a component with dummy data and have below code for service. I want to return observable to component.

Error

```<code>Type 'Observable<{ "CardModel": { "theme": string; "title": string; "description": string; }[]; }>' is not assignable to type 'Observable<CardModel[]>'.
</code>```

//Method

```<code>@Injectable()
export class PlanService {
  constructor() {}

  public getPlans(): Observable<CardModel[]> {
    return of(PlanServiceMock.plansMockData);
  }
}

export class PlanServiceMock {
  public static readonly plansMockData = {
    "CardModel": [
        {
            "theme": "",
            "title": "this is title",
            "description": "this is description"
        }
    ]
  };
}
</code>```

答:
You can use the of operator in order to return an observable from this data
https://www.learnrxjs.io/operators/creation/of.html

So inside in the PlanServiceMock class instead of

```<code>{
"CardModel": [
    {
        "theme": "",
        "title": "this is title",
        "description": "this is description"
    }
]
};
</code>```

use a method to return the mock data like below

```<code>  returnMockData(): Observable<CardModel[]> {
       return of([
          new CardModel(),
          new CardModel(),
          new CardModel()
        ]);
    }
</code>```

Hope this helps.

Title: Angular Json to class

Body:
I want to create a component with dummy data and have below code for service. I want to return observable to component.

Error

Type 'Observable<{ "CardModel": { "theme": string; "title": string; "description": string; }[]; }>' is not assignable to type 'Observable<CardModel[]>'.

//Method

@Injectable()
export class PlanService {
  constructor() {}

  public getPlans(): Observable<CardModel[]> {
    return of(PlanServiceMock.plansMockData);
  }
}

export class PlanServiceMock {
  public static readonly plansMockData = {
    "CardModel": [
        {
            "theme": "",
            "title": "this is title",
            "description": "this is description"
        }
    ]
  };
}

Body:
You can use the of operator in order to return an observable from this data
https://www.learnrxjs.io/operators/creation/of.html

So inside in the PlanServiceMock class instead of

{
"CardModel": [
    {
        "theme": "",
        "title": "this is title",
        "description": "this is description"
    }
]
};

use a method to return the mock data like below

  returnMockData(): Observable<CardModel[]> {
       return of([
          new CardModel(),
          new CardModel(),
          new CardModel()
        ]);
    }

Hope this helps.


问:
Add carriage return using regex pattern of any number
I have text that looks like this:

```<code>3    Q    I think I started out, I said when4 you first noticed
the oyster beds, it sounded5 like it didn't really concern you, you did not6 believe that the dredging material or the berm7 building material could reach the oyster beds?8    A    That's correct.9    Q
</code>```

I need to have an output that finds the first of any numeric sequence (i.e. "10" doesn't need to be a double match for 1 and 0) and looks looks like this (minus the spaces I had to put between each line):

```<code>3    Q    I think I started out, I said when

4 you first noticed the oyster beds, it sounded

5 like it didn't really concern you, you did not

6 believe that the dredging material or the berm

7 building material could reach the oyster beds?

8    A    That's correct.

9    Q
</code>```

答:
We can try matching on the pattern:

```<code>(?<=.)(\d+)
</code>```

This says to match and capture a number of any size, provided that it is not the first number in the text.  This avoids adding an unwanted newline before the first line beginning with 3.  Then, we can replace with a newline followed by that captured number.  Here is a working script:

```<code>Dim regex As Regex = new Regex("(?<=.)(\d+)")
Console.WriteLine(regex.Replace("1 stuff10 more stuff", vbCrLf & "$1"))
</code>```

This outputs:

```<code>1 stuff
10 more stuff
</code>```

Be certain to include the Imports Microsoft.VisualBasic to be able to use vbCrLf in your code.

Body:
I have text that looks like this:

3    Q    I think I started out, I said when4 you first noticed
the oyster beds, it sounded5 like it didn't really concern you, you did not6 believe that the dredging material or the berm7 building material could reach the oyster beds?8    A    That's correct.9    Q

I need to have an output that finds the first of any numeric sequence (i.e. "10" doesn't need to be a double match for 1 and 0) and looks looks like this (minus the spaces I had to put between each line):

3    Q    I think I started out, I said when

4 you first noticed the oyster beds, it sounded

5 like it didn't really concern you, you did not

6 believe that the dredging material or the berm

7 building material could reach the oyster beds?

8    A    That's correct.

9    Q

Body:
We can try matching on the pattern:

(?<=.)(\d+)

This says to match and capture a number of any size, provided that it is not the first number in the text.  This avoids adding an unwanted newline before the first line beginning with 3.  Then, we can replace with a newline followed by that captured number.  Here is a working script:

Dim regex As Regex = new Regex("(?<=.)(\d+)")
Console.WriteLine(regex.Replace("1 stuff10 more stuff", vbCrLf & "$1"))

This outputs:

1 stuff
10 more stuff

Be certain to include the Imports Microsoft.VisualBasic to be able to use vbCrLf in your code.


问:
Select last element without a class
I'm dynamically adding and removing classes to and from elements on specific JS events. What I would like to do is select the last child element that has none these classes with CSS.

Example #1

```<code><container-element>
  <h2></h2>
  <div class='some-class'></div>
  <div></div>
  <div></div> <!-- select this div -->
</container-element>
</code>```

Example #2

```<code><container-element>
  <h2></h2>
  <div></div>
  <div></div> <!-- select this div -->
  <div class='some-class'></div>
</container-element>
</code>```

Is it possible to write a CSS selector to do this?

Something like container-element > div:not(.select):last-of-type?

答:
Per this answer, the solution would technically be container-element > div:nth-last-child(1 of :not(.select)).

However, this of S clause in :nth-last-child is still not supported by any browser other than Safari.

Title: Select last element without a class

Body:
I'm dynamically adding and removing classes to and from elements on specific JS events. What I would like to do is select the last child element that has none these classes with CSS.

Example #1

<container-element>

</container-element>

Example #2

<container-element>

</container-element>

Is it possible to write a CSS selector to do this?

Something like container-element > div:not(.select):last-of-type?


问:
How to import cv2 in python3?
I'm using Windows, and I'm trying to install package cv2 for python3.

I did a pip3 install opencv-python and it reports successful:

But when I do the import cv2 from python3, it's not found and I get weird errors:

What am I doing wrong?

答:
Make a virtual enviroment using python3

```<code>virtualenv env_name --python="python3"
</code>```

and run the following command

```<code>pip3 install opencv-python
</code>```

Title: How to import cv2 in python3?

Body:
Make a virtual enviroment using python3

virtualenv env_name --python="python3"

and run the following command

pip3 install opencv-python


问:
Visual Studio - Setting a different port per solution
I have different solutions that I need to run one after another (not in parallel), but I usually need to swap from one to another quickly.
The issue is that I receive an error that states that the port is already in use, if I exit Visual Studio and re-open the solution, I can debug without issues.

I think the issue is that both the solutions try to use the same port 50847, so basically setting a specific port per solution should solve the problem ?

Any suggestion on this ?

答:
Assuming that socket is a TcpClient, you can switch ExclusiveAddressUse to false and set the linger option to false / 0. In case of server, SocketListener has that ExclusiveAddressUse as well. That way your solutions should no longer block eachother.

```<code>socket = new TcpClient();
socket.LingerState = new LingerOption(false, 0);
socket.ExclusiveAddressUse = false;
socket.NoDelay = true;
</code>```

Body:
Assuming that socket is a TcpClient, you can switch ExclusiveAddressUse to false and set the linger option to false / 0. In case of server, SocketListener has that ExclusiveAddressUse as well. That way your solutions should no longer block eachother.

socket = new TcpClient();
socket.LingerState = new LingerOption(false, 0);
socket.ExclusiveAddressUse = false;
socket.NoDelay = true;


问:
extending Function
I've been seeing the syntax:

```<code>var module = {

    func: function(value) {

        some code;

    }.func2("value");

}
</code>```

cropping up in various places, as am wondering how this is done. I remember seeing an article about it a while back, but can't find it now. Whatever I try .func2("value") just trows syntax errors.

For example, take a look at SproutCore's intro to their TemplateView.

```<code>Todos.StatsView = SC.TemplateView.extend({
  remainingBinding: 'Todos.todoListController.remaining',

  displayRemaining: function() {
    var remaining = this.get('remaining');
    return remaining + (remaining === 1 ? " item" : " items");
  }.property('remaining').cacheable()
});
</code>```

Seems like it would be a useful tool to give users when writing factories.

Thanks.

答:
The syntax I think you are looking for it is:

```<code>func: (function(value) {
    //some code;
}("value"));
</code>```

In which the anonymous function is called immediately and its return value assigned to func.

See also: How do JavaScript closures work?

Title: extending Function

Body:
I've been seeing the syntax:

var module = {

    func: function(value) {

        some code;

    }.func2("value");

}

cropping up in various places, as am wondering how this is done. I remember seeing an article about it a while back, but can't find it now. Whatever I try .func2("value") just trows syntax errors.

For example, take a look at SproutCore's intro to their TemplateView.

Todos.StatsView = SC.TemplateView.extend({
  remainingBinding: 'Todos.todoListController.remaining',

  displayRemaining: function() {
    var remaining = this.get('remaining');
    return remaining + (remaining === 1 ? " item" : " items");
  }.property('remaining').cacheable()
});

Seems like it would be a useful tool to give users when writing factories.

Thanks.

Body:
The syntax I think you are looking for it is:

func: (function(value) {
    //some code;
}("value"));

In which the anonymous function is called immediately and its return value assigned to func.

See also: How do JavaScript closures work?


答:
```<code><div class="students">
    <?php

        foreach ( $students as $student ) {
            $process = '';
            $result = 0;
            $student = learn_press_get_user( $student->ID );
            $data = $student->get_course_data($course->get_id());
            $status = $student->get_course_status($course->get_id());
            $result = $data->get_results();

            if ( $status ) {
            $process = ( $status == 'finished' ) ? 'finished' : 'in-progress';
            }

            echo trim($student->get_id()) . ',';
        }
    ?>
</div>
</code>```

Title: Php for each data to display in a comma seperated list with no space

Body:
Currently i am displaying id's of users to display in a single line with a comma delimiter, the problem is it is having unwanted space between comma's

Showing like this
1, 6, 10

Should be like this
1,6,10

<?php foreach ( $students as $student ) {

          $process = '';
          $result = 0;
          $student = learn_press_get_user( $student->ID );
          $data = $student->get_course_data($course->get_id());
          $status = $student->get_course_status($course->get_id());
          $result = $data->get_results();
   ?>

  <?php if ( $status ) {
  $process = ( $status == 'finished' ) ? 'finished' : 'in-progress';
  } ?>

       <?php echo $student->get_id(); ?>,
        <?php } ?>


问:
How to build multiple concurrent servers with Rust and Tokio?
I'm looking to build multiple concurrent servers on different ports with Rust and Tokio:

```<code>let mut core = Core::new().unwrap();
let handle = core.handle();

// I want to bind to multiple port here if it's possible with simple addresses
let addr = "127.0.0.1:80".parse().unwrap();
let addr2 = "127.0.0.1:443".parse().unwrap();

// Or here if there is a special function on the TcpListener
let sock = TcpListener::bind(&addr, &handle).unwrap();

// Or here if there is a special function on the sock
let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
    // And then retrieve the current port in the callback
    println!("Receive connection on {}!", mysterious_function_to_retrieve_the_port);
    Ok(())
});

core.run(server).unwrap();
</code>```

Is there an option with Tokio to listen to multiple ports or do I need to create a simple thread for each port and run Core::new() in each?

Thanks to rust-scoped-pool, I have:

```<code>let pool = Pool::new(2);

let mut listening_on = ["127.0.0.1:80", "127.0.0.1:443"];

pool.scoped(|scope| {
    for address in &mut listening_on {
        scope.execute(move ||{
            let mut core = Core::new().unwrap();
            let handle = core.handle();

            let addr = address.parse().unwrap();
            let sock = TcpListener::bind(&addr, &handle).unwrap();

            let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
                println!("Receive connection on {}!", address);
                Ok(())
            });

            core.run(server).unwrap();
        });
    }
});
</code>```

rust-scoped-pool is the only solution I have found to execute multiple threads and wait forever after spawning them. I think it's working but I was wondering if a simpler solution existed.

答:
I'd just like to follow up that there seems to be a slightly less manual way to do things than 46bit's answer (at least as of 2019).

let addr1 = "127.0.0.1:80".parse().unwrap();
let addr2 = "127.0.0.1:443".parse().unwrap();

let sock1 = TcpListener::bind(&addr1, &handle).unwrap();
let sock2 = TcpListener::bind(&addr2, &handle).unwrap();

let server1 = sock1.incoming().for_each(|_| Ok(()));
let server2 = sock2.incoming().for_each(|_| Ok(()));

let mut runtime = tokio::runtime::Runtime()::new().unwrap();

runtime.spawn(server1);
runtime.spawn(server2);

runtime.shutdown_on_idle().wait().unwrap();
```

Body:
I'm looking to build multiple concurrent servers on different ports with Rust and Tokio:

let mut core = Core::new().unwrap();
let handle = core.handle();

// I want to bind to multiple port here if it's possible with simple addresses
let addr = "127.0.0.1:80".parse().unwrap();
let addr2 = "127.0.0.1:443".parse().unwrap();

// Or here if there is a special function on the TcpListener
let sock = TcpListener::bind(&addr, &handle).unwrap();

// Or here if there is a special function on the sock
let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
    // And then retrieve the current port in the callback
    println!("Receive connection on {}!", mysterious_function_to_retrieve_the_port);
    Ok(())
});

core.run(server).unwrap();

Is there an option with Tokio to listen to multiple ports or do I need to create a simple thread for each port and run Core::new() in each?

Thanks to rust-scoped-pool, I have:

let pool = Pool::new(2);

let mut listening_on = ["127.0.0.1:80", "127.0.0.1:443"];

pool.scoped(|scope| {
    for address in &mut listening_on {
        scope.execute(move ||{
            let mut core = Core::new().unwrap();
            let handle = core.handle();

            let addr = address.parse().unwrap();
            let sock = TcpListener::bind(&addr, &handle).unwrap();

            let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
                println!("Receive connection on {}!", address);
                Ok(())
            });

            core.run(server).unwrap();
        });
    }
});

rust-scoped-pool is the only solution I have found to execute multiple threads and wait forever after spawning them. I think it's working but I was wondering if a simpler solution existed.


问:
Applying jquery script for a particular column in every row of a table
I am working on a dynamic dropdown list in a table for each row where I select a course in one select list and the classes associated with it are shown in the second dropdown list.

I was able to perform this using jQuery and ajax but the problem is this works only on the first row of the table and not on the rest of the table.

Below is the jQuery code I am using.

```<code> $(function () {
            $("#table").each(function () {
                $("#CourseName").change(function () {
                    alert("changed");
                    $.ajax({
                        type: 'Post',
                        url: '/RegisterStudents/GetClass',
                        dataType: 'json',
                        data: { id: $("#CourseName").val() },

                        success: function (data) {
                            var items = '';
                            $("#ClassName").empty;
                            $.each(data, function (i, row) {
                                items += '<option value="' + row.value + '">' + row.text + '</option>'
                            });
                            $("#ClassName").html(items);
                        }
                    })
                })

            });

        });
</code>```

I expect the jQuery script to work for all the dropdown list in every row of the table.

答:
It looks to me like you have the same Id=classname for each rows select so jquery doesn’t know which row to change. Either have unique ids and find a way to associate with the row or use jquery closest to find the rows select you are changing. This link may point you in the right direction.

Getting next closest select element with jquery

Body:
I am working on a dynamic dropdown list in a table for each row where I select a course in one select list and the classes associated with it are shown in the second dropdown list.

I was able to perform this using jQuery and ajax but the problem is this works only on the first row of the table and not on the rest of the table.

Below is the jQuery code I am using.

 $(function () {
            $("#table").each(function () {
                $("#CourseName").change(function () {
                    alert("changed");
                    $.ajax({
                        type: 'Post',
                        url: '/RegisterStudents/GetClass',
                        dataType: 'json',
                        data: { id: $("#CourseName").val() },

                        success: function (data) {
                            var items = '';
                            $("#ClassName").empty;
                            $.each(data, function (i, row) {
                                items += '<option value="' + row.value + '">' + row.text + '</option>'
                            });
                            $("#ClassName").html(items);
                        }
                    })
                })

            });

        });

I expect the jQuery script to work for all the dropdown list in every row of the table.


问:
How to identify users which are connected to a windows server via remote desktop
At my workplace, we have lab machines that we use to do our testing.

The standard procedure to reserve a machine for testing was to walk around the office to make sure that no one was using the machine.

This is highly inefficient and time consuming.

At first, I set up a web page where people could reserve the lab machine but nobody was keeping the page updated so that turned up to be useless.

I finally found a solution using Microsoft log parser and wanted to share it to the stack overflow community.

It is a batch file that runs on the machine so the user can identify the last users that use the machine and easily IM them to ask if the machine is free.

Is there a better solution to do this?

答: Since it sounds like you're a microsoft shop, you can set up the machines as resources in outlook/exchange and reserve them that way.</p>

OwnerDisplayName: Julien Nephtali

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: sqook

OwnerDisplayName: Joel Coehoorn


问:
cakephp timezone warning notice on debug enabling
In CakePHP-1.2, When i put debug on to 1 or 2 it gives me below timezone related warnings/notices.

Warning (2): date() [http://php.net/function.date]: It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Calcutta' for 'IST/5.0/no DST' instead [CORE/cake/libs/model/model.php, line 1149]

Any idea, how can i remove it?

答:
In you php.ini find

```<code>date.timezone
</code>```

if it's commented, remove comment and set it to your timezone.

For example: date.timezone = Europe/London

Body:
In you php.ini find

date.timezone

if it's commented, remove comment and set it to your timezone.

For example: date.timezone = Europe/London


问:
checking for ANY NULL object before ToLower
I have an object where a property may exist or may not exist.

```<code>if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus.ToLower().Equals("usps_match")))
{

}
</code>```

I have two array items of AddressResponse. First item has null for matchCodeStatus and thats where I get object not set to an instance exception. How can I achieve my target and escape this exception?

I tried to put a null check before my IF, but it didnt work

```<code>if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus != null)
</code>```

答:
As of C# 6, you can also use a null conditional operator ?. :

```<code>inf => inf.AddressResponse.matchCodeStatus?.ToLower().Equals("usps_match"))
</code>```

Body:
I have an object where a property may exist or may not exist.

if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus.ToLower().Equals("usps_match")))
{

}

I have two array items of AddressResponse. First item has null for matchCodeStatus and thats where I get object not set to an instance exception. How can I achieve my target and escape this exception?

I tried to put a null check before my IF, but it didnt work

if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus != null)

Body:
As of C# 6, you can also use a null conditional operator ?. :

inf => inf.AddressResponse.matchCodeStatus?.ToLower().Equals("usps_match"))


问:
system function flaws
We are using C in Linux. Is there any possibility that system() function can behave in an unexpected manner, especially when we handle signals?

We found that sometimes, the system() function blocks the execution or it throws SIGSEGV.

e.g:

```<code>system ( "/bin/mv a b" );
</code>```

Are there any known flaws in using system() that would explain this?

答:
The system() function does what it is supposed to do perfectly well.  The behaviour is pretty reliable as long as it is invoked correctly.  It has two modes of operation:

Check whether there is a command interpreter available - when the argument is a null pointer.

Run the command given, waiting for the command to complete before returning.

So, the system() statement blocks until the shell that runs the command completes.  On Unix-like systems, the command invoked is effectively:

```<code>"sh", "-c", "...argument to system...", NULL
</code>```

This means that the string passed is interpreted by the shell.  How long that takes depends on the command that is executed.  You can consider using the shell notations to run the command in background if you need to:

```<code>system("( /bin/mv a b & )");
</code>```

There are few circumstances where system() will itself generate SIGSEGV.  You would have to pass it an invalid pointer, a pointer to somewhere invalid in the program.

Title: system function flaws

Body:
We are using C in Linux. Is there any possibility that system() function can behave in an unexpected manner, especially when we handle signals?

We found that sometimes, the system() function blocks the execution or it throws SIGSEGV.

e.g:

system ( "/bin/mv a b" );

Are there any known flaws in using system() that would explain this?

Body:
The system() function does what it is supposed to do perfectly well.  The behaviour is pretty reliable as long as it is invoked correctly.  It has two modes of operation:

Check whether there is a command interpreter available - when the argument is a null pointer.

Run the command given, waiting for the command to complete before returning.

So, the system() statement blocks until the shell that runs the command completes.  On Unix-like systems, the command invoked is effectively:

"sh", "-c", "...argument to system...", NULL

This means that the string passed is interpreted by the shell.  How long that takes depends on the command that is executed.  You can consider using the shell notations to run the command in background if you need to:

system("( /bin/mv a b & )");

There are few circumstances where system() will itself generate SIGSEGV.  You would have to pass it an invalid pointer, a pointer to somewhere invalid in the program.


问:
setText function does not change the TextView
the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!

I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)

java

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         play =(Button) findViewById(R.id.button4);
         Pause =(Button) findViewById(R.id.button5);
        hourstext =(TextView) findViewById(R.id.textView1);
        mintext =(TextView) findViewById(R.id.textView2);
        sectext =(TextView) findViewById(R.id.textView3);

    }

    void playb(View v)  {

        while (!ispause) {
            sec = 0 ;
            while (sec < 60) {
                SystemClock.sleep(1000);
                sec++;
               sectext.setText(Integer.toString(sec));
                Log.d("this", "sec value=" + sec);
            }
            sec = 0;
            min++;
            Log.d("this","min value ="+min);

           mintext.setText(String.valueOf(min));

        }

    }
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="114dp"
        android:layout_height="94dp"
        android:layout_marginTop="159dp"
        android:layout_marginEnd="16dp"
        android:layout_x="274dp"
        android:layout_y="120dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="93dp"
        android:layout_x="217dp"
        android:layout_y="296dp"
        android:enabled="false"
        android:onClick="playb"
        android:text="Pause"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/playbutton"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <Button
        android:id="@+id/playbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="116dp"
        android:layout_x="63dp"
        android:layout_y="293dp"
        android:onClick="playb"
        android:text="playb"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="120dp"
        android:layout_height="97dp"
        android:layout_marginTop="156dp"
        android:layout_marginEnd="17dp"
        android:layout_x="139dp"
        android:layout_y="117dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="103dp"
        android:layout_height="94dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="159dp"
        android:layout_x="11dp"
        android:layout_y="117dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

i get no error message ! the app keeps working but no updated textView

i've included my XML Code

答:
It's likely to do with running everything on the main thread. You should never call sleep on the main thread or you will block the UI.

When the button is clicked you should start the counter on a background thread. You will then need to update the TextView on the main thread.

It can be achieved quite easily with RxJava:

```<code>private Disposable disposable;

disposable = Observable.interval(1, 1, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(value -> {
            // Update UI
        });
</code>```

To stop the counter:

```<code>disposable.dispose();
</code>```

Body:
the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!

I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)

java

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         play =(Button) findViewById(R.id.button4);
         Pause =(Button) findViewById(R.id.button5);
        hourstext =(TextView) findViewById(R.id.textView1);
        mintext =(TextView) findViewById(R.id.textView2);
        sectext =(TextView) findViewById(R.id.textView3);

    }

    void playb(View v)  {

        while (!ispause) {
            sec = 0 ;
            while (sec < 60) {
                SystemClock.sleep(1000);
                sec++;
               sectext.setText(Integer.toString(sec));
                Log.d("this", "sec value=" + sec);
            }
            sec = 0;
            min++;
            Log.d("this","min value ="+min);

           mintext.setText(String.valueOf(min));

        }

    }

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="114dp"
        android:layout_height="94dp"
        android:layout_marginTop="159dp"
        android:layout_marginEnd="16dp"
        android:layout_x="274dp"
        android:layout_y="120dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="93dp"
        android:layout_x="217dp"
        android:layout_y="296dp"
        android:enabled="false"
        android:onClick="playb"
        android:text="Pause"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/playbutton"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <Button
        android:id="@+id/playbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="116dp"
        android:layout_x="63dp"
        android:layout_y="293dp"
        android:onClick="playb"
        android:text="playb"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="120dp"
        android:layout_height="97dp"
        android:layout_marginTop="156dp"
        android:layout_marginEnd="17dp"
        android:layout_x="139dp"
        android:layout_y="117dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="103dp"
        android:layout_height="94dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="159dp"
        android:layout_x="11dp"
        android:layout_y="117dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

i get no error message ! the app keeps working but no updated textView

i've included my XML Code

Body:
It's likely to do with running everything on the main thread. You should never call sleep on the main thread or you will block the UI.

When the button is clicked you should start the counter on a background thread. You will then need to update the TextView on the main thread.

It can be achieved quite easily with RxJava:

private Disposable disposable;

disposable = Observable.interval(1, 1, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(value -> {
            // Update UI
        });

To stop the counter:

disposable.dispose();


问:
SyntaxError: Non-UTF-8 code starting with '\xe7'
I made a program which contains chinese and russian words, but when I ran it, I had a problem with the encoding

In the code that I shared, a complete sentence with some Russian and Chinese characters is shown. With that variable assignment the SyntaxError arises. But when i write sentence=input(), when the user enters the same sentence no error appears.

sentence='n紙sнo頭q愛z語u買gлd娜xтgлj鳥u買gлcхd娜u買 рj鳥pщi魚d娜gлh園d娜gлn紙r無z語 рr無pщl電pщv書kмz語u買gлkмu買o頭d娜r無n紙r無d娜o頭pщh園z語gлh園d娜gлpщcхo頭z語gлu買kмwзd娜cхgлsнgлz語r無kмd娜u買o頭pщh園z語gлpщgлz語aчi魚d娜o頭z語xтgлv書z語u買gлd娜cхgлv書j鳥pщcхgлn紙z語h園d娜l電z語xтgлv書r無d娜pщr無gлo頭z語h園z語gлo頭kмn紙z語gлh園d娜gлpщn紙cхkмv書pщv書kмz語u買d娜xтgлd娜u買o頭r無d娜gлxтj鳥xтgлh園kмwзd娜r無xтz語xтgлo頭kмn紙z語xтgлh園d娜gлd娜xтo頭r無j鳥v書o頭j鳥r無pщxтgлh園d娜gлh園pщo頭z語xтgлxтd娜gлd娜u買v書j鳥d娜u買o頭r無pщgлh園kмv書v書kмz語u買pщr無kмz語xтgлh園d娜gлh園pщo頭z語xтgлd娜u買gлd娜xтo頭d娜gлo頭j鳥o頭z語r無kмpщcхgлpщn紙r無d娜u買h園d娜r無d娜l電z語xтgлpщgлj鳥o頭kмcхkмñсpщr無gлd娜xтo頭pщgлd娜xтo頭r無j鳥v書o頭j鳥r無pщgлr無d娜wзkмxтpщu買h園z語gлxтj鳥xтgлl電d娜o頭z語h園z語xтgлl電pщxтgлj鳥o頭kмcхkмñсpщh園z語xт'
```

```SyntaxError: Non-UTF-8 code starting with '\xe5' in file hjs.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
```

How can I solve it?

答:
First of all, welcome to Stack Overflow!
Second, you could solve your problem by using Python 3 or, for Python 2, following what is said in this answer.

But why?

Well, according to the aforementioned PEP 263,

Python will default to ASCII as standard encoding if no other encoding hints are given.

And in the PEP you can see the same thing that the mentioned answer says, to add the line # -*- coding: <encoding name> -*-

And why isn't Python 3 affected by this issue?
As said in here,

Since Python 3.0, the language’s str type contains Unicode characters(...)

So there is no need for adding the coding magic comment.

For more on that the full unicode article linked above is a great reading, and as it is a classic in StackOverflow, please see this.

Body:
I made a program which contains chinese and russian words, but when I ran it, I had a problem with the encoding

In the code that I shared, a complete sentence with some Russian and Chinese characters is shown. With that variable assignment the SyntaxError arises. But when i write sentence=input(), when the user enters the same sentence no error appears.

sentence='n紙sнo頭q愛z語u買gлd娜xтgлj鳥u買gлcхd娜u買 рj鳥pщi魚d娜gлh園d娜gлn紙r無z語 рr無pщl電pщv書kмz語u買gлkмu買o頭d娜r無n紙r無d娜o頭pщh園z語gлh園d娜gлpщcхo頭z語gлu買kмwзd娜cхgлsнgлz語r無kмd娜u買o頭pщh園z語gлpщgлz語aчi魚d娜o頭z語xтgлv書z語u買gлd娜cхgлv書j鳥pщcхgлn紙z語h園d娜l電z語xтgлv書r無d娜pщr無gлo頭z語h園z語gлo頭kмn紙z語gлh園d娜gлpщn紙cхkмv書pщv書kмz語u買d娜xтgлd娜u買o頭r無d娜gлxтj鳥xтgлh園kмwзd娜r無xтz語xтgлo頭kмn紙z語xтgлh園d娜gлd娜xтo頭r無j鳥v書o頭j鳥r無pщxтgлh園d娜gлh園pщo頭z語xтgлxтd娜gлd娜u買v書j鳥d娜u買o頭r無pщgлh園kмv書v書kмz語u買pщr無kмz語xтgлh園d娜gлh園pщo頭z語xтgлd娜u買gлd娜xтo頭d娜gлo頭j鳥o頭z語r無kмpщcхgлpщn紙r無d娜u買h園d娜r無d娜l電z語xтgлpщgлj鳥o頭kмcхkмñсpщr無gлd娜xтo頭pщgлd娜xтo頭r無j鳥v書o頭j鳥r無pщgлr無d娜wзkмxтpщu買h園z語gлxтj鳥xтgлl電d娜o頭z語h園z語xтgлl電pщxтgлj鳥o頭kмcхkмñсpщh園z語xт'

SyntaxError: Non-UTF-8 code starting with '\xe5' in file hjs.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

How can I solve it?


问:
currently having trouble with lists,strings and integers
i'm trying to challenge myself by coding a version of the card game 21, but i'm having trouble with the strings and integers. my counter also doesn't work and that is beyond me

I've tried defining everything as an integer

define

```<code>cardnum1 = " "
cardnum2 = " "

print("the dealer shuffles the cards and deals the first hand")
import random
list = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
#1st card
card1 = random.choice(list)
print("your first card is ",card1)
#numbers
if card1 == ["2","3","4","5","6","7","8","9","10"]:
    card1=int(cardnum1)

elif card1 == "Jack":
    cardnum1=int(10)

elif card1 == "Queen":
    cardnum1=int(10)

elif card1 == "King":
    cardnum1=int(10)

elif card1 == "Ace":
    cardnum1=input("do you want your Ace to be a 1 or a 11?")

card2 = random.choice(list)
print("your second card is ",card2)

#numbers 1 - 10
if card2 == ["2","3","4","5","6","7","8","9","10"]:
    card1=int(cardnum1)

#special cards
elif card2 == "Jack":
    cardnum2=int(10)

elif card2 == "Queen":
    cardnum2=int(10)

elif card2 == "King":
    cardnum2=int(10)

elif card2 == "Ace":
    cardnum2=input("do you want your Ace to be a 1 or a 11?")

print ("your cards combined are ",cardnum1 + cardnum2)
</code>```

i'm trying to randomly get 2 cards and the have the program tell me how far i am from 21 and if i've bust or not.
cardnum1 and cardnum2 don't seem to properly add.

i get the error message :

```<code>TypeError: can only concatenate str (not "int") to str
</code>```

答:
While others have given working versions of your program, and pointed out the issues with your version, let me offer a simple alternative of how you could do it:

```<code>import random

deck = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 'Jack', 'Queen', 'King']

card1 = random.choice(deck)
card2 = random.choice(deck)

def card_value(card):
    if card == 'Ace':
        chosen_value = input("do you want your Ace to be a 1 or a 11?")
        return int(chosen_value)
    elif card in ['Jack', 'Queen', 'King']:
        return 10
    else:
        # Return the integer as it is
        return card

print("Your first card is", card1)
print("Your first card is", card2)

print("Your cards combined are ", card_value(card1) + card_value(card2))
</code>```

The only major difference between this version and yours is that I use a card_value helper method to derive the value of the card as an integer. If the card value is already an integer, it just returns as it is.

P.S:

Welcome to the world of programming, and it's super cool that you are trying to challenge yourself this early. Don't worry about the downvotes to your question; It happens. But you can avoid it by taking a methodical approach to your problem:

First write down an algorithm in plain english or pseudocode

Code and test each stage of the algorithm

Write tests that check expected output with actual output

In the beginning, you may also find it beneficial to invest time and learn how to think like a programmer, than dig deep into any one language. See these links to know what I mean:

https://zapier.com/blog/think-like-a-programmer/

https://www.amazon.com/Think-Like-Programmer-Introduction-Creative/dp/1593274246

https://medium.freecodecamp.org/how-to-think-like-a-programmer-lessons-in-problem-solving-d1d8bf1de7d2

Body:
i'm trying to challenge myself by coding a version of the card game 21, but i'm having trouble with the strings and integers. my counter also doesn't work and that is beyond me

I've tried defining everything as an integer

define

cardnum1 = " "
cardnum2 = " "

print("the dealer shuffles the cards and deals the first hand")
import random
list = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
#1st card
card1 = random.choice(list)
print("your first card is ",card1)
#numbers
if card1 == ["2","3","4","5","6","7","8","9","10"]:
    card1=int(cardnum1)

elif card1 == "Jack":
    cardnum1=int(10)

elif card1 == "Queen":
    cardnum1=int(10)

elif card1 == "King":
    cardnum1=int(10)

elif card1 == "Ace":
    cardnum1=input("do you want your Ace to be a 1 or a 11?")

card2 = random.choice(list)
print("your second card is ",card2)

#numbers 1 - 10
if card2 == ["2","3","4","5","6","7","8","9","10"]:
    card1=int(cardnum1)

#special cards
elif card2 == "Jack":
    cardnum2=int(10)

elif card2 == "Queen":
    cardnum2=int(10)

elif card2 == "King":
    cardnum2=int(10)

elif card2 == "Ace":
    cardnum2=input("do you want your Ace to be a 1 or a 11?")

print ("your cards combined are ",cardnum1 + cardnum2)

i'm trying to randomly get 2 cards and the have the program tell me how far i am from 21 and if i've bust or not.
cardnum1 and cardnum2 don't seem to properly add.

i get the error message :

TypeError: can only concatenate str (not "int") to str

Body:
While others have given working versions of your program, and pointed out the issues with your version, let me offer a simple alternative of how you could do it:

import random

deck = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 'Jack', 'Queen', 'King']

card1 = random.choice(deck)
card2 = random.choice(deck)

def card_value(card):
    if card == 'Ace':
        chosen_value = input("do you want your Ace to be a 1 or a 11?")
        return int(chosen_value)
    elif card in ['Jack', 'Queen', 'King']:
        return 10
    else:
        # Return the integer as it is
        return card

print("Your first card is", card1)
print("Your first card is", card2)

print("Your cards combined are ", card_value(card1) + card_value(card2))

The only major difference between this version and yours is that I use a card_value helper method to derive the value of the card as an integer. If the card value is already an integer, it just returns as it is.

P.S:

Welcome to the world of programming, and it's super cool that you are trying to challenge yourself this early. Don't worry about the downvotes to your question; It happens. But you can avoid it by taking a methodical approach to your problem:

First write down an algorithm in plain english or pseudocode

Code and test each stage of the algorithm

Write tests that check expected output with actual output

In the beginning, you may also find it beneficial to invest time and learn how to think like a programmer, than dig deep into any one language. See these links to know what I mean:

https://zapier.com/blog/think-like-a-programmer/

https://www.amazon.com/Think-Like-Programmer-Introduction-Creative/dp/1593274246

https://medium.freecodecamp.org/how-to-think-like-a-programmer-lessons-in-problem-solving-d1d8bf1de7d2


问:
How to debug a Clojure web application in Intellij?
I am using Intellij + Cursive and I want to debug a Clojure web application written using ring + compojure. I start the application in the Intellij terminal using lein and the ring plugin:

```<code>> lein ring server-headless
</code>```

I want to debug this application using Intellij to set up breakpoints in the source code, see variables, etc.

But Intellij's Leiningen tab does not show a task with the ring command. Run configurations also do not have an option to run the ring command.

答:
You need two steps:

Update your project.clj to pass extra parameters, like this

```<code>  :ring {:nrepl {:start? true :port 4001}      ;; <== Add this
         :handler com.mycompany.web/myhandler} ;; you should have this
</code>```

... this should launch the web application in port 4000 and also an nREPL port for debugging, etc. in port 4001. You can check the lein-ring documentation for more details.

You should see the following when starting your app:

```<code>$ lein ring server-headless 4000
[... some output omitted ...]
Started nREPL server on port 4001
Started server on port 4000
</code>```

In Cursive, connect to the nREPL server as described in the section Remote REPLs in the Cursive docs. You should use either localhost or 0.0.0.0 in the host name and 4001 (or whatever nREPL port you used in the configuration in the previous step).

Body:
I am using Intellij + Cursive and I want to debug a Clojure web application written using ring + compojure. I start the application in the Intellij terminal using lein and the ring plugin:

> lein ring server-headless

I want to debug this application using Intellij to set up breakpoints in the source code, see variables, etc.

But Intellij's Leiningen tab does not show a task with the ring command. Run configurations also do not have an option to run the ring command.

Body:
You need two steps:

Update your project.clj to pass extra parameters, like this

  :ring {:nrepl {:start? true :port 4001}      ;; <== Add this
         :handler com.mycompany.web/myhandler} ;; you should have this

... this should launch the web application in port 4000 and also an nREPL port for debugging, etc. in port 4001. You can check the lein-ring documentation for more details.

You should see the following when starting your app:

$ lein ring server-headless 4000
[... some output omitted ...]
Started nREPL server on port 4001
Started server on port 4000

In Cursive, connect to the nREPL server as described in the section Remote REPLs in the Cursive docs. You should use either localhost or 0.0.0.0 in the host name and 4001 (or whatever nREPL port you used in the configuration in the previous step).


问:
Typical Requests/Second a "server" can handle?
I want to implement an ajax Client that does polling to the server. This leads to millions of small requests...

Do you have any rough estimates (based on your hardware and your experiences, I do currenlty not have any dedicated server hardware yet), how man requets a sever can handle for example Tomcat 7 with standard server hardware (8GB Ram, 4 Cores, 2,5GHZ each)? The internal Processing of one request is estemated to finish within 50 millisecons (only data is put into a Ram Cache, some counters are incrementd, light textprocessing and then data is read from memory again to return to the client. it will all fit in RAM).

I would be thankfull for any experiences you made how much requests you think or you were able to handle on your server in a comparable environment.

thanks!!
jens

答:
50ms gives you quite a lot of processing, actually... especially if most of these requests are just polling, presumably for changes. How did you come up with that estimate? That would keep 4 cores busy with 80 requests per second, of course... but that's not an awful lot, and you probably wouldn't want to run your servers at full capacity the whole time, and there'll be some overhead for the simple handling of the networking.

To be honest, estimates are relatively pointless compared with just trying it. You'll need to load test your servers anyway, so it would be best to do that now rather than later.

Note that an alternative to frequent polling would be to have long "hanging" requests, aka Comet. Each request would be held unfulfilled for some period (e.g. 5-10 minutes) and as soon as you had a change, you'd respond appropriately. That way you can drastically reduce the number of requests - but it does make the code much harder to write (as it has to be asynchronous; you don't want one thread per request at that point).


问:
Currency conversion in R
I am trying to convert currency values from factor to numeric. The format is €110.5M €565K I was able to get rid of € sign, M and K letters but I also need to make the conversion as to show 110.5M=110.500.000 and 565K=565.000. Is there a way that you can suggest?

```<code>value<-as.numeric(gsub("[€MK]", "", as.character(strength[1:18207,1])))
</code>```

Data to be converted

```<code>€110.5M €565K
€77M    €405K
€118.5M €290K
</code>```

Title: Currency conversion in R

Body:
I am trying to convert currency values from factor to numeric. The format is €110.5M €565K I was able to get rid of € sign, M and K letters but I also need to make the conversion as to show 110.5M=110.500.000 and 565K=565.000. Is there a way that you can suggest?

value<-as.numeric(gsub("[€MK]", "", as.character(strength[1:18207,1])))

Data to be converted

€110.5M €565K
€77M    €405K
€118.5M €290K

Body:
An option is gsubfn

library(gsubfn)
out <- unname(sapply(gsubfn("M|K", list(M = "* 1e6", K = "* 1e3"),
    sub("€", "", str1)), function(x) eval(parse(text = x))))
out
#[1] 110500000    565000  77000000    405000 118500000    290000

scales::dollar_format(prefix = "", big.mark = ".")(out)
#[1] "110.500.000" "565.000"     "77.000.000"  "405.000"
#[4] "118.500.000" "290.000"

data

str1 <- c("€110.5M",  "€565K", "€77M", "€405K", "€118.5M", "€290K")


问:
What Language For Image Recognition In Conjunction With Robotics
I have some basic general coding knowledge but have never delved into one language very much. I am interested in creating a program that utilizes image recognition in a live video feed to control a robot. I want to be able to identify specific objects in the image. I'm thinking of using an Arduino or Raspberry Pi to control the robot and possibly a USB webcam or serial camera for capturing the image.

I'm wondering what language would be best suited for the image processing in real-time, working in conjunction with my robot, being able to feed the program data (images) for it to learn and other factors I may not have considered that might be necessary for this application.

答:
C++ and python are the best I can think of

OpenCV is standard.  But doubt it can recognize face fast enough on Raspberry PI. Usually, we use Keras for running more state of the art code on the striped notebook motherboard with GPU. sth like the image below. You can get it at PC repair shop. Just say you need a replacement motherboard. quite ez to get.

Arduino is for simple control. e.g two servo. But if you need to program the robot to do sth advanced e.g path planning, homolomic control, ROS is more ideal.


问:
Why can't I display images when using github pages?
I have a test site here that has only one image tag which I can not get to load:

https://jamie-siminoff-007.github.io/

The index file is:

```<code><!DOCTYPE html>
<html>
  <body>
    <img src="_heart.png" alt="foo">
  </body>
</html>
</code>```

This is a git page so it is completely hosted on GitHub and the repo is here:

https://github.com/jamie-siminoff-007/jamie-siminoff-007.github.io

What am I missing?

FYI, I can put in what I call the raw link as seen below for the src and it works:

```<code>https://raw.githubusercontent.com/jamie-siminoff-007/jamie-siminoff-6.github.io/master/_heart.png
</code>```

but this does not seem like the correct way.  Surely when GitHub made pages, they have a way for you to use relative paths.

Research

Images in github pages and relative links
... not related

https://pages.github.com
... nothing relevant

https://help.github.com/en/categories/github-pages-basics
... nothing on images

More Info.

I found that google dev tools has a neat feature where you can change the src attribute of the image and it will update the page in real time.

This is how I found out that the raw link worked.

More More Info.

I am starting to think that my GitHub pages need further configuration but I'm not sure.

I checked my configuration and I am configured to publish on the master branch which is good b.c. it is the only branch I have.

答:
It looks like your src gives a 404 error (file not found).
For me, this src works: "https://raw.githubusercontent.com/jamie-siminoff-007/jamie-siminoff-007.github.io/master/_heart.png"

```

Body:
I have a test site here that has only one image tag which I can not get to load:

https://jamie-siminoff-007.github.io/

The index file is:

<!DOCTYPE html>

This is a git page so it is completely hosted on GitHub and the repo is here:

https://github.com/jamie-siminoff-007/jamie-siminoff-007.github.io

What am I missing?

FYI, I can put in what I call the raw link as seen below for the src and it works:

https://raw.githubusercontent.com/jamie-siminoff-007/jamie-siminoff-6.github.io/master/_heart.png

but this does not seem like the correct way.  Surely when GitHub made pages, they have a way for you to use relative paths.

Research

Images in github pages and relative links
... not related

https://pages.github.com
... nothing relevant

https://help.github.com/en/categories/github-pages-basics
... nothing on images

More Info.

I found that google dev tools has a neat feature where you can change the src attribute of the image and it will update the page in real time.

This is how I found out that the raw link worked.

More More Info.

I am starting to think that my GitHub pages need further configuration but I'm not sure.

I checked my configuration and I am configured to publish on the master branch which is good b.c. it is the only branch I have.

Body:
It looks like your src gives a 404 error (file not found).
For me, this src works: "https://raw.githubusercontent.com/jamie-siminoff-007/jamie-siminoff-007.github.io/master/_heart.png"

<html class="gr__jamie-siminoff-007_github_io"><head></head><body data-gr-c-s-loaded="true">
    <img src="https://raw.githubusercontent.com/jamie-siminoff-007/jamie-siminoff-007.github.io/master/_heart.png" alt="foo">

</body></html>