问:
Robust way to manage and kill any process
I am writing code to run experiments in parallel. I don't have control over what the experiments do, they might open use subprocess.Popen or check_output to run one or multiple additional child processes.

I have two conditions: I want to be able to kill experiments that exceed a time out and I want to kill experiments upon KeyboardInterrupt.

Most ways to terminate processes don't make sure that all subprocesses etc are killed. This is obviously a problem if 100s of experiments are run one after the other but they all spawn child processes that stay alive after the timeout occurred and the experiment was supposedly killed.

The way I am dealing with this now it to include code to store experiment configurations in a database, generating code that loads and runs experiments from command line and then calling these commands via subprocess.Popen(cmd, shell=True, start_new_session=True) and killing them using os.killpg on timeout.

My main question then is: Calling these experiments via command line feels cumbersome, so is there a way to call code directly via multiprocessing.Process(target=fn) and achieving the same effect of start_new_session=True + os.killpg upon timeout and KeyboardInterrupt?

```<code><file1>
def run_exp(config):
    do work
    return result

if __name__ == "__main__":
    save_exp(run_exp(load_config(sys.args)))

<file2>
def monitor(queue):
    active = set()  # active process ids
    while True:
        msg = queue.get()
        if msg == "sentinel":
             <loop over active ids and kill them with os.killpg>
        else:
            <add or remove id from active set>

def worker(args):
    id, queue = args
    command = f"python <file1> {id}"
    with subprocess.Popen(command, shell=True, ..., start_new_session=True) as process:
        try:
            queue.put(f"start {process.pid}")
            process.communicate(timeout=timeout)
        except TimeoutExpired:
            os.killpg(process.pid, signal.SIGINT)  # send signal to the process group
            process.communicate()
        finally:
            queue.put(f"done {process.pid}")

def main():
    <save configs => c_ids>
    queue = manager.Queue()
    process = Process(target=monitor, args=(queue,))
    process.start()

    def clean_exit():
        queue.put("sentinel")
        <terminate pool and monitor process>

    r = pool.map_async(worker, [(c_id, queue) for c_id in c_ids])
    atexit.register(clean_exit)
    r.wait()
    <terminate pool and monitor process>
</code>```

I posted a skeleton of the code that details the approach of starting processes via command line and killing them. An additional complication of that version of my approach is that when the KeyboardInterrupt arrives, the queue already gets terminated (for a lack of a better word) and communicating with the monitor process is impossible (the sentinel message never arrives). Instead I have to resort to writing process ids to file and reading the file back to in the main process to kill the still running processes. If you know a way to work around this queue-issue I'd be eager to learn about it.

答:
I guess there is one way to avoid this is using Try catch block.

Say if the KeyboardInterrupt arrives in main() then you could try this:

```<code>def main():
    try:
        <save configs => c_ids>
        queue = manager.Queue()
        process = Process(target=monitor, args=(queue,))
        process.start()

        def clean_exit():
            queue.put("sentinel")
            <terminate pool and monitor process>

        r = pool.map_async(worker, [(c_id, queue) for c_id in c_ids])
        atexit.register(clean_exit)
        r.wait()
        <terminate pool and monitor process>
    except KeyboardInterrupt as e:
        pass
        #write the process you want to keep continuing.
</code>```

Guess this will be helpful.

Body:
I am writing code to run experiments in parallel. I don't have control over what the experiments do, they might open use subprocess.Popen or check_output to run one or multiple additional child processes.

I have two conditions: I want to be able to kill experiments that exceed a time out and I want to kill experiments upon KeyboardInterrupt.

Most ways to terminate processes don't make sure that all subprocesses etc are killed. This is obviously a problem if 100s of experiments are run one after the other but they all spawn child processes that stay alive after the timeout occurred and the experiment was supposedly killed.

The way I am dealing with this now it to include code to store experiment configurations in a database, generating code that loads and runs experiments from command line and then calling these commands via subprocess.Popen(cmd, shell=True, start_new_session=True) and killing them using os.killpg on timeout.

My main question then is: Calling these experiments via command line feels cumbersome, so is there a way to call code directly via multiprocessing.Process(target=fn) and achieving the same effect of start_new_session=True + os.killpg upon timeout and KeyboardInterrupt?

<file1>
def run_exp(config):
    do work
    return result

if __name__ == "__main__":
    save_exp(run_exp(load_config(sys.args)))

<file2>
def monitor(queue):
    active = set()  # active process ids
    while True:
        msg = queue.get()
        if msg == "sentinel":
             <loop over active ids and kill them with os.killpg>
        else:
            <add or remove id from active set>

def worker(args):
    id, queue = args
    command = f"python <file1> {id}"
    with subprocess.Popen(command, shell=True, ..., start_new_session=True) as process:
        try:
            queue.put(f"start {process.pid}")
            process.communicate(timeout=timeout)
        except TimeoutExpired:
            os.killpg(process.pid, signal.SIGINT)  # send signal to the process group
            process.communicate()
        finally:
            queue.put(f"done {process.pid}")

def main():
    <save configs => c_ids>
    queue = manager.Queue()
    process = Process(target=monitor, args=(queue,))
    process.start()

    def clean_exit():
        queue.put("sentinel")
        <terminate pool and monitor process>

    r = pool.map_async(worker, [(c_id, queue) for c_id in c_ids])
    atexit.register(clean_exit)
    r.wait()
    <terminate pool and monitor process>

I posted a skeleton of the code that details the approach of starting processes via command line and killing them. An additional complication of that version of my approach is that when the KeyboardInterrupt arrives, the queue already gets terminated (for a lack of a better word) and communicating with the monitor process is impossible (the sentinel message never arrives). Instead I have to resort to writing process ids to file and reading the file back to in the main process to kill the still running processes. If you know a way to work around this queue-issue I'd be eager to learn about it.

Body:
I guess there is one way to avoid this is using Try catch block.

Say if the KeyboardInterrupt arrives in main() then you could try this:

def main():
    try:
        <save configs => c_ids>
        queue = manager.Queue()
        process = Process(target=monitor, args=(queue,))
        process.start()

        def clean_exit():
            queue.put("sentinel")
            <terminate pool and monitor process>

        r = pool.map_async(worker, [(c_id, queue) for c_id in c_ids])
        atexit.register(clean_exit)
        r.wait()
        <terminate pool and monitor process>
    except KeyboardInterrupt as e:
        pass
        #write the process you want to keep continuing.

Guess this will be helpful.


来源: stackexchange

问:
Override center tag with css
I am using Stylebot, which adds CSS properties with !important to websites. The page looks like this:

```<code><article class="main" id="contentDetail">
  <center>
    <img src="example.png">
  </center>
...
</code>```

Is it possible to add CSS properties to override the  tag and have the image align left? I have tried align="left". Stylebot does not seem to be able to remove the tag.

答:
This will solve your issue</p>

```<code>center{
display: inline;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Override center tag with css

Body:
I am using Stylebot, which adds CSS properties with !important to websites. The page looks like this:

...

Is it possible to add CSS properties to override the  tag and have the image align left? I have tried align="left". Stylebot does not seem to be able to remove the tag.

Body:
This will solve your issue

center{
display: inline;
}

ContentLicense: CC BY-SA 4.0


问:
Stripe application fees via the W3C Web Payments API
Stripe provide Web Application Fees payment functionality to their merchants/customers via a native bespoke API. Is there anyway other than this feature request to surface the functionality via the Web Payments API?</p>

答:
Great news!

@adrianhopebailie has detailed a solution right here right now for Web Payment Disbursement functionality that requires no (absolutely ZERO) changes to the Payment Request OR Payment Handler APIs and W3C standards! (Always a bonus :-)

As he correctly points out, the methodData argument is opaque and pretty much down to the autonomous Payment Handler to specify. So Stripe, Square, and PayPal are free to specify to their customers the format/naming-convention for communicating Application Fees between Web App supplier and Stripe.

To quote Adrian's example: -

```<code>const methodData = [
  {
    supportedMethods: "https://square.com/",
    data: {
      parties: [{
        merchantId: "super-mini-cabs",
        portion: 0.1
      },{
        merchantId: "driver-fred",
        portion: 0.9
      }],
    },
  },
  {
    supportedMethods: "https://stripe.com",
    data: {
      application_fee_amount: 1.00,
    },
  },
  {
    supportedMethods: "https://paypal.com",
    data: {
      payouts: [{
        paypalId: 12478764,
        amount: 1.00
      },{
        paypalId: 23448764,
        amount: 9.00
      }],
    },
  },
];
</code>```

Just tell us Paul/Stripe what you need us to tell you and it's done!

Body:
Great news!

@adrianhopebailie has detailed a solution right here right now for Web Payment Disbursement functionality that requires no (absolutely ZERO) changes to the Payment Request OR Payment Handler APIs and W3C standards! (Always a bonus :-)

As he correctly points out, the methodData argument is opaque and pretty much down to the autonomous Payment Handler to specify. So Stripe, Square, and PayPal are free to specify to their customers the format/naming-convention for communicating Application Fees between Web App supplier and Stripe.

To quote Adrian's example: -

const methodData = [
  {
    supportedMethods: "https://square.com/",
    data: {
      parties: [{
        merchantId: "super-mini-cabs",
        portion: 0.1
      },{
        merchantId: "driver-fred",
        portion: 0.9
      }],
    },
  },
  {
    supportedMethods: "https://stripe.com",
    data: {
      application_fee_amount: 1.00,
    },
  },
  {
    supportedMethods: "https://paypal.com",
    data: {
      payouts: [{
        paypalId: 12478764,
        amount: 1.00
      },{
        paypalId: 23448764,
        amount: 9.00
      }],
    },
  },
];

Just tell us Paul/Stripe what you need us to tell you and it's done!


问:
CUDA - linking errors with convolution example
I'm trying to compile the following code by Joe Stam (convolutionapproaches, project with vs2005, I am using VS2010 but compiling with 9.0 engine)

1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaEventDestroy@4 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>main.obj : error LNK2001: unresolved
  external symbol _cudaEventDestroy@4
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaEventElapsedTime@12 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>main.obj : error LNK2001: unresolved
  external symbol
  _cudaEventElapsedTime@12 1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaEventSynchronize@4 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>main.obj : error LNK2001: unresolved
  external symbol
  _cudaEventSynchronize@4 1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaGetLastError@0 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaConfigureCall@32 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaEventRecord@8 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>main.obj : error LNK2001: unresolved
  external symbol _cudaEventRecord@8
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaEventCreate@4 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>main.obj : error LNK2001: unresolved
  external symbol _cudaEventCreate@4
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaMemset@12 referenced in function "float _cdecl
  NaiveGlobalConvolution(unsigned char
  *,unsigned char *,unsigned int,unsigned int,unsigned
  int,int,int)"
  (?NaiveGlobalConvolution@@YAMPAE0IIIHH@Z)
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  _cudaSetupArgument@12 referenced in function "void _cdecl
  device_stub__Z28NaiveGlobalConvolutionKernelPhS_jjjf(unsigned
  char *,unsigned char *,unsigned
  int,unsigned int,unsigned int,float)"
  (?__device_stub__Z28NaiveGlobalConvolutionKernelPhS_jjjf@@YAXPAE0IIIM@Z)
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  ___cudaRegisterVar@32 referenced in function "void _cdecl
  _sti_cudaRegisterAll_59_tmpxft_00000a3c_00000000_3_ConvolutionCudaFunctions_cpp1_ii_imgTex(void)"
  (?sti__cudaRegisterAll_59_tmpxft_00000a3c_00000000_3_ConvolutionCudaFunctions_cpp1_ii_imgTex@@YAXXZ)
  1>ConvolutionCudaFunctions.obj : error
  LNK2019: unresolved external symbol
  ___cudaRegisterTexture@28 referenced in function "void _cdecl

... a lot of other errors...

1>Debug/ConvTest.exe : fatal error
  LNK1120: 35 unresolved externals

This with /MDd for code generation and CUDA C/C++ Runtime Host library.

If I switch to /MTd for both is the same.

What's wrong with this? I tried both the 32 bit and the 64 bit SDK, the toolkit is 6

答: There was a problem with 32/64 bit sdks, I solved by linking with the 32 bit</p>

ContentLicense: CC BY-SA 2.5


问:
jsonwebtoken: expiresIn does not expires?
I am trying to set the token to be expired in one hour following the example from the guide:

```<code>jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 })
</code>```

But the toke never expires in a few hours later:

```<code>curl -XGET -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTU4OTAzMDI3LCJleHAiOjE1NTg5MDY2Mjd9.8uHKDM4Hgy08kw_0CLib2QnzqudeC_RsIlh8e9uURT0' 'http://localhost:3000/api/users'
</code>```

Have I missing something?

How do I set it to expire in 1 or 5 minutes?

The code for verifying the token:

```<code>import jwt from 'jsonwebtoken'
import config from '../config'

export default async (ctx, next) => {
  try {
    await next()

    if(ctx.req.hasOwnProperty('headers') && ctx.req.headers.hasOwnProperty('authorization')) {
      ctx.req.user = jwt.verify(ctx.req.headers['authorization'], config.JWT_SECRET, function (err, payload) {
        console.log(payload)
      })
    } else {
      // If there is no autorization header, return 401 status code.
      ctx.throw(401, 'Protected resource, use Authorization header to get access')
    }
  } catch (err) {
    ctx.status = err.status || 500

    ctx.type = 'json'
    ctx.body = {
      status: ctx.status,
      message: err.message
    }

    ctx.app.emit('error', err, ctx)
  }
}
</code>```

答:
From the docs it says that

This means that the exp field should contain the number of seconds since the epoch.

So:

1 minute => 60

5 minutes => 60 * 5

Which gives

```<code>// Expires in 5 minutes
jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 5 * 60 })
</code>```

Body:
I am trying to set the token to be expired in one hour following the example from the guide:

jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 })

But the toke never expires in a few hours later:

curl -XGET -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTU4OTAzMDI3LCJleHAiOjE1NTg5MDY2Mjd9.8uHKDM4Hgy08kw_0CLib2QnzqudeC_RsIlh8e9uURT0' 'http://localhost:3000/api/users'

Have I missing something?

How do I set it to expire in 1 or 5 minutes?

The code for verifying the token:

import jwt from 'jsonwebtoken'
import config from '../config'

export default async (ctx, next) => {
  try {
    await next()

    if(ctx.req.hasOwnProperty('headers') && ctx.req.headers.hasOwnProperty('authorization')) {
      ctx.req.user = jwt.verify(ctx.req.headers['authorization'], config.JWT_SECRET, function (err, payload) {
        console.log(payload)
      })
    } else {
      // If there is no autorization header, return 401 status code.
      ctx.throw(401, 'Protected resource, use Authorization header to get access')
    }
  } catch (err) {
    ctx.status = err.status || 500

    ctx.type = 'json'
    ctx.body = {
      status: ctx.status,
      message: err.message
    }

    ctx.app.emit('error', err, ctx)
  }
}

Body:
From the docs it says that

This means that the exp field should contain the number of seconds since the epoch.

So:

1 minute => 60

5 minutes => 60 * 5

Which gives

// Expires in 5 minutes
jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 5 * 60 })


问:
Display Park Name and Time outside Loop
How do I display the parkName and time outside the for loop?

for(int i=1; i<=5; i++) {
    System.out.print("\n\nEnter park name: ");
    String parkName = input.nextLine();

    System.out.print("Enter run time: ");
    String runTime = input.nextLine();

    //convert to double the user input which was a string
    //create new variable for time as double

    Double time = Double.parseDouble(runTime);
    parkRunner.recordNewRuns(parkName, time);
}
```

答:
Make ParkRunner Object Arraylist outside of the the loop and inside the loop save your inputs in that array list and after getting inputs, Print them using a another for loop.

```<code>ArrayList<ParkRunner> parkRunnerList = new ArrayList<>();

for(int i=1; i<=5; i++) {
    System.out.print("\n\nEnter park name: ");
    String parkName = input.nextLine();

    System.out.print("Enter run time: ");
    String runTime = input.nextLine();

    //convert to double the user input which was a string
    //create new variable for time as double

    Double time = Double.parseDouble(runTime);
    ParkRunner temp = new ParkRunner(parkName, runTime);
    parkRunnerList.add(temp);
}

for(int j=1; j<=5; j++) {
    System.out.println("id:- "+ (j));
    System.out.println("name:- "+ parkRunnerList.get(j).getName());
    System.out.println("time:- "+ parkRunnerList.get(j).getRunTime());
}
</code>```

It is the simplest way of doing it.

Title: Display Park Name and Time outside Loop

Body:
Make ParkRunner Object Arraylist outside of the the loop and inside the loop save your inputs in that array list and after getting inputs, Print them using a another for loop.

ArrayList<ParkRunner> parkRunnerList = new ArrayList<>();

for(int i=1; i<=5; i++) {
    System.out.print("\n\nEnter park name: ");
    String parkName = input.nextLine();

    System.out.print("Enter run time: ");
    String runTime = input.nextLine();

    //convert to double the user input which was a string
    //create new variable for time as double

    Double time = Double.parseDouble(runTime);
    ParkRunner temp = new ParkRunner(parkName, runTime);
    parkRunnerList.add(temp);
}

for(int j=1; j<=5; j++) {
    System.out.println("id:- "+ (j));
    System.out.println("name:- "+ parkRunnerList.get(j).getName());
    System.out.println("time:- "+ parkRunnerList.get(j).getRunTime());
}

It is the simplest way of doing it.


问:
Override components like MuiTab that use media queries
I'm trying to provide CSS overrides for MuiTab to increase the font-size.

Using the documentation about CSS overrides on material-ui I've managed to increase font size for most elements, however I got stuck at elements that use media queries as they produce more specific CSS rules than the ones I provide with my overrides.

theme.ts :

```<code>import { createMuiTheme } from '@material-ui/core';

const fontSizeStyle = {
  fontSize: '1rem',
};

const fontFamilyStyle = {
  fontFamily: '"Ubuntu", sans-serif'
};

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        ...fontFamilyStyle,
        ...fontSizeStyle,
      },
      label: fontSizeStyle,
    },
  }
});

export default theme;
</code>```

This produces following css rules applied to a MuiTab:

The rule is generated by the following file:

https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Tab/Tab.js

```<code>[theme.breakpoints.up('md')]: {
  fontSize: theme.typography.pxToRem(13),
},
</code>```

Does anyone have an example how to override this media query using createMuiTheme function? I don't have the breakpoints, so perhaps I need to specify breakpoints as well to be able to use them in my overrides

Kind regards

答:
Specify it as follows

let theme = createMuiTheme({});

theme = {
  ...theme,
  overrides: {
    MuiTab: {
      root: {
        [theme.breakpoints.up("xs")]: {
          minHeight: 10
        }
      }
    }
  }
}

export default theme;```

theme.breakpoints exposes four helper methods to create CSS media queries:

theme.breakpoints.up(key)

theme.breakpoints.down(key)

theme.breakpoints.only(key)

theme.breakpoints.between(start, end)

Where each key is a breakpoint and matches with a fixed screen width.
Allowed key values are xs|sm|md|lg|xl

See material-ui docs for more info

Body:
I'm trying to provide CSS overrides for MuiTab to increase the font-size.

Using the documentation about CSS overrides on material-ui I've managed to increase font size for most elements, however I got stuck at elements that use media queries as they produce more specific CSS rules than the ones I provide with my overrides.

theme.ts :

import { createMuiTheme } from '@material-ui/core';

const fontSizeStyle = {
  fontSize: '1rem',
};

const fontFamilyStyle = {
  fontFamily: '"Ubuntu", sans-serif'
};

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        ...fontFamilyStyle,
        ...fontSizeStyle,
      },
      label: fontSizeStyle,
    },
  }
});

export default theme;

This produces following css rules applied to a MuiTab:

The rule is generated by the following file:

https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Tab/Tab.js

[theme.breakpoints.up('md')]: {
  fontSize: theme.typography.pxToRem(13),
},

Does anyone have an example how to override this media query using createMuiTheme function? I don't have the breakpoints, so perhaps I need to specify breakpoints as well to be able to use them in my overrides

Kind regards

Body:
Specify it as follows

let theme = createMuiTheme({});

theme = {
  ...theme,
  overrides: {
    MuiTab: {
      root: {
        [theme.breakpoints.up("xs")]: {
          minHeight: 10
        }
      }
    }
  }
}

export default theme;

theme.breakpoints exposes four helper methods to create CSS media queries:

theme.breakpoints.up(key)

theme.breakpoints.down(key)

theme.breakpoints.only(key)

theme.breakpoints.between(start, end)

Where each key is a breakpoint and matches with a fixed screen width.
Allowed key values are xs|sm|md|lg|xl

See material-ui docs for more info


问:
Fetching python class name while using abstract classes with `abc` library
I want to extract the python class name while using abstract classes with abc library. I unfortunately instead receive the class name ABCMeta.

import abc

class A(abc.ABC)
    pass

class B(A)
    pass

print(A.__class__.__name__)  # output: 'ABCMeta'
print(B.__class__.__name__)  # output: 'ABCMeta'
print(str(A))  # output: "<class '__main__.A'>"
print(str(B))  # output: "<class '__main__.B'>"

```

<p>I expect that I should receive the output as below</p>

<pre class="lang-py prettyprint-override"><code>print(A.__class__.__name__)  # output: 'A'
print(B.__class__.__name__)  # output: 'B'
</code>```

The str(A) and str(B) seems to print the class name so I assume the class name can be extracted from somewhere. But nonetheless, I am not interested to use str to parse and get the class name.

答:
Use just the __name__ property

```<code>print(A.__name__)
#A
</code>```

A in itself is a class, if you use A.__class__ you are getting it’s metaclass therefore it’s metaclass’ name.

Body:
I want to extract the python class name while using abstract classes with abc library. I unfortunately instead receive the class name ABCMeta.

import abc

class A(abc.ABC)
    pass

class B(A)
    pass

print(A.__class__.__name__)  # output: 'ABCMeta'
print(B.__class__.__name__)  # output: 'ABCMeta'
print(str(A))  # output: "<class '__main__.A'>"
print(str(B))  # output: "<class '__main__.B'>"

I expect that I should receive the output as below

print(A.__class__.__name__)  # output: 'A'
print(B.__class__.__name__)  # output: 'B'

The str(A) and str(B) seems to print the class name so I assume the class name can be extracted from somewhere. But nonetheless, I am not interested to use str to parse and get the class name.

Body:
Use just the __name__ property

print(A.__name__)
#A

A in itself is a class, if you use A.__class__ you are getting it’s metaclass therefore it’s metaclass’ name.


问:
How to check if all array values are blank in Javascript
I have an array like:

```<code>["", "", "", "1", "", ""]
</code>```

I want to alert when all the array values are blanks, i.e, when the array is like this:

```<code>["", "", "", "", "", ""]
</code>```

How can I achieve this.

答:
You can always use a basic for loop as a solution for your problem:

function allBlanks(arr)
{
    for (var i = 0; i < arr.length; i++)
    {
        if (arr[i] !== "") return false;
    }

    return true;
}

console.log(allBlanks(["", "", "", "1", "", ""]));
console.log(allBlanks(["", "", "", "", "", ""]));
console.log(allBlanks(["", [], "", null, undefined, ""]));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Body:
I have an array like:

["", "", "", "1", "", ""]

I want to alert when all the array values are blanks, i.e, when the array is like this:

["", "", "", "", "", ""]

How can I achieve this.

Body:
You can always use a basic for loop as a solution for your problem:

function allBlanks(arr)
{
    for (var i = 0; i < arr.length; i++)
    {
        if (arr[i] !== "") return false;
    }

    return true;
}

console.log(allBlanks(["", "", "", "1", "", ""]));
console.log(allBlanks(["", "", "", "", "", ""]));
console.log(allBlanks(["", [], "", null, undefined, ""]));

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
How to access global variable
From the following code, I wish for the output of names to contain an array of names taken from a column in a csv file. When the function is run, the array remains empty. Why?

```<code>def cp_identifier():
    global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])
</code>```

Current Output:

```<code>[]
</code>```

Expected output:

```<code>['Card Name', 'Card Name', ... , 'Card Name']
</code>```

答:
Why dont you use something like the following, rather than using a global variable

```<code>def cp_identifier():
    names = array_dec()
    print(names)
    return names

def array_dec():
    names = []
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')

        for row in card_list_table:
            names.append(row["Card Name"])
    return names
if __name__ == "__main__":
    names = cp_identifier()
    print(names)
</code>```

Title: How to access global variable

Body:
From the following code, I wish for the output of names to contain an array of names taken from a column in a csv file. When the function is run, the array remains empty. Why?

def cp_identifier():
    global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])

Current Output:

[]

Expected output:

['Card Name', 'Card Name', ... , 'Card Name']

Body:
Why dont you use something like the following, rather than using a global variable

def cp_identifier():
    names = array_dec()
    print(names)
    return names

def array_dec():
    names = []
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')

        for row in card_list_table:
            names.append(row["Card Name"])
    return names
if __name__ == "__main__":
    names = cp_identifier()
    print(names)


问:
how to deploy pytorch neural network for production code in Unity
I have a neural network trained in pytorch that I'd like to deploy into a Unity app. What's the best way to do it? I'm also interested in allowing the user to further train the neural network in the Unity app, which I guess would require to integrate some part of pytorch into Unity (maybe there's a way to integrate pytorch's C++ / torchscript API with Unity?). If anybody has experience with this, I'd like to know what the best alternatives are.</p>

答:
This is not a complete answer. But it should be able to help you progress further.

Essentially you'd as I see it just need to be able to run Python code within C# code. In this case in collaboration with Unity's framework.

I did some searching and came across 4 partial solutions:

Unity python interpreter: https://forum.unity.com/threads/python-interpreter-in-unity.86461/

An example of running code with IronPython in Unity: https://gamedev.stackexchange.com/questions/123526/a-python-script-controlling-a-unity-game

Communication example between Unity3D C# and Python, using ZeroMQ: https://unitylist.com/p/hc8/Unity3D-Python-Communication

Implementing language support for other languages yourself via an XML file: https://forum.unity.com/threads/add-multiple-language-support-to-your-unity-projects.206271/

Once you're able to run the code you'd then need to refer to the location of your python files. This way you should be able to run it if the environment you run it in also has Python installed and set up correctly.

You must ensure that the files are in your project on deployment. And that Unity can access them.

Hope this helps you.


问:
Printing the Current Value of a loop to a widget
I am trying to print the current value of a for loop to a QT Widget and I am not sure which widget is the right way to go and how to get the current value passed to the widget.

In detail:
I have a Signal from a pushButton which will do a set of calculations for variable t. And for every iteration N, I would like to print the iteration number N and variable t value to the Widget (textEdit, LineEdit or what ever is most appropriate). Sort of like what qDebug() does. For Example:

```<code>double t = 0.0;
for (int N=1; N<50; N++)
{
 t = t + 2;
  ui->textEdit->text(QString::number(t));
}
</code>```

And I would like my widget to have
N                  t
itertionNumber currentValue_of_t

答:
A simple way to do this is to use the QTextEdit::append method.

```<code>double t = 0.0;

for (int N = 1; N < 50; N++)
{
    t += 2.0;
    QString line = QString("\tN=%1\tt=%2").arg(N).arg(t);
    te.append(line);
}
</code>```

This logs:

    N=1     t=2
    N=2     t=4
    N=3     t=6
    N=4     t=8
    N=5     t=10
    ...
    N=45    t=90
    N=46    t=92
    N=47    t=94
    N=48    t=96
    N=49    t=98
```

Regarding the widget to use text-edits are the most appropriate as they allow for new-lines (line-edits don't). The Application Output panel of QtCreator most likely uses a text-edit.

Demo on Github

Body:
I am trying to print the current value of a for loop to a QT Widget and I am not sure which widget is the right way to go and how to get the current value passed to the widget.

In detail:
I have a Signal from a pushButton which will do a set of calculations for variable t. And for every iteration N, I would like to print the iteration number N and variable t value to the Widget (textEdit, LineEdit or what ever is most appropriate). Sort of like what qDebug() does. For Example:

double t = 0.0;
for (int N=1; N<50; N++)
{
 t = t + 2;
  ui->textEdit->text(QString::number(t));
}

And I would like my widget to have
N                  t
itertionNumber currentValue_of_t

Body:
A simple way to do this is to use the QTextEdit::append method.

double t = 0.0;

for (int N = 1; N < 50; N++)
{
    t += 2.0;
    QString line = QString("\tN=%1\tt=%2").arg(N).arg(t);
    te.append(line);
}

This logs:

    N=1     t=2
    N=2     t=4
    N=3     t=6
    N=4     t=8
    N=5     t=10
    ...
    N=45    t=90
    N=46    t=92
    N=47    t=94
    N=48    t=96
    N=49    t=98

Regarding the widget to use text-edits are the most appropriate as they allow for new-lines (line-edits don't). The Application Output panel of QtCreator most likely uses a text-edit.

Demo on Github


问:
Create a basic contact form that send a mail
I have a template for a form already designed (using bootstrap-studio).
I just need to get the data from it and send it as a mail to my email id.
It would also be great if the page could get redirected to a new one after pressing submit.

I have already set up the settings.py and am able to send the 'message' part of the form.

```<code>    if request.method == 'POST':
        message = request.POST['message']

        send_mail(
            'Contact Form',
            message,
            settings.EMAIL_HOST_USER,
            ['abcd@gmail.com'],
            fail_silently=False

        )
    return render(request, 'contact.html')
</code>```

What I need is to be able to send an email with 'message', 'name', 'email',
included in it.

I tried writing

```<code>message = request.POST['message','name','email']
</code>```

Didn't get expected results.

contact.html:

```<code>        <form method="post">
            {% csrf_token %}
            <h2 class="text-center">Contact us</h2>
            <div class="form-group"><input class="form-control" type="text" name="name" placeholder="Name"></div>
            <div class="form-group"><input class="form-control " type="email" name="email" placeholder="Email"></div>
            <div class="form-group"><textarea class="form-control" name="message" placeholder="Message" rows="14"></textarea></div>
            <div class="form-group"><button class="btn btn-primary" type="submit">send </button></div>
        </form>
    </div>
</code>```

答:
To fetch data from form you have to do it invidually.

```<code>message = request.POST["message"]
name = request.POST["name"]
email = request.POST["email"]
</code>```

Then you can use this data to pass into send_mail() function as arguments.
To redirect to another page after submitting the form, use this logic:

from django.shortcuts import redirect

    if request.method == 'POST':
        message = request.POST['message']
        name = request.POST["name"]
        email = request.POST["email"]

        send_mail(
            'Contact Form',
            message,
            settings.EMAIL_HOST_USER,
            [email,],
            fail_silently=False

        )
        return redirect("/home/")
    return render(request, 'contact.html')
```

Body:
I have a template for a form already designed (using bootstrap-studio).
I just need to get the data from it and send it as a mail to my email id.
It would also be great if the page could get redirected to a new one after pressing submit.

I have already set up the settings.py and am able to send the 'message' part of the form.

    if request.method == 'POST':
        message = request.POST['message']

        send_mail(
            'Contact Form',
            message,
            settings.EMAIL_HOST_USER,
            ['abcd@gmail.com'],
            fail_silently=False

        )
    return render(request, 'contact.html')

What I need is to be able to send an email with 'message', 'name', 'email',
included in it.

I tried writing

message = request.POST['message','name','email']

Didn't get expected results.

contact.html:

        <form method="post">
            {% csrf_token %}

Contact us

<input class="form-control" type="text" name="name" placeholder="Name">

<input class="form-control " type="email" name="email" placeholder="Email">

<textarea class="form-control" name="message" placeholder="Message" rows="14"></textarea>

<button class="btn btn-primary" type="submit">send </button>

        </form>

Body:
To fetch data from form you have to do it invidually.

message = request.POST["message"]
name = request.POST["name"]
email = request.POST["email"]

Then you can use this data to pass into send_mail() function as arguments.
To redirect to another page after submitting the form, use this logic:

from django.shortcuts import redirect

    if request.method == 'POST':
        message = request.POST['message']
        name = request.POST["name"]
        email = request.POST["email"]

        send_mail(
            'Contact Form',
            message,
            settings.EMAIL_HOST_USER,
            [email,],
            fail_silently=False

        )
        return redirect("/home/")
    return render(request, 'contact.html')


问:
How to use quick replies with attachment
In official documentation of quick replies says:

Quick Replies work with all message types including text message, image and template attachments.

But when i try send it with template_type: button, I got error:

```<code>{
    "error": {
        "message": "(#100) Only one of text or attachment can be specified",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "H8w+ZfRbBub"
    }
}
</code>```

That I try to send:

```<code>{
    "recipient": {"id": "234567890"},
    "message": {
        "text": "TEXT_MESSAGE",
        "quick_replies": [
            {
                "content_type": "text",
                "title": "SOME_TITLE_1",
                "payload": "PAY_LOAD_1"
            },
            {
            "content_type": "text",
            "title": "SOME_TITLE_2",
            "payload": "PAY_LOAD_2"
            }
        ],
        "attachment": {
            "type": "template",
            "payload": {
                "template_type": "button",
                "text": "TEXT_MESSAGE",
                "buttons": [
                    {
                        "title": "READ_MORE_BUTTON",
                        "type": "postback",
                        "payload": "look:1:c"
                    }
                ]
            }
        }
    }
}
</code>```

when I sent without message.text, I got error:

```<code>{
    "error": {
        "message": "(#100) Cannot use both CTA and quick reply",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "C0DDxGzaUUj"
    }
}
</code>```

What is CTA?

How send quick replies with attachment?

答:
This worked for me while using dialogflow</p>

```<code>{
  "facebook": {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
           {
            "title":"Welcome!",
            "image_url":"https://petersfancybrownhats.com/company_image.png",
            "subtitle":"We have the right hat for everyone.",
            "default_action": {
              "type": "web_url",
              "url": "https://petersfancybrownhats.com/view?item=103",
              "webview_height_ratio": "tall"
            },
            "buttons":[
              {
                "type":"web_url",
                "url":"https://petersfancybrownhats.com",
                "title":"View Website"
              },{
                "type":"postback",
                "title":"Start Chatting",
                "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }
            ]
          }
        ]
      }
    },
     "quick_replies":[
      {
        "content_type":"text",
        "title":"Search",
        "payload":"<POSTBACK_PAYLOAD>",
        "image_url":"http://example.com/img/red.png"
      },
      {
        "content_type":"location"
      }
    ]
  }
}
</code>```

Body:
In official documentation of quick replies says:

Quick Replies work with all message types including text message, image and template attachments.

But when i try send it with template_type: button, I got error:

{
    "error": {
        "message": "(#100) Only one of text or attachment can be specified",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "H8w+ZfRbBub"
    }
}

That I try to send:

{
    "recipient": {"id": "234567890"},
    "message": {
        "text": "TEXT_MESSAGE",
        "quick_replies": [
            {
                "content_type": "text",
                "title": "SOME_TITLE_1",
                "payload": "PAY_LOAD_1"
            },
            {
            "content_type": "text",
            "title": "SOME_TITLE_2",
            "payload": "PAY_LOAD_2"
            }
        ],
        "attachment": {
            "type": "template",
            "payload": {
                "template_type": "button",
                "text": "TEXT_MESSAGE",
                "buttons": [
                    {
                        "title": "READ_MORE_BUTTON",
                        "type": "postback",
                        "payload": "look:1:c"
                    }
                ]
            }
        }
    }
}

when I sent without message.text, I got error:

{
    "error": {
        "message": "(#100) Cannot use both CTA and quick reply",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "C0DDxGzaUUj"
    }
}

What is CTA?

How send quick replies with attachment?

Body:
This worked for me while using dialogflow

{
  "facebook": {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
           {
            "title":"Welcome!",
            "image_url":"https://petersfancybrownhats.com/company_image.png",
            "subtitle":"We have the right hat for everyone.",
            "default_action": {
              "type": "web_url",
              "url": "https://petersfancybrownhats.com/view?item=103",
              "webview_height_ratio": "tall"
            },
            "buttons":[
              {
                "type":"web_url",
                "url":"https://petersfancybrownhats.com",
                "title":"View Website"
              },{
                "type":"postback",
                "title":"Start Chatting",
                "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }
            ]
          }
        ]
      }
    },
     "quick_replies":[
      {
        "content_type":"text",
        "title":"Search",
        "payload":"<POSTBACK_PAYLOAD>",
        "image_url":"http://example.com/img/red.png"
      },
      {
        "content_type":"location"
      }
    ]
  }
}


问:
How could I get part of json from a js file code string(got by fs.readFileSync)?
```<code>var a = {
    properties:{
        title:{
            type:"String",
            value:"sss"
        },
        content:{
            type:"String",
            value:"555"
        }
    },
    data:{
        abc:123,
        ddd:444,
        fff:"dd"
    },
    methods: {
        abc () {

        },
        cde () {

        }
    }
}
</code>```

<p>The code above is a text string from js file(got by fs.readFileSync). I need to get the part of 'properties' string by regex and parse it to a json object. </p>

答:
You can use object Destructuring

const {properties} = a;

var a = {
  properties: {
    title: {
      type: "String",
      value: "sss"
    },
    content: {
      type: "String",
      value: "555"
    }
  },
  data: {
    abc: 123,
    ddd: 444,
    fff: "dd"
  },
  methods: {
    abc() {

    },
    cde() {

    }
  }
}

const {properties} = a;

console.log(properties);```

or access using dot operator

a.properties

or

a["properties"]

Body:
var a = {
    properties:{
        title:{
            type:"String",
            value:"sss"
        },
        content:{
            type:"String",
            value:"555"
        }
    },
    data:{
        abc:123,
        ddd:444,
        fff:"dd"
    },
    methods: {
        abc () {

        },
        cde () {

        }
    }
}

The code above is a text string from js file(got by fs.readFileSync). I need to get the part of 'properties' string by regex and parse it to a json object.

Body:
You can use object Destructuring

const {properties} = a;

var a = {
  properties: {
    title: {
      type: "String",
      value: "sss"
    },
    content: {
      type: "String",
      value: "555"
    }
  },
  data: {
    abc: 123,
    ddd: 444,
    fff: "dd"
  },
  methods: {
    abc() {

    },
    cde() {

    }
  }
}

const {properties} = a;

console.log(properties);

or access using dot operator

a.properties

or

a["properties"]


问:
Set user agent with WebView with react-native
I want to modify the user agent string in a WebView so that on the server side I can detect that the request has come from my react-native app. I want to do this using the source prop in the WebView.

How do I do this for IOS and Android?

答:
For iOS, you can use WKWebView instead of WebView which support userAgent setting.
https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md#useragent</p>


问:
What is the fastest way to compare two text files, not counting moved lines as different
I have two files which are very large in size say 50000 lines each. I need to compare these two files and identify the changes. However, the catch is if a line is present at different position, it should not be shown as different.

For eg, consider this

File A.txt

```<code>xxxxx
yyyyy
zzzzz
</code>```

File B.txt

```<code>zzzzz
xxxx
yyyyy
</code>```

So if this is the content of the file. My code should give the output as xxxx(or both xxxx and xxxxx).

Ofcourse the easiest way would be storing each line of the file in a

```<code>List< String>
</code>```

and comparing with the other

```<code>List< String>.
</code>```

But this seems to be taking a lot of time. I have also tried using the DiffUtils in java. But it doesnt recognize the lines present in diferent line numbers as same. So is there any other algorithm that might help me?

答:
I think this will be useful,</p>

```<code>   BufferedReader reader1 = new BufferedReader(new FileReader("C:\\file1.txt"));

    BufferedReader reader2 = new BufferedReader(new FileReader("C:\\file2.txt"));

    String line1 = reader1.readLine();

    String line2 = reader2.readLine();

    boolean areEqual = true;

    int lineNum = 1;

    while (line1 != null || line2 != null)
    {
        if(line1 == null || line2 == null)
        {
            areEqual = false;

            break;
        }
        else if(! line1.equalsIgnoreCase(line2))
        {
            areEqual = false;

            break;
        }

        line1 = reader1.readLine();

        line2 = reader2.readLine();

        lineNum++;
    }

    if(areEqual)
    {
        System.out.println("Two files have same content.");
    }
    else
    {
        System.out.println("Two files have different content. They differ at line "+lineNum);

        System.out.println("File1 has "+line1+" and File2 has "+line2+" at line "+lineNum);
    }

    reader1.close();

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

Body:
I have two files which are very large in size say 50000 lines each. I need to compare these two files and identify the changes. However, the catch is if a line is present at different position, it should not be shown as different.

For eg, consider this

File A.txt

xxxxx
yyyyy
zzzzz

File B.txt

zzzzz
xxxx
yyyyy

So if this is the content of the file. My code should give the output as xxxx(or both xxxx and xxxxx).

Ofcourse the easiest way would be storing each line of the file in a

List< String>

and comparing with the other

List< String>.

But this seems to be taking a lot of time. I have also tried using the DiffUtils in java. But it doesnt recognize the lines present in diferent line numbers as same. So is there any other algorithm that might help me?

Body:
I think this will be useful,

   BufferedReader reader1 = new BufferedReader(new FileReader("C:\\file1.txt"));

    BufferedReader reader2 = new BufferedReader(new FileReader("C:\\file2.txt"));

    String line1 = reader1.readLine();

    String line2 = reader2.readLine();

    boolean areEqual = true;

    int lineNum = 1;

    while (line1 != null || line2 != null)
    {
        if(line1 == null || line2 == null)
        {
            areEqual = false;

            break;
        }
        else if(! line1.equalsIgnoreCase(line2))
        {
            areEqual = false;

            break;
        }

        line1 = reader1.readLine();

        line2 = reader2.readLine();

        lineNum++;
    }

    if(areEqual)
    {
        System.out.println("Two files have same content.");
    }
    else
    {
        System.out.println("Two files have different content. They differ at line "+lineNum);

        System.out.println("File1 has "+line1+" and File2 has "+line2+" at line "+lineNum);
    }

    reader1.close();

    reader2.close();


问:
Java coding style 2019
I am curious to know the current coding style for java. My team is forcing  to use {} for one liner if statements. Although we used to have braces for one liners current java source code does not use braces for one liner if statements anymore and I myself am inclined towards the same.

Python dropped braces altogether.

However I do not see any particular style guide in 2019.. The oracle doc still refers to the 1997 coding style.

What would be correct coding or is it something more to do with developer's preference?

```<code>   foo();

   if (condition)
      doSomething();

   bar();
</code>```

vs

```<code>   foo();

   if (condition) {
      doSomething();
   }

   bar();
</code>```

Edit 1:  As Kartik mentioned we can write one liners like this as well:

```<code>   if (condition) doSomething();
</code>```

For me, it as a developers preference and I am ok with both the approaches but in my current team some developers are of opinion not using braces is a BAD coding practice. I saw the java source code and found in many places braces are omitted. So, I don't believe this to be true. As for google coding style, it was also there for many years and many people continue to use the same. But for new code are there any new guidelines?

Edit 2: This question is marked as opinion based and put on hold

I want to clarify that I am NOT looking for opinions. I am more looking for standard guidelines which Oracle (or java open source communities) might have put forward regarding best practices as of today (2019). Most practices java/google are very old dating back to 1996 and may not be relevant today. Even if there is some reference in some new books and some can share those details it will be very helfpul

答:
Write as you like. I prefer brackets.
They help navigate the code.</p>

Title: Java coding style 2019

Body:
I am curious to know the current coding style for java. My team is forcing  to use {} for one liner if statements. Although we used to have braces for one liners current java source code does not use braces for one liner if statements anymore and I myself am inclined towards the same.

Python dropped braces altogether.

However I do not see any particular style guide in 2019.. The oracle doc still refers to the 1997 coding style.

What would be correct coding or is it something more to do with developer's preference?

   foo();

   if (condition)
      doSomething();

   bar();

vs

   foo();

   if (condition) {
      doSomething();
   }

   bar();

Edit 1:  As Kartik mentioned we can write one liners like this as well:

   if (condition) doSomething();

For me, it as a developers preference and I am ok with both the approaches but in my current team some developers are of opinion not using braces is a BAD coding practice. I saw the java source code and found in many places braces are omitted. So, I don't believe this to be true. As for google coding style, it was also there for many years and many people continue to use the same. But for new code are there any new guidelines?

Edit 2: This question is marked as opinion based and put on hold

I want to clarify that I am NOT looking for opinions. I am more looking for standard guidelines which Oracle (or java open source communities) might have put forward regarding best practices as of today (2019). Most practices java/google are very old dating back to 1996 and may not be relevant today. Even if there is some reference in some new books and some can share those details it will be very helfpul


问:
removing spaces in DataFrame using SCALA. (I have loaded CSV file into RDD then trying to remove spaces from it
I have data with un-wanted spaces & Null values in my CSV file. I have loaded this file into spark RDD till here no problem. Now I have to remove spaces and null values from this RDD. How to do that can anyone help me pls?

```<code>object Oracle {def main(args: Array[String]): Unit = {
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
System.setProperty("hadoop.home.dir","D:\\hadoop\\");
val spark = SparkSession.builder().appName("Schema").master("local[*]").getOrCreate()

import spark.implicits._
import org.apache.spark.sql.functions._
val inpp = spark.read.csv("file:///C:/Users/user/Desktop/xyz.csv")
inpp.show()

val df = inpp.toDF("name")

inpp.select(
    col("name"),
    regexp_replace(col("name"), "\\s+$", ""),
    rtrim(col("name")),
    length(col("name"))
    ).show() }}
</code>```

Here is my data with un-wanted spaces and  null values.

答:
You can provide these options in the csv reader to trim the data and later filter the irrelevant ones:</p>

```<code>val df = spark.read
.format("csv")
.option("ignoreLeadingWhiteSpace", "true")
.option("ignoreTrailingWhiteSpace", "true")
.option("inferSchema", "true")
.option("header", "true")
.load("file:///C:/Users/user/Desktop/xyz.csv")
.filter(col("name").isNotNull)
.show()
</code>```

Body:
I have data with un-wanted spaces & Null values in my CSV file. I have loaded this file into spark RDD till here no problem. Now I have to remove spaces and null values from this RDD. How to do that can anyone help me pls?

object Oracle {def main(args: Array[String]): Unit = {
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
System.setProperty("hadoop.home.dir","D:\\hadoop\\");
val spark = SparkSession.builder().appName("Schema").master("local[*]").getOrCreate()

import spark.implicits._
import org.apache.spark.sql.functions._
val inpp = spark.read.csv("file:///C:/Users/user/Desktop/xyz.csv")
inpp.show()

val df = inpp.toDF("name")

inpp.select(
    col("name"),
    regexp_replace(col("name"), "\\s+$", ""),
    rtrim(col("name")),
    length(col("name"))
    ).show() }}

Here is my data with un-wanted spaces and  null values.

Body:
You can provide these options in the csv reader to trim the data and later filter the irrelevant ones:

val df = spark.read
.format("csv")
.option("ignoreLeadingWhiteSpace", "true")
.option("ignoreTrailingWhiteSpace", "true")
.option("inferSchema", "true")
.option("header", "true")
.load("file:///C:/Users/user/Desktop/xyz.csv")
.filter(col("name").isNotNull)
.show()


问:
Auto Copy and Paste Cell Values not Formula to another Cell
I also need to get your help for the same issue. I need to copy the cell values and not the formulas automatically to the other Cell, "automatically" meaning, I don't need to click, use mouse, or any other means to do that, like once theres a value on that specific cell (which is derived from a formula), the value will automatically be copied and pasted in the other cell (without any intervention from my part) (Only the value is copied not the formula)

Note:
The cell should contain only the copied value and not the formula.

Scenario:

A1 Cell : has 250 value

B1 Cell : has a vlookup formula to search for the value of A1 cell (I need to use VLOOKUP as there's a lot of items in the list, and it is "Dynamic", the reason I cannot just use formula "=A1" to get the value directly)

C1 Cell : Needs to copy and paste only the plain value from B1 cell which is 250, not including the vlookup formula, it should be automatically copied without any intervention (Cannot use VBA code / Macro as it will be run in excel online)

Thanks!!

答:
Just use abasic Excel formula.

Example:

The source data is in cell A1.

You want to copy the same value to cell B1.

In cell B1 write:

```<code>=A1
</code>```

That is all.

Additionally, you need to configure correctly the strategy for calculating the formulas:

Body:
Just use abasic Excel formula.

Example:

The source data is in cell A1.

You want to copy the same value to cell B1.

In cell B1 write:

=A1

That is all.

Additionally, you need to configure correctly the strategy for calculating the formulas:


问:
Way to call hooks from button events in react
This is my first time to develop a react application. I intend to make an Api call when user clicked a button. Is it possible to directly call a hook from an event? If yes, how can I call it if the hook was from a different component?

This is the button (different component)

```<code> const paginationButtons = (
    <React.Fragment>
      <Button onClick={() => viewDetails()}>View Details</Button>
    </React.Fragment>
  );

function viewDetails() {
   //Is it Possible to call fetch data.js and pass the url from here?
  }
</code>```

This is the hook for fetch data.js

```<code>import axios from 'axios';
import PropTypes from 'prop-types';
import { useState, useEffect} from 'react';

const propTypes = {
  initialUrl: PropTypes.string.isRequired,
  initialParams: PropTypes.object
}

export const useFetchData = props => {
  PropTypes.checkPropTypes(propTypes, props, 'property', 'useFetchData');

  const { initialUrl, initialParams } = props;

  const [request, setRequest] = useState({
    url: initialUrl,
    params: initialParams
  });
  const [loading, setIsLoading] = useState(false);
  const [error, setError] = useState();
  const [data, setData] = useState([]);

  useEffect(() => {
    const {url, params} = request;

    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await axios(url, {params: {...params}});
        setIsLoading(false);
        setData(result.data);
      } catch(err) {
        setIsLoading(false);
        setError(err);
      }
    }

    fetchData();
  }, [request]);

  const doFetch = (params) => {
    setRequest({url: request.url, params: params});
  };
  return {loading, error, data, doFetch};
}

</code>```

Thank you very much for your help.

答:
What you intend to do is possible, but in my opinion, it shouldn't be done in a real-world application. Here's why.

First, let's consider why we would want to use a hook. React function components had no way of preserving local state and handling lifecycle events between rerenders. This is why hooks were introduced.

Before I use a hook, I would ask myself, "Do I need to handle component state or the component life-cycle?". If not, using a hook is either overkill or an anti-pattern.

In your example, let's consider what you may be trying to do with the viewDetails function. Obviously, you want to do the fetch call, but what do you intend to do afterward? Let's see some possibilities...

Update the dom imperatively: You shouldn't do imperative operations unless there is a very specific reason. Let's assume, you want to show an alert, then, of course, you can call an imperative API (like notie.js or sweet-alert for instance).

Update the dom reactively: This is the most common scenario I think. In such a case, you should either call some setState function, or fire an event to be captured by another component. In either case, there's no use of using a hook for fetching data.

Thus instead of trying to call a hook like useFetchData, you should call a function like doFetchData.

I am not suggesting that you should get rid of the useFetchData hook. It's just, they serve different purposes. It makes sense to use the hook for any fetch operations that should happen at load time rather than as a response to a user action.

Now that I have given my opinion, here's one way you can trigger a hook based on user action.

```<code>// Here we are using a shouldFetch flag to conditionally call a function
function useFetch(url, options, shouldFetch, setShouldFetch) {
    const [state, setState] = useState({});
    useEffect(() => {
        if (shouldFetch) {
            doFetch(url, options)
                // set the fetch result to local state
                .then(data => {
                   setState(data)
                   setShouldFetch(false) // avoid infinite calls
                })
        }
    });

    return [state]; // You can maybe add fetch status as well
}
</code>```

Now you can use it like this,

```<code>function MyComponent() {
    const [shouldFetch, setShouldFetch] = useState(false);
    const [fetchData] = useFetch('url', {}, shouldFetch, setShouldFetch);

    return (
        <Button onClick={() => {setShouldFetch(true)}}>Click Me</Button>
    )
}

</code>```

But really, you shouldn't use a hook this way. A regular doFetchData call is the way to go. Call some setState functions to preserve the fetched data if you need to.

Body:
This is my first time to develop a react application. I intend to make an Api call when user clicked a button. Is it possible to directly call a hook from an event? If yes, how can I call it if the hook was from a different component?

This is the button (different component)

 const paginationButtons = (
    <React.Fragment>
      <Button onClick={() => viewDetails()}>View Details</Button>
    </React.Fragment>
  );

function viewDetails() {
   //Is it Possible to call fetch data.js and pass the url from here?
  }

This is the hook for fetch data.js

import axios from 'axios';
import PropTypes from 'prop-types';
import { useState, useEffect} from 'react';

const propTypes = {
  initialUrl: PropTypes.string.isRequired,
  initialParams: PropTypes.object
}

export const useFetchData = props => {
  PropTypes.checkPropTypes(propTypes, props, 'property', 'useFetchData');

  const { initialUrl, initialParams } = props;

  const [request, setRequest] = useState({
    url: initialUrl,
    params: initialParams
  });
  const [loading, setIsLoading] = useState(false);
  const [error, setError] = useState();
  const [data, setData] = useState([]);

  useEffect(() => {
    const {url, params} = request;

    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await axios(url, {params: {...params}});
        setIsLoading(false);
        setData(result.data);
      } catch(err) {
        setIsLoading(false);
        setError(err);
      }
    }

    fetchData();
  }, [request]);

  const doFetch = (params) => {
    setRequest({url: request.url, params: params});
  };
  return {loading, error, data, doFetch};
}

Thank you very much for your help.

Body:
What you intend to do is possible, but in my opinion, it shouldn't be done in a real-world application. Here's why.

First, let's consider why we would want to use a hook. React function components had no way of preserving local state and handling lifecycle events between rerenders. This is why hooks were introduced.

Before I use a hook, I would ask myself, "Do I need to handle component state or the component life-cycle?". If not, using a hook is either overkill or an anti-pattern.

In your example, let's consider what you may be trying to do with the viewDetails function. Obviously, you want to do the fetch call, but what do you intend to do afterward? Let's see some possibilities...

Update the dom imperatively: You shouldn't do imperative operations unless there is a very specific reason. Let's assume, you want to show an alert, then, of course, you can call an imperative API (like notie.js or sweet-alert for instance).

Update the dom reactively: This is the most common scenario I think. In such a case, you should either call some setState function, or fire an event to be captured by another component. In either case, there's no use of using a hook for fetching data.

Thus instead of trying to call a hook like useFetchData, you should call a function like doFetchData.

I am not suggesting that you should get rid of the useFetchData hook. It's just, they serve different purposes. It makes sense to use the hook for any fetch operations that should happen at load time rather than as a response to a user action.

Now that I have given my opinion, here's one way you can trigger a hook based on user action.

// Here we are using a shouldFetch flag to conditionally call a function
function useFetch(url, options, shouldFetch, setShouldFetch) {
    const [state, setState] = useState({});
    useEffect(() => {
        if (shouldFetch) {
            doFetch(url, options)
                // set the fetch result to local state
                .then(data => {
                   setState(data)
                   setShouldFetch(false) // avoid infinite calls
                })
        }
    });

    return [state]; // You can maybe add fetch status as well
}

Now you can use it like this,

function MyComponent() {
    const [shouldFetch, setShouldFetch] = useState(false);
    const [fetchData] = useFetch('url', {}, shouldFetch, setShouldFetch);

    return (
        <Button onClick={() => {setShouldFetch(true)}}>Click Me</Button>
    )
}

But really, you shouldn't use a hook this way. A regular doFetchData call is the way to go. Call some setState functions to preserve the fetched data if you need to.


问:
Getting "Server refused to allocate pty" error when trying to connect to Bitbucket via SSH on Windows
I'm trying to hook up Mercurial to Bitbucket on a PC and it's being really tough. I followed the instructions here:

http://www.codza.com/mercurial-with-ssh-setup-on-windows

and I'm running pageant set to my private key. I typed this at the command line:

plink -v hg@bitbucket.org and I get the following output:

```<code>C:\mypath>plink -v hg@bitbucket.org
"skipped for briefness"
Access granted
Opened channel for session
Server refused to allocate pty
Started a shell/command
conq: invalid command syntax
Server sent command exit status 0
Disconnected: All channels closed
</code>```

My friend got the same error when he tried it on his PC. Can you help explain what the problem is or how to debug?

Running plink ssh://hg@bitbucket.org gives Using username ssh://hg and Disconnected: No supported authentication methods available.

Thanks for your help,
Kevin

答:
You cannot connect to Bitbucket like that and get a login shell -- their backend process (called conq) will only accept Mercurial commands. With TortoiseHg, you don't have to do anything special -- so hg push ssh://hg@bitbucket.org/... should just work out of the box.

Using HTTPS is generally a nicer option for Bitbucket and as we discussed on IRC, there are plenty of ways to cache the passwords.

Body:
I'm trying to hook up Mercurial to Bitbucket on a PC and it's being really tough. I followed the instructions here:

http://www.codza.com/mercurial-with-ssh-setup-on-windows

and I'm running pageant set to my private key. I typed this at the command line:

plink -v hg@bitbucket.org and I get the following output:

C:\mypath>plink -v hg@bitbucket.org
"skipped for briefness"
Access granted
Opened channel for session
Server refused to allocate pty
Started a shell/command
conq: invalid command syntax
Server sent command exit status 0
Disconnected: All channels closed

My friend got the same error when he tried it on his PC. Can you help explain what the problem is or how to debug?

Running plink ssh://hg@bitbucket.org gives Using username ssh://hg and Disconnected: No supported authentication methods available.

Thanks for your help,
Kevin


问:
Bash get the command that is piping into a script
Take the following example:

```<code>ls -l | grep -i readme | ./myscript.sh
</code>```

What I am trying to do is get ls -l | grep -i readme as a string variable in myscript.sh. So essentially I am trying to get the whole command before the last pipe to use inside myscript.sh.

Is this possible?

答:
I think that it is possible, have a look at this example:

```<code>#!/bin/bash
result=""
while read line; do
  result=$result"${line}"
done
echo $result
</code>```

Now run this script using a pipe, for example:

```<code>ls -l /etc | ./script.sh
</code>```

I hope that will be helpful for you :)

Body:
Take the following example:

ls -l | grep -i readme | ./myscript.sh

What I am trying to do is get ls -l | grep -i readme as a string variable in myscript.sh. So essentially I am trying to get the whole command before the last pipe to use inside myscript.sh.

Is this possible?

Body:
I think that it is possible, have a look at this example:

#!/bin/bash
result=""
while read line; do
  result=$result"${line}"
done
echo $result

Now run this script using a pipe, for example:

ls -l /etc | ./script.sh

I hope that will be helpful for you :)


答:
Recall that a metaclass is the type of a class, while a class is the type of its instances.

If we have a = A(), a is of type A, and A is of type abc.ABCMeta. Therefore, you should naturally expect that A.__class__ and B.__class__ both return abc.ABCMeta, since they are instances of it!

What you want is the names of A and B themselves, which you can get with A.__name__ and B.__name__ respectively.

Title: Fetching python class name while using abstract classes with `abc` library

Body:
I want to extract the python class name while using abstract classes with abc library. I unfortunately instead receive the class name ABCMeta.

import abc

class A(abc.ABC)
    pass

class B(A)
    pass

print(A.__class__.__name__)  # output: 'ABCMeta'
print(B.__class__.__name__)  # output: 'ABCMeta'
print(str(A))  # output: "<class '__main__.A'>"
print(str(B))  # output: "<class '__main__.B'>"

I expect that I should receive the output as below

print(A.__class__.__name__)  # output: 'A'
print(B.__class__.__name__)  # output: 'B'

The str(A) and str(B) seems to print the class name so I assume the class name can be extracted from somewhere. But nonetheless, I am not interested to use str to parse and get the class name.


问:
php variable scope
i'm confused about the php variable scope.
such as:

```<code>while(true){
    $var = "yes , it is a test!";
  }
  printf($var)
</code>```

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

答:
Loop does not have any scope in PHP. variable is simply available outside the loop.

just echo outside the loop;

echo $var;

Title: php variable scope

Body:
i'm confused about the php variable scope.
such as:

while(true){
    $var = "yes , it is a test!";
  }
  printf($var)

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .


问:
TFS 2018 - Error MSB1008 (build using VS)
I have an Installed instance of TFS 2015 where I had configured a build using VS.
Everything is working.

In this instance I have configured the build like this:

I installed TFS 2018 in another machine and I am trying to create the some build.
I configured TFS 2018 like this:

I don't know why but even though I kept the same build config (as in TFS 2015) I am getting some error:

```<code> MSBUILD : error MSB1008: Only one project can be specified.
 Switch: TFS2018\Agent1\_work\3\a
 For switch syntax, type "MSBuild /help"
 Process 'msbuild.exe' exited with code '1'.
</code>```

Screenshot:

Can you help me with this?
How can I fix this error?

EDIT: Here goes my Nuget Restore config.

答:
This error  MSBUILD : error MSB1008: Only one project can be specified usually caused because of the space in arguments, but not quoted.

Since the path contains spaces (between Agents and TFS2018, see your error logs), the TFS2018 part is considered a new argument and MSBuild doesn't know what to do with it.

So modify your MSBuild Arguments, put the path directory to your file in quotation marks (") to indicate the directory is one argument, then try again.

```<code>/p:OutDir="$(build.stagingDirectory)" /p:UesWPP_CopyWebApplication=true /p:PipelineDependsOnBuild=false
</code>```

Body:
I have an Installed instance of TFS 2015 where I had configured a build using VS.
Everything is working.

In this instance I have configured the build like this:

I installed TFS 2018 in another machine and I am trying to create the some build.
I configured TFS 2018 like this:

I don't know why but even though I kept the same build config (as in TFS 2015) I am getting some error:

 MSBUILD : error MSB1008: Only one project can be specified.
 Switch: TFS2018\Agent1\_work\3\a
 For switch syntax, type "MSBuild /help"
 Process 'msbuild.exe' exited with code '1'.

Screenshot:

Can you help me with this?
How can I fix this error?

EDIT: Here goes my Nuget Restore config.

Body:
This error  MSBUILD : error MSB1008: Only one project can be specified usually caused because of the space in arguments, but not quoted.

Since the path contains spaces (between Agents and TFS2018, see your error logs), the TFS2018 part is considered a new argument and MSBuild doesn't know what to do with it.

So modify your MSBuild Arguments, put the path directory to your file in quotation marks (") to indicate the directory is one argument, then try again.

/p:OutDir="$(build.stagingDirectory)" /p:UesWPP_CopyWebApplication=true /p:PipelineDependsOnBuild=false


问:
filter by key in javascript
I would like to filter by key in javascript.

I have a ajax function , on passing id, will result obj1 in success one after other.
I would like to combine all results by key and push to single object.
How to do the following in javascript.

```<code>var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}

//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

</code>```

Expected Output:

```<code>var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}
</code>```

答:
You can try as below, this will the merge the values if result already have the values</p>

```<code>//
 var id =["trans", "fund"];
 var result = {};

 function getObj(obj){
   id.map(val => {
      if(result[val]) { result[val] = [...result[val], ...obj[val]]}
      else result[val] = obj[val]
   })
 }

//on first call
    var obj1={
      country: "SG",
      trans: [{
        rate: 20,
        members: 100
      }]
    }
    getObj(obj1)
/*
{
  trans: [{
    rate: 20,
    members: 100
  }]
}
*/

    //on second call
    var obj1={
      country: "TH",
      fund: [{
        rate: 20,
        members: 100
      }]
    }
getObj(obj2)
/*
{
  trans: [{
    rate: 20,
    members: 100
   }],
   fund: [{
     rate: 20,
     members: 100
   }]
}
*/
</code>```

Title: filter by key in javascript

Body:
I would like to filter by key in javascript.

I have a ajax function , on passing id, will result obj1 in success one after other.
I would like to combine all results by key and push to single object.
How to do the following in javascript.

var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}

//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

Expected Output:

var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}

Body:
You can try as below, this will the merge the values if result already have the values

//
 var id =["trans", "fund"];
 var result = {};

 function getObj(obj){
   id.map(val => {
      if(result[val]) { result[val] = [...result[val], ...obj[val]]}
      else result[val] = obj[val]
   })
 }

//on first call
    var obj1={
      country: "SG",
      trans: [{
        rate: 20,
        members: 100
      }]
    }
    getObj(obj1)
/*
{
  trans: [{
    rate: 20,
    members: 100
  }]
}
*/

    //on second call
    var obj1={
      country: "TH",
      fund: [{
        rate: 20,
        members: 100
      }]
    }
getObj(obj2)
/*
{
  trans: [{
    rate: 20,
    members: 100
   }],
   fund: [{
     rate: 20,
     members: 100
   }]
}
*/


问:
Visual Studio Code Is Not Able To Launch Django Project From Debugger
I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework.  I am developing on a 2018 MacBook Pro.  I am able to launch my web applications by launching them in the terminal using:

```<code>python3 manage.py runserver
</code>```

However, I want to be able to launch my application through the debugger.  To try and do this, I navigated to the debug section, created the launch.json file, and changed my configuration in the drop down to Python: Django.  Here is are my configurations from the file.

```<code>    {
        "name": "Python: Django",
        "type": "python",
        "request": "launch",
        "program": "${workspaceFolder}/manage.py",
        "console": "integratedTerminal",
        "args": [
            "runserver",
            "--noreload",
            "--nothreading"
        ],
        "django": true
    },
</code>```

When I try to run the debugger using the green play arrow, I get the following exception:

Exception has occurred: ImportError
  Couldn't import Django. Are you
  sure it's installed and available on your PYTHONPATH environment
  variable? Did you forget to activate a virtual environment?   File
  "/Users/justinoconnor/Desktop/Rapid
  Prototyping/Projects/hello_django/manage.py", line 14, in
      ) from exc

Launching the VS Code debugger with this configuration should be the same as running python manage.py runserver --noreload --nothreading, but it is not working.  I'm thinking it is because on the MacBook I have to use the "python3" command rather than "python", but I did not see anything in the documentation that would allow me to specify this in the launch.json configuration file.

Does anyone know how to resolve this so that when I run the debugger it automatically executes/saves my project?  I don't understand why this is not working when I can type python3 manage.py runserver into the terminal and it will execute just fine.

答:
Same issue caused to my VS Code environment even launching VS Code after activating venv (Python virtual environment).

The VS Code also displayed the Python Environment option "Python 3.7.3 64 bit" on the Status Bar. On first sight, this python environment option looks correct.

But, my issue resolved after applying Boregore's comment. Python Environment option related with venv python needs to be selected as an interpreter.

I selected the correct Python Environment option related with venv (in my case i.e. ~/.virtualenvs/djangodev/bin/python), by applying following steps,

Select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P).

Start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too)

Select Python Environment option showing venv path (in my case, i.e. ~/.virtualenvs/djangodev/bin/python)

Now, VS Code displays the Python Environment option related with venv, (in my case, i.e. "Python 3.7.3 64 bit ('djangodev': venv)" on the Status Bar.

Re-run debug steps.

(Many thanks to Boregore for providing solution, this is just a re-elaboration of his comment to the actual question)

Body:
I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework.  I am developing on a 2018 MacBook Pro.  I am able to launch my web applications by launching them in the terminal using:

python3 manage.py runserver

However, I want to be able to launch my application through the debugger.  To try and do this, I navigated to the debug section, created the launch.json file, and changed my configuration in the drop down to Python: Django.  Here is are my configurations from the file.

    {
        "name": "Python: Django",
        "type": "python",
        "request": "launch",
        "program": "${workspaceFolder}/manage.py",
        "console": "integratedTerminal",
        "args": [
            "runserver",
            "--noreload",
            "--nothreading"
        ],
        "django": true
    },

When I try to run the debugger using the green play arrow, I get the following exception:

Exception has occurred: ImportError
  Couldn't import Django. Are you
  sure it's installed and available on your PYTHONPATH environment
  variable? Did you forget to activate a virtual environment?   File
  "/Users/justinoconnor/Desktop/Rapid
  Prototyping/Projects/hello_django/manage.py", line 14, in
      ) from exc

Launching the VS Code debugger with this configuration should be the same as running python manage.py runserver --noreload --nothreading, but it is not working.  I'm thinking it is because on the MacBook I have to use the "python3" command rather than "python", but I did not see anything in the documentation that would allow me to specify this in the launch.json configuration file.

Does anyone know how to resolve this so that when I run the debugger it automatically executes/saves my project?  I don't understand why this is not working when I can type python3 manage.py runserver into the terminal and it will execute just fine.


问:
send a json from one component to another without being seen in the url of the target component
I'm trying to send a json from componentA to componentB. The problem is that the json appears in the url. How can I make the json not appear?

routing

```<code>const appRoutes: Routes = [
  {path: 'componentA', component: componentA},
  {path: 'componentB', component: componentA, data : {}},
  {path: '**', component: NotFoundComponent}
];
</code>```

template componentA

```<code><a *ngFor="let item aArray" (click)="fn_sendJson(item)">Send jSON</a>
</code>```

componentA .ts

```<code>this.aArray={"name":"pablo","countrys":["colombia","perú"],"lastname":"ramirez"}
.
.
fn_sendJson(item:any){
 this.router.navigate(['componentB', {"data": JSON.stringify(item)}]);
}
</code>```

ComponentB .ts

```<code>constructor(
 private router : Router,
 private route: ActivatedRoute
 ) {
 sub:any;
 jsonReceived:any
 .
 .
 this.sub = this.route.params
 .subscribe(v => this.jsonReceived =JSON.parse(v.data));
</code>```

I have not found a way to avoid converting the original json to a string, I would like to know if there is an effective method of sending such as the json, and get it without needing it to be present in the url. Thank you

答:
You can use data service like below

first, create one service in that

```<code>  share: Subject<any> = new Subject();
  share$: Observable<any> = this.share.asObservable();
</code>```

and then define one method

```<code>shareDate(data:object){
 this.share.next(data);
}
</code>```

In the component A

```<code>fn_sendJson(item:any){
 this.router.navigate(['componentB']);
 this.serviceName.shareDate({"data": JSON.stringify(item)})
}
</code>```

and in the component B you can access the data like below

```<code>ngOnInit() {
this.serviceName.share$.subscribe(
  res=>{
        console.log(res)//you will get the data
    }
  }
</code>```

Hope it will solve your problem!

Body:
I'm trying to send a json from componentA to componentB. The problem is that the json appears in the url. How can I make the json not appear?

routing

const appRoutes: Routes = [
  {path: 'componentA', component: componentA},
  {path: 'componentB', component: componentA, data : {}},
  {path: '**', component: NotFoundComponent}
];

template componentA

Send jSON

componentA .ts

this.aArray={"name":"pablo","countrys":["colombia","perú"],"lastname":"ramirez"}
.
.
fn_sendJson(item:any){
 this.router.navigate(['componentB', {"data": JSON.stringify(item)}]);
}

ComponentB .ts

constructor(
 private router : Router,
 private route: ActivatedRoute
 ) {
 sub:any;
 jsonReceived:any
 .
 .
 this.sub = this.route.params
 .subscribe(v => this.jsonReceived =JSON.parse(v.data));

I have not found a way to avoid converting the original json to a string, I would like to know if there is an effective method of sending such as the json, and get it without needing it to be present in the url. Thank you

Body:
You can use data service like below

first, create one service in that

  share: Subject<any> = new Subject();
  share$: Observable<any> = this.share.asObservable();

and then define one method

shareDate(data:object){
 this.share.next(data);
}

In the component A

fn_sendJson(item:any){
 this.router.navigate(['componentB']);
 this.serviceName.shareDate({"data": JSON.stringify(item)})
}

and in the component B you can access the data like below

ngOnInit() {
this.serviceName.share$.subscribe(
  res=>{
        console.log(res)//you will get the data
    }
  }

Hope it will solve your problem!


问:
How to save attribute value on xml file?
I'm trying to save a value in my xml file. In the code below, the line "s.Attribute("Value").Value = value; break;" executes and the file is saved but it doesn't change the value of the attribute

```<code>     public void CustomSettingXML_WriteValue(string key, string value)
    {

        XDocument doc = XDocument.Load(xmlFile);

        var elements = from x in XElement.Load(xmlFile).Elements("Item") select x;

        foreach (var s in elements)
        {
            if (s.Attribute("Text").Value == key)
            {
                s.Attribute("Value").Value = value;
                doc.Save(@xmlFile);
               break;
            }
        }
    }
</code>```

答:
There are in fact two things that might have to vary.

a) You are reading the Xml using XDocument.Load as well as XElement.Load. While altering, you are using Elements, and while saving you are using XDocument.

b) Since hierarchy in XML is (Items.Item), it would be better you use Descendants to parse the elements.

Full Code

```<code>public void CustomSettingXML_WriteValue(string key, string value)
{
    XDocument doc = XDocument.Load(xmlFile);
    var elements = from x in doc.Descendants("Item") select x;
    foreach (var s in elements)
    {

        if (s.Attribute("Text").Value == key)
        {
            s.Attribute("Value").Value = value;
            doc.Save(@xmlFile);
           break;
        }
    }
}
</code>```

Body:
I'm trying to save a value in my xml file. In the code below, the line "s.Attribute("Value").Value = value; break;" executes and the file is saved but it doesn't change the value of the attribute

     public void CustomSettingXML_WriteValue(string key, string value)
    {

        XDocument doc = XDocument.Load(xmlFile);

        var elements = from x in XElement.Load(xmlFile).Elements("Item") select x;

        foreach (var s in elements)
        {
            if (s.Attribute("Text").Value == key)
            {
                s.Attribute("Value").Value = value;
                doc.Save(@xmlFile);
               break;
            }
        }
    }

Body:
There are in fact two things that might have to vary.

a) You are reading the Xml using XDocument.Load as well as XElement.Load. While altering, you are using Elements, and while saving you are using XDocument.

b) Since hierarchy in XML is (Items.Item), it would be better you use Descendants to parse the elements.

Full Code

public void CustomSettingXML_WriteValue(string key, string value)
{
    XDocument doc = XDocument.Load(xmlFile);
    var elements = from x in doc.Descendants("Item") select x;
    foreach (var s in elements)
    {

        if (s.Attribute("Text").Value == key)
        {
            s.Attribute("Value").Value = value;
            doc.Save(@xmlFile);
           break;
        }
    }
}


问:
Java Regex for positive numeric and few special symbol validation for a particular pattern
I have a String ex=1,2,3,4,5-7,8,9,10-15,34,898

In the above string my regex has to validate the following things

ex String should contain only numeric values(0-9) and two special characters
,- alone.

Regex should validate ex should not start with space,cama(,) and
hyfun(-),same should not end.

After cama(,) should have numeric value alone.

String ex should support only positive numbers 0-9.

After hyfun(-) there should be a positive numeric value alone.

It should not allow space any where in the string.

hyfun(-) symbol is the range indicator in the above ex String, so it should
prefix and suffix with a positive numeric value.

cama(,) is a separator for each element in the string, so it should succeeded  with positive numeric value.

so for i have tried with individual regex which making my code clumsy and few cases its failing

```<code> //Regex Pattern for validating number alone as its starting and ending of the string
        Pattern digits = Pattern.compile ("^[0-9](.*[0-9])?$");
 //Regex Pattern for validating special character along with the digits alone
        Pattern special = Pattern.compile("^[0-9,-]*$");
//Regex Pattern for validating only positive numeric values alone
        Pattern positiveNumeric = Pattern.compile("^\\d+$");
</code>```

答:
Here is a general regex pattern which should work:

```<code>^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$
</code>```

Demo

The quantity \d+(?:-\d+)? says to match one or more digits, followed optionally by a hyphen and then one or more other digits.  Then, we append this to end of the pattern:

```<code>(?:,\d+(?:-\d+)?)*
</code>```

This matches a comma followed by another digit/range of digits group, zero or more times.

Note that the ^ and $ anchors may not be necessary in your Java code if you are using, e.g. String#matches, which automatically adds these anchors.

Body:
I have a String ex=1,2,3,4,5-7,8,9,10-15,34,898

In the above string my regex has to validate the following things

ex String should contain only numeric values(0-9) and two special characters
,- alone.

Regex should validate ex should not start with space,cama(,) and
hyfun(-),same should not end.

After cama(,) should have numeric value alone.

String ex should support only positive numbers 0-9.

After hyfun(-) there should be a positive numeric value alone.

It should not allow space any where in the string.

hyfun(-) symbol is the range indicator in the above ex String, so it should
prefix and suffix with a positive numeric value.

cama(,) is a separator for each element in the string, so it should succeeded  with positive numeric value.

so for i have tried with individual regex which making my code clumsy and few cases its failing

 //Regex Pattern for validating number alone as its starting and ending of the string
        Pattern digits = Pattern.compile ("^[0-9](.*[0-9])?$");
 //Regex Pattern for validating special character along with the digits alone
        Pattern special = Pattern.compile("^[0-9,-]*$");
//Regex Pattern for validating only positive numeric values alone
        Pattern positiveNumeric = Pattern.compile("^\\d+$");

Body:
Here is a general regex pattern which should work:

^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$

Demo

The quantity \d+(?:-\d+)? says to match one or more digits, followed optionally by a hyphen and then one or more other digits.  Then, we append this to end of the pattern:

(?:,\d+(?:-\d+)?)*

This matches a comma followed by another digit/range of digits group, zero or more times.

Note that the ^ and $ anchors may not be necessary in your Java code if you are using, e.g. String#matches, which automatically adds these anchors.


问:
How to connect to localhost and external database from docker container
I have two docker containers, nginx and php, from which I want to access mysql server running on host machine and sql server on remote machine.

Have tried change the network type from "bridge" to "host" but it returns errors.

```<code>version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - /var/www/:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - mynetwork
    php:
        image: php:fpm
        volumes:
            - /var/www/:/code
        networks:
           - mynetwork
networks:
    mynetwork:
       driver: bridge
</code>```

I'm expecting php code running in my containers can connect to those two databases.

Note: I don't using docker run to run container, instead I'm using docker-compose up -d so I just want to edit the docker-compose.yml file.

答:
In your php service declaration you have to add something like:

```<code>extra_hosts:
      - "local_db:host_ip"
</code>```

Where local_db is the name you will configure in your database connection string and host_ip is the IP of your host on the local network.

You have to make sure that your php code does not try to connect to "localhost" because that will not work. You need to use the server name "local_db" (in my example).

You do the same thing for the remote database, just make sure the IP is reachable.

You can remove the network declaration because it is not needed.

Body:
I have two docker containers, nginx and php, from which I want to access mysql server running on host machine and sql server on remote machine.

Have tried change the network type from "bridge" to "host" but it returns errors.

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - /var/www/:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - mynetwork
    php:
        image: php:fpm
        volumes:
            - /var/www/:/code
        networks:
           - mynetwork
networks:
    mynetwork:
       driver: bridge

I'm expecting php code running in my containers can connect to those two databases.

Note: I don't using docker run to run container, instead I'm using docker-compose up -d so I just want to edit the docker-compose.yml file.

Body:
In your php service declaration you have to add something like:

extra_hosts:
      - "local_db:host_ip"

Where local_db is the name you will configure in your database connection string and host_ip is the IP of your host on the local network.

You have to make sure that your php code does not try to connect to "localhost" because that will not work. You need to use the server name "local_db" (in my example).

You do the same thing for the remote database, just make sure the IP is reachable.

You can remove the network declaration because it is not needed.


问:
Concatenation Full Name with Miss Ms in javascript
My Question is that i have one option set which is Gender inside two option Male and Female and one field Fullname. I want that when i select male inside option set the full name is concate with ms and when we select female full name is concate with miss</p>

答:
```<code>I applied this code and now it's working
==================================================
</code>```

function GenderValidation(executionContext) {
  var formContext = executionContext.getFormContext();
  var FullName, gender;
  if (formContext.getAttribute("cms_fullname") != null) {
    var FullName = formContext.getAttribute("cms_fullname").getValue();
  }

  if (formContext.getAttribute("cms_gender") != null) {
    var gender = formContext.getAttribute("cms_gender").getValue();
  }
  if (gender == 175650000) {
    FullName = "Miss" + ' ' + FullName;

    formContext.getAttribute("cms_fullname").setValue(FullName);
  } else if (gender == 175650001) {
    FullName = "Ms" + ' ' + FullName;

    formContext.getAttribute("cms_fullname").setValue(FullName);
  }

}```

Body:
I applied this code and now it's working
==================================================

function GenderValidation(executionContext) {
  var formContext = executionContext.getFormContext();
  var FullName, gender;
  if (formContext.getAttribute("cms_fullname") != null) {
    var FullName = formContext.getAttribute("cms_fullname").getValue();
  }

  if (formContext.getAttribute("cms_gender") != null) {
    var gender = formContext.getAttribute("cms_gender").getValue();
  }
  if (gender == 175650000) {
    FullName = "Miss" + ' ' + FullName;

    formContext.getAttribute("cms_fullname").setValue(FullName);
  } else if (gender == 175650001) {
    FullName = "Ms" + ' ' + FullName;

    formContext.getAttribute("cms_fullname").setValue(FullName);
  }

}