问:
Sharing same git submodule for both project
So i've a 3 project A, B and C

Project A is the core library
Project B is an extension of A (so project A is requiered to work)
Project C is an application build with project A & B

Project A

|            |

|            |

|        Project B

|            |

|            |

Project C

My projects setup are like this

ProjectA/srcs/

ProjectB/lib/ProjectA (submodule)

ProjectB/srcs/

ProjectC/lib/ProjectA (submodule)

ProjectC/lib/ProjectB (submodule)

ProjectC/lib/ProjectB/lib/ProjectA (submodule)

ProjectC/srcs

How can i use the same ProjectA (bold) submodule in ProjectC without modifying ProjectB ?

Thanks for your help

答:
I would use symlinks to achieve the goal.

That is if ProjectC needs the same version of ProjectA as ProjectB make

ProjectC/lib/ProjectA to be a symlink to ../ProjectB/lib/ProjectA


来源: stackexchange

问:
Prolog, building list with conditional clauses
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

```<code>goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).
</code>```

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

答:
try the ignore/1 predicate:

```<code>goal(Stuff) :-
    do_something(X)
    ignore(only_do_this_if_something(Y)),
    always_do_this(Z).
</code>```

ignore/1 calls the only argument and succeeds whenever it fails or not:

```<code>ignore(X) :- X, !.
ignore(_).
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

Body:
try the ignore/1 predicate:

goal(Stuff) :-
    do_something(X)
    ignore(only_do_this_if_something(Y)),
    always_do_this(Z).

ignore/1 calls the only argument and succeeds whenever it fails or not:

ignore(X) :- X, !.
ignore(_).


问:
google sheets sum on previous rows data + constant variable
I'm currently facing a problem which I cannot solve, would appreciate help.

a link to the spreadsheet

click here

now, here is the problem.
I want H to be calculated by the sum of previous months(H)+ portfolio size(K8) * G of the current row. in array formula so I won't need to add the function each time I create a new row.

but if it exceeds 10,000 that it will be G(current row)*10,000.

for example:

row 4, IF(portfolio size + SUM (H2:H3)>10000,G4*10000,G4* (portfolio size(K8) + SUM (H2:H3)))

row 5, IF(portfolio size + SUM (H2:H4)>10000,G4*10000,G4* (portfolio size(K8) + SUM (H2:H4)))
 and so on.

would appreciate the help

答:
try:

```<code>=ARRAYFORMULA(IF(A2:A="",,IF(K8+IF(A2:A="",,
 {0; MMULT(TRANSPOSE((ROW(B2:B)<=TRANSPOSE(ROW(B2:B)))*G2:G*K8),
 SIGN(G2:G)^0)})>K8,G2:G*K8, (K8+IF(A2:A="",,
 {0; MMULT(TRANSPOSE((ROW(B2:B)<=TRANSPOSE(ROW(B2:B)))*G2:G*K8),
 SIGN(G2:G)^0)}))*G2:G)))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
try:

=ARRAYFORMULA(IF(A2:A="",,IF(K8+IF(A2:A="",,
 {0; MMULT(TRANSPOSE((ROW(B2:B)<=TRANSPOSE(ROW(B2:B)))*G2:G*K8),
 SIGN(G2:G)^0)})>K8,G2:G*K8, (K8+IF(A2:A="",,
 {0; MMULT(TRANSPOSE((ROW(B2:B)<=TRANSPOSE(ROW(B2:B)))*G2:G*K8),
 SIGN(G2:G)^0)}))*G2:G)))


问:
CSV file with Arabic characters is displayed as symbols in Excel
I am using python to extract Arabic tweets from twitter and save it as a CSV file, but when I open the saved file in excel the Arabic language displays as symbols. However, inside python, notepad, or word, it looks good.

May I know where is the problem?

答:
Excel is known to have an awful csv import sytem. Long story short if on same system you import a csv file that you have just exported, it will work smoothly. Else, the csv file is expected to use the Windows system encoding and delimiter.

A rather awkward but robust system is to use LibreOffice or Oracle OpenOffice. Both are far beyond Excel on any feature but the csv module: they will allow you to specify the delimiters and optional quoting characters along with the encoding of the csv file and you will be able to save the resulting file in xslx.


问:
TypeError: undefined is not an object (evaluating 'event.target.value')
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

```<code>export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}
</code>```

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

答:
Just try with below code::

handleChange(inputText) {
    this.setState({
      email: inputText,
    });
}

handleEmailChange(inputText) {
    this.setState({
      email: inputText,
    });
}

handlePasswordChange(inputText) {
    this.setState({
      password: inputText,
    });
}

<TextInput
        style={{ backgroundColor: '#f8f8ff' }}
        value={email}
        onChangeText={this.handleChange}
        label="Adresse email"
        mode="outlined"
/>
```

<p>or you can use like this also</p>

<pre class="lang-js prettyprint-override"><code><TextInput
        style={{ backgroundColor: '#f8f8ff' }}
        value={email}
        onChangeText={(email) => { this.setState({ email }) }}
        label="Adresse email"
        mode="outlined"
/>

<TextInput
        style={{ backgroundColor: '#f8f8ff' }}
        value={email}
        onChangeText={(password) => { this.setState({ password}) }}
        label="Password"
        mode="outlined"
/>
</code>```

I think this will work.. I have updated the onChangeText props

Body:
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

Body:
Just try with below code::

handleChange(inputText) {
    this.setState({
      email: inputText,
    });
}

handleEmailChange(inputText) {
    this.setState({
      email: inputText,
    });
}

handlePasswordChange(inputText) {
    this.setState({
      password: inputText,
    });
}

<TextInput
        style={{ backgroundColor: '#f8f8ff' }}
        value={email}
        onChangeText={this.handleChange}
        label="Adresse email"
        mode="outlined"
/>

or you can use like this also

<TextInput
        style={{ backgroundColor: '#f8f8ff' }}
        value={email}
        onChangeText={(email) => { this.setState({ email }) }}
        label="Adresse email"
        mode="outlined"
/>

<TextInput
        style={{ backgroundColor: '#f8f8ff' }}
        value={email}
        onChangeText={(password) => { this.setState({ password}) }}
        label="Password"
        mode="outlined"
/>

I think this will work.. I have updated the onChangeText props


问:
typescript: enforcing existing object keys
I would like dropdownAttributes to limited to attributes on DropDownItem interface.

```<code>interface DropDownItem {
    [key: string]: any;
}
</code>```

```<code>interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: string[];
}
</code>```

if DropDownItem did now have dynamic properties I think I could solve this with keyof like this:

```<code>interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: (keyof DropDownItem)[];
}
</code>```

But that does not work now in my case. How to solve?

答:
You can't provide a keyof if the keys are defined in the interface as [key: string]: value, because that means, there can be virtually any key.

Hence also, this keyof DropDownItem code returns string | number, because those are the values that the key can have.

You can avoid this by defining specific keys for the object interface:

```<code>interface DropdownItem {
   id: number,
   text: string,
   isDisplayed: boolean,
}

interface Props {
   dropdownList: DropdownItem[],
   dropdownAttributes: (keyof DropdownItem)[] // ("id" | "text" | "isDisplayed")[]
}
</code>```

Body:
I would like dropdownAttributes to limited to attributes on DropDownItem interface.

interface DropDownItem {
    [key: string]: any;
}

interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: string[];
}

if DropDownItem did now have dynamic properties I think I could solve this with keyof like this:

interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: (keyof DropDownItem)[];
}

But that does not work now in my case. How to solve?

Body:
You can't provide a keyof if the keys are defined in the interface as [key: string]: value, because that means, there can be virtually any key.

Hence also, this keyof DropDownItem code returns string | number, because those are the values that the key can have.

You can avoid this by defining specific keys for the object interface:

interface DropdownItem {
   id: number,
   text: string,
   isDisplayed: boolean,
}

interface Props {
   dropdownList: DropdownItem[],
   dropdownAttributes: (keyof DropdownItem)[] // ("id" | "text" | "isDisplayed")[]
}


问:
Glide assert: java.lang.IllegalArgumentException: You must call this method on the main thread
Has anyone used Glide to fetch images from a background thread? I keep getting this assert:

```<code>java.lang.IllegalArgumentException: You must call this method on the main thread
</code>```

but according to this thread, it should work:

https://github.com/bumptech/glide/issues/310

Yet, I cannot get it to work, unless I call it from the main thread.

Here's is what I am trying to do from the main thread:

```<code>    Glide.get(mContext);
    loadUserImage(userImageUrl);

    // wait 5 seconds before trying again
    int imageLoadingTimeOut = mContext.getResources().getInteger(R.integer.image_loading_time_out);
    if (imageLoadingTimeOut > 0) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (!mUserImageLoaded) {
                    loadUserImage(userImageUrl);
                }
            }
        }, imageLoadingTimeOut);
    }
}
</code>```

and the loadUserImage:

```<code>private boolean mUserImageLoaded = false;

private void loadUserImage(String userImageUrl) {

    if (userImageUrl != null && !userImageUrl.isEmpty() && !mUserImageLoaded) {
        Glide.with(mContext).using(Cloudinary.getUrlLoader(mContext)).load(userImageUrl).crossFade().listener(new RequestListener<String, GlideDrawable>() {

            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                mImageMessageContent.invalidate();
                mUserImageLoaded = true;
                return false;
            }
        }).into(mImageMessageContent);

    } else {
        mImageMessageContent.setVisibility(View.GONE);
    }
}
</code>```

and mContext is just the activity "this" pointer.

Anyway, can I use Glide from a thread different than main?

答:
Here is the Kotlin-way solution</p>

```<code>Glide.with(context).asBitmap().load(photo_url).into(
      BitmapImageViewTarget(imgYourResourceID)
)
</code>```

Body:
Has anyone used Glide to fetch images from a background thread? I keep getting this assert:

java.lang.IllegalArgumentException: You must call this method on the main thread

but according to this thread, it should work:

https://github.com/bumptech/glide/issues/310

Yet, I cannot get it to work, unless I call it from the main thread.

Here's is what I am trying to do from the main thread:

    Glide.get(mContext);
    loadUserImage(userImageUrl);

    // wait 5 seconds before trying again
    int imageLoadingTimeOut = mContext.getResources().getInteger(R.integer.image_loading_time_out);
    if (imageLoadingTimeOut > 0) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (!mUserImageLoaded) {
                    loadUserImage(userImageUrl);
                }
            }
        }, imageLoadingTimeOut);
    }
}

and the loadUserImage:

private boolean mUserImageLoaded = false;

private void loadUserImage(String userImageUrl) {

    if (userImageUrl != null && !userImageUrl.isEmpty() && !mUserImageLoaded) {
        Glide.with(mContext).using(Cloudinary.getUrlLoader(mContext)).load(userImageUrl).crossFade().listener(new RequestListener<String, GlideDrawable>() {

            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                mImageMessageContent.invalidate();
                mUserImageLoaded = true;
                return false;
            }
        }).into(mImageMessageContent);

    } else {
        mImageMessageContent.setVisibility(View.GONE);
    }
}

and mContext is just the activity "this" pointer.

Anyway, can I use Glide from a thread different than main?

Body:
Here is the Kotlin-way solution

Glide.with(context).asBitmap().load(photo_url).into(
      BitmapImageViewTarget(imgYourResourceID)
)


问:
Mysql Query structure for searching two tables
I have two tables sturctured like so:

```<code>Posts Table
id
content

Meta Table
id
post_id
content
name
</code>```

The posts table is the main parent that can have data from the meta table joined with it

```<code>Post Table
id   content
1    My first row

Meta Table
id   post_id  content   name
4    1        2011-5-5    date
5    1        My Heading  heading
6    2        2012-3-3    date
7    2        My Title    heading
</code>```

How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading

I can get them individually

```<code>Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
</code>```

But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things

```<code>Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
   AND (name='heading' AND content='My Heading')
</code>```

Any help would be greatly appreciated, Thanks!

答:
Have you tried this:

```<code>Select *
from posts, meta, meta meta_2
WHERE (meta.post_id = posts.id
      and meta_2.post_id = posts.id)
   AND ((meta.name='date' AND meta.content='2011-5-5')
       and (meta_2.name='heading' AND meta_2.content='My Heading'))
</code>```

Since there are two different meta records that you want to associate with a single post record, you have to select from meta twice (once for the 'date' meta-value and once for the 'heading' meta-value).

Body:
I have two tables sturctured like so:

Posts Table
id
content

Meta Table
id
post_id
content
name

The posts table is the main parent that can have data from the meta table joined with it

Post Table
id   content
1    My first row

Meta Table
id   post_id  content   name
4    1        2011-5-5    date
5    1        My Heading  heading
6    2        2012-3-3    date
7    2        My Title    heading

How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading

I can get them individually

Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')

But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things

Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
   AND (name='heading' AND content='My Heading')

Any help would be greatly appreciated, Thanks!

Body:
Have you tried this:

Select *
from posts, meta, meta meta_2
WHERE (meta.post_id = posts.id
      and meta_2.post_id = posts.id)
   AND ((meta.name='date' AND meta.content='2011-5-5')
       and (meta_2.name='heading' AND meta_2.content='My Heading'))

Since there are two different meta records that you want to associate with a single post record, you have to select from meta twice (once for the 'date' meta-value and once for the 'heading' meta-value).


问:
Print a value in Python from oracle database
I have an issue when displaying  a value in python retrieved from oracle table into CLOB field:

Oracle query:

```<code>SELECT EXTRACTVALUE(xmltype(t.xml), '/DCResponse/ResponseInfo/ApplicationId')
  FROM table t
 WHERE id = 2
</code>```

Value displayed in Oracle Client

```<code>5701200
</code>```

Python code

```<code>import cx_Oracle
conn = cx_Oracle.Connection("user/pwd@localhost:1521/orcl")
cursor = conn.cursor()
cursor.execute("""SELECT EXTRACTVALUE(xmltype(t.xml),'/DCResponse/ResponseInfo/ApplicationId') FROM table t where id = 2""")
for row in cursor:
print(row)
</code>```

Python Console: Nothing is displayed!!! I want to show:5701200

Please Help.
Best Regards
Giancarlo

答:
If you want to iterate over result, use this one:

```<code>for row in cursor.execute("sql_query")
    print(row)
</code>```

or you can fetch each row like this:

```<code>cursor = conn.cursor()
cursor.execute("sql_query")
while True:
    row = cursor.fetchone()
    print(row)
</code>```

Body:
I have an issue when displaying  a value in python retrieved from oracle table into CLOB field:

Oracle query:

SELECT EXTRACTVALUE(xmltype(t.xml), '/DCResponse/ResponseInfo/ApplicationId')
  FROM table t
 WHERE id = 2

Value displayed in Oracle Client

5701200

Python code

import cx_Oracle
conn = cx_Oracle.Connection("user/pwd@localhost:1521/orcl")
cursor = conn.cursor()
cursor.execute("""SELECT EXTRACTVALUE(xmltype(t.xml),'/DCResponse/ResponseInfo/ApplicationId') FROM table t where id = 2""")
for row in cursor:
print(row)

Python Console: Nothing is displayed!!! I want to show:5701200

Please Help.
Best Regards
Giancarlo

Body:
If you want to iterate over result, use this one:

for row in cursor.execute("sql_query")
    print(row)

or you can fetch each row like this:

cursor = conn.cursor()
cursor.execute("sql_query")
while True:
    row = cursor.fetchone()
    print(row)


问:
Update checkbox value to database
I want to update my database entry with an 1 or 0 depends on it is checked or not.

My current code looks like this (only one checkbox, the others are the same just other name):

```<code><form method="post" action="" name="form">
  <label class="switch"><input type="checkbox" name="csgo" value="1"><span class="slider"></span></label> CSGO;
  <input type="submit" value="Save" class="btn btn-primary" name="submit">
 <?php
   $csgoac = isset($_POST["csgo"]) ? $_POST["csgo"] : 0;
   $sql = "UPDATE Users SET csgoactive='".$csgoac."' WHERE ID='1'";
   mysqli_query($db, $sql);
 ?>
</form>
</code>```

I tested it with echo $csgoac; (before the query) and the output was checked = 1 and not checked = 0.

With the query now, it is only updating "0" to the database, what I did wrong on there?

答:
Of course, the first time the page is rendered, $csgoac is 0 because isset($_POST["csgo"]) is false.

If the checkbox is checked and then the form is submitted, $csgoac will be 1.

So the question becomes: What is the result of mysqli_query($db, $sql);?

Are you getting/checking all available feedback? If display_errors is Off in php.ini, there will not be feedback in the browser, but perhaps an error is in the php errorlog. (For instance, in the snippet, $db is not defined, so mysqli_query($db, $sql); fails with Undefined variable: db.).

If the UPDATE is not successful, mysqli_query($db, $sql); will return FALSE and $db->error should tell you what error was encountered.

You could also use mysqli_stmt_affected_rows for additional feedback.

Perhaps add some feedback/error checking to get as much information as possible so you can know what is really happening.

Title: Update checkbox value to database

Body:
I want to update my database entry with an 1 or 0 depends on it is checked or not.

My current code looks like this (only one checkbox, the others are the same just other name):

<form method="post" action="" name="form">
  <input type="checkbox" name="csgo" value="1"> CSGO;
  <input type="submit" value="Save" class="btn btn-primary" name="submit">
 <?php
   $csgoac = isset($_POST["csgo"]) ? $_POST["csgo"] : 0;
   $sql = "UPDATE Users SET csgoactive='".$csgoac."' WHERE ID='1'";
   mysqli_query($db, $sql);
 ?>
</form>

I tested it with echo $csgoac; (before the query) and the output was checked = 1 and not checked = 0.

With the query now, it is only updating "0" to the database, what I did wrong on there?


问:
PyTorch-YOLOv3 Generating Training and Validation Curves
Hello again stackoverflow!  I greatly appreciate this community and the helpful feedback.

I have some other questions that I hope someone can help me with.  I am working with an implementation of PyTorch-YOLOv3 from https://github.com/eriklindernoren/PyTorch-YOLOv3

I have been able to train the model, but now I would like to generate training/validation curves. During training, I get back metrics on each epoch that look like this:

Epoch 1/3001 batch 0/8
Epoch 1/3001 batch 7/8

I'm trying to generate a graph of a metric (loss, recall, precision, accuacy, mAP) versus epoch by logging these metrics to an external .csv file and plotting those values.

Question 1: Does anyone with experience with this YOLOv3 know where the relevant information is?  I know the AP and mAP for each epoch are at the bottom of the second image (epoch 1/3001 batch 7/8).  I'm not sure where to look for the relevant loss, recall, and precision metrics.

Question 2: Does anyone know the difference between the YOLO layer 0 and layer 1.  Would plotting the metrics from each of these layers yield the training and validation curves, respectively?

Question 3: As of two to three months ago, I started receiving the warning the following warning instead of getting the epoch outputs.

/pytorch/aten/src/ATen/native/IndexingUtils.h:20: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead.

It doesn't affect the training, but I would like to update the code so that this warning disappears.  Any suggestions?

Thank you all in advance.

答:
The solution is mentioned in the issues. The exact link is: https://github.com/eriklindernoren/PyTorch-YOLOv3/issues/283

Replace in utils:269

ByteTensor = torch.cuda.ByteTensor if pred_boxes.is_cuda else torch.ByteTensor

With:
BoolTensor = torch.cuda.BoolTensor if pred_boxes.is_cuda else torch.BoolTensor

And it usage in lines 278, 279
obj_mask = BoolTensor(nB, nA, nG, nG).fill_(0)
noobj_mask = BoolTensor(nB, nA, nG, nG).fill_(1)


问:
What should be the values of GOPATH and GOROOT?
I'm trying to install doozer like this:

```<code>$ goinstall github.com/ha/doozer
</code>```

I get these errors.

```<code>goinstall: os: go/build: package could not be found locally
goinstall: fmt: go/build: package could not be found locally
goinstall: io: go/build: package could not be found locally
goinstall: reflect: go/build: package could not be found locally
goinstall: math: go/build: package could not be found locally
goinstall: rand: go/build: package could not be found locally
goinstall: url: go/build: package could not be found locally
goinstall: net: go/build: package could not be found locally
goinstall: sync: go/build: package could not be found locally
goinstall: runtime: go/build: package could not be found locally
goinstall: strings: go/build: package could not be found locally
goinstall: sort: go/build: package could not be found locally
goinstall: strconv: go/build: package could not be found locally
goinstall: bytes: go/build: package could not be found locally
goinstall: log: go/build: package could not be found locally
goinstall: encoding/binary: go/build: package could not be found locally
</code>```

答:
As of 2020 and Go version 1.13+, in Windows the best way for updating GOPATH is just typing in command prompt:</p>

```<code>setx GOPATH C:\mynewgopath
</code>```

Body:
I'm trying to install doozer like this:

$ goinstall github.com/ha/doozer

I get these errors.

goinstall: os: go/build: package could not be found locally
goinstall: fmt: go/build: package could not be found locally
goinstall: io: go/build: package could not be found locally
goinstall: reflect: go/build: package could not be found locally
goinstall: math: go/build: package could not be found locally
goinstall: rand: go/build: package could not be found locally
goinstall: url: go/build: package could not be found locally
goinstall: net: go/build: package could not be found locally
goinstall: sync: go/build: package could not be found locally
goinstall: runtime: go/build: package could not be found locally
goinstall: strings: go/build: package could not be found locally
goinstall: sort: go/build: package could not be found locally
goinstall: strconv: go/build: package could not be found locally
goinstall: bytes: go/build: package could not be found locally
goinstall: log: go/build: package could not be found locally
goinstall: encoding/binary: go/build: package could not be found locally

Body:
As of 2020 and Go version 1.13+, in Windows the best way for updating GOPATH is just typing in command prompt:

setx GOPATH C:\mynewgopath


问:
"port 4200 already in use" error, inspite it is not being used
I am starting up with a angular project. While running ng-serve port 4200 already in use error comes up. I have tried all the trivial solutions. netstat does not show up any process running on 127.0.0.1:4200. Also tried with --port command to change the default port, unfortunately dint work for any entered ports (tried it thrice with different port numbers). Have visited almost all the answers in here, none helped. Thanks in advance.

答:
in that case use angular command-

```<code>ng serve --port 4201
</code>```

you've to change the port number.

Body:
in that case use angular command-

ng serve --port 4201

you've to change the port number.


问:
How can I connect to Android with ADB over TCP?
I am attempting to debug an application on a Motorola Droid, but I am having some difficulty connecting to the device via USB. My development server is a Windows 7 64-bit VM running in Hyper-V, and so I cannot connect directly via USB in the guest or from the host.

I installed a couple of different USB-over-TCP solutions, but the connection appears to have issues since the ADB monitor reports "devicemonitor failed to start monitoring" repeatedly. Is there a way to connect directly from the client on the development machine to the daemon on the device using the network instead of the USB connection or possibly another viable options?

答:
These are the steps I followed and it worked for me,

adb shell ifconfig (get the ip address of the device from here)

adb tcpip 7777 (connect adb to some port)

adb connect "ipaddress":7777


问:
fadeOut not working in IE7/IE8
I'm not quite sure why this bit of jQuery isn't working in IE7 & IE8.  Does anyone have any ideas what could be causing this?</p>

答:
Well for one thing since you are using jQuery do this without the inline js:

```<code>$('input[type=checkbox]').click(function(){
    var checkbox = this;
    if (checkbox.checked) {
        $("#message1").stop(true, true).show().fadeOut(10000);
        $("#message2").hide();
    }
    else {
        $("#message1").stop(true, true).hide();
        $("#message2").stop(true, true).show().fadeOut(10000);
    }
});
</code>```

Just doing this might fix the IE problem

Fiddle: http://jsfiddle.net/maniator/xMSwQ/5/

Title: fadeOut not working in IE7/IE8

Body:
Well for one thing since you are using jQuery do this without the inline js:

$('input[type=checkbox]').click(function(){
    var checkbox = this;
    if (checkbox.checked) {
        $("#message1").stop(true, true).show().fadeOut(10000);
        $("#message2").hide();
    }
    else {
        $("#message1").stop(true, true).hide();
        $("#message2").stop(true, true).show().fadeOut(10000);
    }
});

Just doing this might fix the IE problem

Fiddle: http://jsfiddle.net/maniator/xMSwQ/5/


问:
how can we add default parameters in model scope in rails?
I have the following scope in my model.

```<code>class Referral < ActiveRecord::Base
  scope :date_range, -> (start_date,end_date) { where("created_at <= ? AND created_at >= ?", start_date, end_date) }
end

calling like this :- Referral.date_range(Date.today,Date.today)
</code>```

How can we change this scope so that it takes the current date as start date and end date,in case if we don't pass any parameters while calling.

答:
Ruby actually has ranges. Use them.

```<code>class Referral < ActiveRecord::Base
  def self.created_between(range = Date.today.beginning_of_day..Date.today.end_of_day)
    where(created_at: range)
  end
end
</code>```

The thing that everybody forgets about scope is that its just syntactic sugar for creating class methods in a one-liner. Any arguments you add to the block/lambda will be arguments of the method.

But if your method takes arguments it probably does not fit in a decent length one-liner. Thus your should not be using scope in the first place. While you can write multi-line methods with scope it a completely pointless level of meta-programming since it takes the exact same number of lines and is less readable and cannot be detected by tools that cannot find dynamically generated methods.

Body:
I have the following scope in my model.

class Referral < ActiveRecord::Base
  scope :date_range, -> (start_date,end_date) { where("created_at <= ? AND created_at >= ?", start_date, end_date) }
end

calling like this :- Referral.date_range(Date.today,Date.today)

How can we change this scope so that it takes the current date as start date and end date,in case if we don't pass any parameters while calling.

Body:
Ruby actually has ranges. Use them.

class Referral < ActiveRecord::Base
  def self.created_between(range = Date.today.beginning_of_day..Date.today.end_of_day)
    where(created_at: range)
  end
end

The thing that everybody forgets about scope is that its just syntactic sugar for creating class methods in a one-liner. Any arguments you add to the block/lambda will be arguments of the method.

But if your method takes arguments it probably does not fit in a decent length one-liner. Thus your should not be using scope in the first place. While you can write multi-line methods with scope it a completely pointless level of meta-programming since it takes the exact same number of lines and is less readable and cannot be detected by tools that cannot find dynamically generated methods.


问:
Where to set viewport size in wordpress theme genesis
I have the following meta tag in functions.php file under wordpress.

```<code><meta name="viewport" content="width=device-width">
</code>```

and custom CSS as:

```<code>.x-navbar .desktop .x-nav>li>a>span {
padding-left:15px;
padding-right:15px;
}

.x-comments-area{
display:none;
}

@media (max-width: 1024px) and (min-width:801px){
.x-navbar {
  font-size: 12px;
}

.x-navbar .desktop .x-nav>li>a>span {
padding-left:5px;
padding-right:5px;
}
}
</code>```

I need to change viewport size as google insight says:

The page content is 389 CSS pixels wide, but the viewport is only 375
  CSS pixels wide.

I would like to know where I put the changes in genesis theme as I have got the wordpress website for optimization.

答:
function et_add_viewport_meta_2(){
 echo '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">';
}
add_action( 'wp_head', 'et_add_viewport_meta_2' );```

Body:
I have the following meta tag in functions.php file under wordpress.

<meta name="viewport" content="width=device-width">

and custom CSS as:

.x-navbar .desktop .x-nav>li>a>span {
padding-left:15px;
padding-right:15px;
}

.x-comments-area{
display:none;
}

@media (max-width: 1024px) and (min-width:801px){
.x-navbar {
  font-size: 12px;
}

.x-navbar .desktop .x-nav>li>a>span {
padding-left:5px;
padding-right:5px;
}
}

I need to change viewport size as google insight says:

The page content is 389 CSS pixels wide, but the viewport is only 375
  CSS pixels wide.

I would like to know where I put the changes in genesis theme as I have got the wordpress website for optimization.


问:
Does SFSpeechRecognizer have a limit if supportsOnDeviceRecognition is true and offline mode is available?
According to the Apple documents, there is a limit to the number of requests that SFSpeechRecognizer can send.

Be prepared to handle failures caused by speech recognition limits. Because speech recognition is a network-based service, limits are enforced so that the service can remain freely available to all apps. Individual devices may be limited in the number of recognitions that can be performed per day, and each app may be throttled globally based on the number of requests it makes per day. If a recognition request fails quickly (within a second or two of starting), check to see if the recognition service became unavailable. If it is, you may want to ask users to try again later.
  https://developer.apple.com/documentation/speech/sfspeechrecognizer

Another document says that a device can send 1000 requests per hour.

The current rate limit for the number of SFSpeechRecognitionRequest
  calls a device can make is 1000 requests per hour. Please note this
  limit is on the number of requests that a device can make and is not
  tied to the application making it. This is regardless of the length of
  audio associated with the request. For a given
  SFSpeechRecognitionRequest, you are allowed up to one minute of audio
  per request.

Now I am creating a SFSpeechRecognizer as shown below and check the supportsOnDeviceRecognition property that indicates whether the speech recognizer can operate without network access. It returns true on my iOS 13.2.3 installed device.

```<code>let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
print(speechRecognizer.supportsOnDeviceRecognition) //true
</code>```

I have tried to run my application offline and it works fine without an internet connection. But there is no information if there is still a request limit or not if supportsOnDeviceRecognition is true. In this situation, SFSpeechRecognizer probably won't connect to the Apple servers even if the device is connected to the internet because it would be unnecessary. Is the rate limit only when supportsOnDeviceRecognition is true?

答:
According to this presentation at the WWDC2019, On-device has no limits.

https://developer.apple.com/videos/play/wwdc2019/256/

Body:
According to the Apple documents, there is a limit to the number of requests that SFSpeechRecognizer can send.

Be prepared to handle failures caused by speech recognition limits. Because speech recognition is a network-based service, limits are enforced so that the service can remain freely available to all apps. Individual devices may be limited in the number of recognitions that can be performed per day, and each app may be throttled globally based on the number of requests it makes per day. If a recognition request fails quickly (within a second or two of starting), check to see if the recognition service became unavailable. If it is, you may want to ask users to try again later.
  https://developer.apple.com/documentation/speech/sfspeechrecognizer

Another document says that a device can send 1000 requests per hour.

The current rate limit for the number of SFSpeechRecognitionRequest
  calls a device can make is 1000 requests per hour. Please note this
  limit is on the number of requests that a device can make and is not
  tied to the application making it. This is regardless of the length of
  audio associated with the request. For a given
  SFSpeechRecognitionRequest, you are allowed up to one minute of audio
  per request.

Now I am creating a SFSpeechRecognizer as shown below and check the supportsOnDeviceRecognition property that indicates whether the speech recognizer can operate without network access. It returns true on my iOS 13.2.3 installed device.

let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
print(speechRecognizer.supportsOnDeviceRecognition) //true

I have tried to run my application offline and it works fine without an internet connection. But there is no information if there is still a request limit or not if supportsOnDeviceRecognition is true. In this situation, SFSpeechRecognizer probably won't connect to the Apple servers even if the device is connected to the internet because it would be unnecessary. Is the rate limit only when supportsOnDeviceRecognition is true?


问:
Sitecore 500 Error Logging / Alerts

Problem

Currently, I'm looking to serve a custom 500 error page as well as log and alert a web master about the condition that was hit (What URL, stack trace, timestamp, etc.).

I tried defined custom http errors under system configuration, but the error pages were not hit.
I am able to handle 404s and their related errors (layoutnotfound).

Question

Should I intercept the context in global.asax to handle the 500 errors and return a custom page? Is there another way with Sitecore to achieve what I'm looking for?

Mainly, I'm looking for best practice of logging / alerts for 500 errors with Sitecore

答:
I tried defined custom http errors
  under system configuration, but the
  error pages were not hit. I am able to
  handle 404s and their related errors
  (layoutnotfound).

On that particular point...Be aware that custom errors behave differently when accessed locally. Also, by default you need to use physical files (not sitecore pages) for these pages. You need be aware of IIS behaviour when returning status codes over 200 and how it is dependant on the  configuration within web.config and (if running in integrated mode) the  section. In particular, see the flow chart half way down the first link below.

http://learn.iis.net/page.aspx/267/how-to-use-http-detailed-errors-in-iis-70/
http://www.iis.net/ConfigReference/system.webServer/httpErrors
http://msdn.microsoft.com/en-us/library/ms689487(v=VS.90).aspx

You might also want to change the RequestErrors.UseServerSideRedirect setting to "true" to provide better http responses without redirects.

Title: Sitecore 500 Error Logging / Alerts


问:
Copy values of named range referenced in another cell
I want to create a loop that copies one range to another, dependent on the value in a list. The list contains the names of all the ranges that I want to copy.

So in this example, PolicyOutput is a named range from DD15:DD77. I want it to update with values from another range, policy1, then loop to copy new values again from a different cell range, policy2.

The list of policies is in a range of cells called PolicyChoice

Each row of PolicyChoice contains a reference to a group of cells. It will be values: policy1, policy2, policy3 etc.

The values of the cells refer to named ranges. For example policy1 is A15:A77, and policy2 is B15:B77

I want A15:A77 to copy to DD15:DD77, then B15:B77 to copy to DD15:DD77, but in a way that can be updated and rerun as the list of "PolicyChoice" is changed by the user.

I tried the code below, but it just copies "policy1" over again into each cell in the range PolicyOutput, instead of the values in the range policy1

```<code>policyChoiceCount = (Sheets("RunModel").Range("policyChoice").Count) - Application.WorksheetFunction.CountIf(Sheets("RunModel").Range("policyChoice"), "")

For h = 1 To PolicyChoiceCount
             Sheets(PolicySheetName).Range("PolicyOutput").Value = WorksheetFunction.Index(Sheets("RunModel").Range("policyChoice"), h)

 Next h
</code>```

Thanks!

答:
Add Range(WorksheetFunction ..).value like this

```<code>Sheets(policySheetName).Range("PolicyOutput").Value = _
Range(WorksheetFunction.Index(Sheets("RunModel").Range("policyChoice"), h)).Value
</code>```

or in simple steps

Sub mycopy()

```<code>    Dim wb As Workbook, wsSource As Worksheet, wsTarget As Worksheet
    Dim rngSource As Range, rngTarget As Range, cell As Range

    Set wb = ThisWorkbook
    Set wsSource = wb.Sheets("RunModel")
    Set wsTarget = wb.Sheets("PolicySheetName")
    Set rngTarget = wsTarget.Range("PolicyOutput")

    For Each cell In wsSource.Range("PolicyChoice")
        If Len(cell) > 0 Then
            On Error Resume Next
            If IsEmpty(Range(cell)) Then
                MsgBox "No named range " & cell, vbCritical, "ERROR"
                Exit Sub
            End If
            On Error GoTo 0

            rngTarget.Value = Range(cell).Value
        End If
    Next

End Sub
</code>```

Body:
I want to create a loop that copies one range to another, dependent on the value in a list. The list contains the names of all the ranges that I want to copy.

So in this example, PolicyOutput is a named range from DD15:DD77. I want it to update with values from another range, policy1, then loop to copy new values again from a different cell range, policy2.

The list of policies is in a range of cells called PolicyChoice

Each row of PolicyChoice contains a reference to a group of cells. It will be values: policy1, policy2, policy3 etc.

The values of the cells refer to named ranges. For example policy1 is A15:A77, and policy2 is B15:B77

I want A15:A77 to copy to DD15:DD77, then B15:B77 to copy to DD15:DD77, but in a way that can be updated and rerun as the list of "PolicyChoice" is changed by the user.

I tried the code below, but it just copies "policy1" over again into each cell in the range PolicyOutput, instead of the values in the range policy1

policyChoiceCount = (Sheets("RunModel").Range("policyChoice").Count) - Application.WorksheetFunction.CountIf(Sheets("RunModel").Range("policyChoice"), "")

For h = 1 To PolicyChoiceCount
             Sheets(PolicySheetName).Range("PolicyOutput").Value = WorksheetFunction.Index(Sheets("RunModel").Range("policyChoice"), h)

 Next h

Thanks!

Body:
Add Range(WorksheetFunction ..).value like this

Sheets(policySheetName).Range("PolicyOutput").Value = _
Range(WorksheetFunction.Index(Sheets("RunModel").Range("policyChoice"), h)).Value

or in simple steps

Sub mycopy()

    Dim wb As Workbook, wsSource As Worksheet, wsTarget As Worksheet
    Dim rngSource As Range, rngTarget As Range, cell As Range

    Set wb = ThisWorkbook
    Set wsSource = wb.Sheets("RunModel")
    Set wsTarget = wb.Sheets("PolicySheetName")
    Set rngTarget = wsTarget.Range("PolicyOutput")

    For Each cell In wsSource.Range("PolicyChoice")
        If Len(cell) > 0 Then
            On Error Resume Next
            If IsEmpty(Range(cell)) Then
                MsgBox "No named range " & cell, vbCritical, "ERROR"
                Exit Sub
            End If
            On Error GoTo 0

            rngTarget.Value = Range(cell).Value
        End If
    Next

End Sub


问:
NPE error when running TestNg test groups using eclipse
I am trying to run a Test group in TestNG by right clicking on TestNG.xml as a test suite and get below Error.

```<code>java.lang.NullPointerException
at execution_Engine.TestCase1_Login.Login(TestCase1_Login.java:54)
</code>```

Note: When I run the Test on its own(not as a Test suite) it runs fine.

Can anyone be kind enough to point out what the problem is? and solution to this problem.

TestNG.xml

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Smoke tests">
<test name="regressions Test Suite">
    <groups>
        <run>
            <include name="Regression"/>
        </run>
    </groups>
    <classes>
        <class name="execution_Engine.TestCase1_Login"/>
        <class name="execution_Engine.TestCase2_InvalidLogin"/>
    </classes>
            <packages>
        <package name="execution_Engine" />
        </packages>
</test>
</suite>

@SuppressWarnings("unused")
public class TestCase1_Login  {

public static WebDriver driver = null;

 @BeforeMethod
  public static void LaunchIEandNavigate() {

      /*** Launch IE **/
    System.setProperty "webdriver.ie.driver", "C:\\IE\\IEDriverServer.exe");
      driver = new InternetExplorerDriver();

      /*** implicit Wait **/
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      /*** Navigate to URL **/
      driver.get("http://google.com");

@Test(enabled = true, groups = "Regression")
public void Login() {

       /*** Login Action  **/
       driver.findElement(By.id("UserId")).sendKeys("DummyUser"); Line 54
       driver.findElement(By.id("Password")).sendKeys("password");
       driver.findElement(By.id("Submit-button")).click();

   System.out.println("Testcase1 - ValidLogin executed sucessfully.");

}

@AfterMethod
public void CloseIEandQuit() {
//driver.switchTo().defaultContent();
  /** Close and quit browser*/
  driver.close();
  driver.quit();

}
</code>```

答:
To add to above answer, add (alwaysRun=true) to all the annotations you are using. I had annotation @BeforeClass along with @BeforeMethod. So add (alwaysRun=true) to all the annotations that form part of your test. </p>

```<code>  @Parameters("browser")
  @BeforeClass(alwaysRun=true)
  public void setupDriver(String browser)
  {
      application=new SSC_NewUserRegisteration(browser);

  }

  @BeforeMethod(alwaysRun=true)
  public void launchApplication()
  {
      application.app_launchApplication();
  }

  @Test(priority=1, groups = {"Valid Data"})
  public void submitWithAadharDetails()
  {
      application.app_setTestData(1);

      application.app_fillNewUserRegisterationDetails();

      application.app_submitData();
  }
</code>```

Body:
I am trying to run a Test group in TestNG by right clicking on TestNG.xml as a test suite and get below Error.

java.lang.NullPointerException
at execution_Engine.TestCase1_Login.Login(TestCase1_Login.java:54)

Note: When I run the Test on its own(not as a Test suite) it runs fine.

Can anyone be kind enough to point out what the problem is? and solution to this problem.

TestNG.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Smoke tests">
<test name="regressions Test Suite">
    <groups>
        <run>
            <include name="Regression"/>
        </run>
    </groups>
    <classes>
        <class name="execution_Engine.TestCase1_Login"/>
        <class name="execution_Engine.TestCase2_InvalidLogin"/>
    </classes>
            <packages>
        <package name="execution_Engine" />
        </packages>
</test>
</suite>

@SuppressWarnings("unused")
public class TestCase1_Login  {

public static WebDriver driver = null;

 @BeforeMethod
  public static void LaunchIEandNavigate() {

      /*** Launch IE **/
    System.setProperty "webdriver.ie.driver", "C:\\IE\\IEDriverServer.exe");
      driver = new InternetExplorerDriver();

      /*** implicit Wait **/
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      /*** Navigate to URL **/
      driver.get("http://google.com");

@Test(enabled = true, groups = "Regression")
public void Login() {

       /*** Login Action  **/
       driver.findElement(By.id("UserId")).sendKeys("DummyUser"); Line 54
       driver.findElement(By.id("Password")).sendKeys("password");
       driver.findElement(By.id("Submit-button")).click();

   System.out.println("Testcase1 - ValidLogin executed sucessfully.");

}

@AfterMethod
public void CloseIEandQuit() {
//driver.switchTo().defaultContent();
  /** Close and quit browser*/
  driver.close();
  driver.quit();

}

Body:
To add to above answer, add (alwaysRun=true) to all the annotations you are using. I had annotation @BeforeClass along with @BeforeMethod. So add (alwaysRun=true) to all the annotations that form part of your test.

  @Parameters("browser")
  @BeforeClass(alwaysRun=true)
  public void setupDriver(String browser)
  {
      application=new SSC_NewUserRegisteration(browser);

  }

  @BeforeMethod(alwaysRun=true)
  public void launchApplication()
  {
      application.app_launchApplication();
  }

  @Test(priority=1, groups = {"Valid Data"})
  public void submitWithAadharDetails()
  {
      application.app_setTestData(1);

      application.app_fillNewUserRegisterationDetails();

      application.app_submitData();
  }


问:
enter command -$ npm install -g hexo-cli
I have a question ah..   It began like this~

when I press the Command - $ 'npm install -g hexo-cli',The error follows.

```<code>npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/usr/local/lib

npm ERR! Error: EACCES: permission denied, access        '/usr/local/lib/node_modules'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, access    '/usr/local/lib/node_modules']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
</code>```

答:
Try with

$ sudo npm install -g hexo-cli
```

Here and here you have the exact information about that error.

Body:
I have a question ah..   It began like this~

when I press the Command - $ 'npm install -g hexo-cli',The error follows.

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/usr/local/lib

npm ERR! Error: EACCES: permission denied, access        '/usr/local/lib/node_modules'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, access    '/usr/local/lib/node_modules']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:

Body:
Try with

$ sudo npm install -g hexo-cli

Here and here you have the exact information about that error.


问:
Detect when TextBox autocomplete list is showing
I have TextBox controls and associated Timers that restarts on each KeyDown or MouseClick event, and performs queries based on typed text after 3 seconds without those events. So far so good.

But some of my TextBoxes also have AutoComplete lists which user can browse in, but even if they do using keyboard arrow keys, timer is not halted and an unexpected query is fired in the middle of user browsing the list.

Question: is there a way of detecting when autocomplete list is showing, so that I can suspend timer or ignoring its tick?

Thank you very much!

答:
Reza Aghaei's approach translated into C#:

```<code>public delegate bool EnumThreadDelegate(IntPtr hwnd, IntPtr lParam);

[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumThreadWindows(uint dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);
</code>```

```<code>bool isAutoCompleteListOpen = false;
EnumThreadDelegate callback = (IntPtr hwnd, IntPtr lParam) =>
{
    var cn = new StringBuilder("", 256);
    GetClassName(hwnd, cn, 256);
    if (cn.ToString() == "Auto-Suggest Dropdown" && IsWindowVisible(hwnd)) {
        isAutoCompleteListOpen = true;
        return false;
    }
    return true;
};

EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero);
return isAutoCompleteListOpen;
</code>```

For better performance, here we're returning false in the callback upon finding an open list, which stops the enumeration.

Body:
Reza Aghaei's approach translated into C#:

public delegate bool EnumThreadDelegate(IntPtr hwnd, IntPtr lParam);

[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumThreadWindows(uint dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);

bool isAutoCompleteListOpen = false;
EnumThreadDelegate callback = (IntPtr hwnd, IntPtr lParam) =>
{
    var cn = new StringBuilder("", 256);
    GetClassName(hwnd, cn, 256);
    if (cn.ToString() == "Auto-Suggest Dropdown" && IsWindowVisible(hwnd)) {
        isAutoCompleteListOpen = true;
        return false;
    }
    return true;
};

EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero);
return isAutoCompleteListOpen;

For better performance, here we're returning false in the callback upon finding an open list, which stops the enumeration.


问:
Generic interface problem
So here is my problem:

I have the interface:

```<code>public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}
</code>```

And wanted to implement ISubstratum interface in this way:

```<code>public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}
</code>```

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!

答:
Because your constraint on the T generic type parameter of your ISubstratum interface is not specific enough. It should be:

```<code>where T : struct, IComparable<ICell<Feature>>
</code>```

Title: Generic interface problem

Body:
So here is my problem:

I have the interface:

public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}

And wanted to implement ISubstratum interface in this way:

public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!

Body:
Because your constraint on the T generic type parameter of your ISubstratum interface is not specific enough. It should be:

where T : struct, IComparable<ICell<Feature>>


问:
Tree implementation in C++: Cannot convert Node to int* Ask Question
I'm currently working on my homework. Below is the program for construction of binary tree which I wrote. I'm getting the error that, "cannot convert 'node' to 'int*' in assignment". Can you please help me out here?**

```<code>#include<iostream>
#include<conio.h>

struct node
{
    char data;
    int *left,*right;
};

int main()
{
    node *T; //ROOT of tree
    node *p,*q; //address of first node in T
    T=new node;
    T->left=NULL;
    T->right=NULL;
    T->data='A';

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='B';
    T->left=&p;

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='C';
    T->right=&p;

    q=new node;
    q->left=NULL;
    q->right=NULL;
    q->data='D';
    p->left=&q;

    return 0;
}```
```

答:
Change your structure definition to

```<code>struct node
{
    char data;
    node *left,*right;  // <- node * here
};
</code>```

Tree node has a recursive definition.

Body:
I'm currently working on my homework. Below is the program for construction of binary tree which I wrote. I'm getting the error that, "cannot convert 'node' to 'int*' in assignment". Can you please help me out here?**

#include<iostream>
#include<conio.h>

struct node
{
    char data;
    int *left,*right;
};

int main()
{
    node *T; //ROOT of tree
    node *p,*q; //address of first node in T
    T=new node;
    T->left=NULL;
    T->right=NULL;
    T->data='A';

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='B';
    T->left=&p;

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='C';
    T->right=&p;

    q=new node;
    q->left=NULL;
    q->right=NULL;
    q->data='D';
    p->left=&q;

    return 0;
}```

Body:
Change your structure definition to

struct node
{
    char data;
    node *left,*right;  // <- node * here
};

Tree node has a recursive definition.


问:
Get property with lowest value from ArrayList of objects
I have ArrayList containing objects inside of it, every object in the ArrayList has a property and I wan't to see which of these objects has the lowest value on that property. Here's my code + Object structure</p>

```<code>class ServerInfo{

   public int playerCount = 0; //This is different per every object in the array list
}

List<ServerInfo> onlineServers = new ArrayList<ServerInfo> //From this array i want object with lowest 'playerCount' property value.
</code>```

答:
You can use Java 8 stream like below :</p>

```<code>ServerInfo serverInfoWithMinPlayerCount = onlineServers.stream().min(Comparator.comparing(ServerInfo::getPlayerCount)).orElseThrow(NoSuchElementException::new);
</code>```

Body:
I have ArrayList containing objects inside of it, every object in the ArrayList has a property and I wan't to see which of these objects has the lowest value on that property. Here's my code + Object structure

class ServerInfo{

   public int playerCount = 0; //This is different per every object in the array list
}

List<ServerInfo> onlineServers = new ArrayList<ServerInfo> //From this array i want object with lowest 'playerCount' property value.

Body:
You can use Java 8 stream like below :

ServerInfo serverInfoWithMinPlayerCount = onlineServers.stream().min(Comparator.comparing(ServerInfo::getPlayerCount)).orElseThrow(NoSuchElementException::new);


问:
I am having a trouble in installing angular
I am getting this error while installing angular . I think may be its a problem of path of npm , but how to solve it .
I did with root permission also then also got error of certificated untrusted. Error below -</p>

```<code> root@Aishwarya:/# npm uninstall -g angular-cli
    npm WARN uninstall not installed in /usr/local/lib/node_modules: "angular-cli"
    root@Aishwarya:/# npm install -g angular-cli
    npm http GET https://registry.npmjs.org/angular-cli
    npm http GET https://registry.npmjs.org/angular-cli
    npm http GET https://registry.npmjs.org/angular-cli
    npm ERR! Error: CERT_UNTRUSTED
    npm ERR!     at SecurePair.<anonymous> (tls.js:1370:32)
    npm ERR!     at SecurePair.EventEmitter.emit (events.js:92:17)
    npm ERR!     at SecurePair.maybeInitFinished (tls.js:982:10)
    npm ERR!     at CleartextStream.read [as _read] (tls.js:469:13)
    npm ERR!     at CleartextStream.Readable.read (_stream_readable.js:320:10)
    npm ERR!     at EncryptedStream.write [as _write] (tls.js:366:25)
    npm ERR!     at doWrite (_stream_writable.js:223:10)
    npm ERR!     at writeOrBuffer (_stream_writable.js:213:5)
    npm ERR!     at EncryptedStream.Writable.write (_stream_writable.js:180:11)
    npm ERR!     at write (_stream_readable.js:583:24)
    npm ERR! If you need help, you may report this log at:
    npm ERR!     <http://github.com/isaacs/npm/issues>
    npm ERR! or email it to:
    npm ERR!     <npm-@googlegroups.com>

    npm ERR! System Linux 4.2.0-35-generic
    npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "angular-cli"
    npm ERR! cwd /
    npm ERR! node -v v0.10.25
    npm ERR! npm -v 1.3.10
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR!     /npm-debug.log
    npm ERR! not ok code 0
    root@Aishwarya:/#
</code>```

答:
I think it's a network issue if you are using Linux then;

```<code>sudo service network-manager restart
</code>```

If windows then restarting your PC should solve this.

It could also be git version issue or node version issue if thats the issue then:

Uninstall Git, Node.js, npm

Install Git

Install Node.js witn npm

Install angular

Or simply the following could also solve the issue:

```<code>npm uninstall -g angular-cli
npm cache clean
npm install -g rxjs
npm install -g @angular/cli
</code>```

Body:
I am getting this error while installing angular . I think may be its a problem of path of npm , but how to solve it .
I did with root permission also then also got error of certificated untrusted. Error below -

 root@Aishwarya:/# npm uninstall -g angular-cli
    npm WARN uninstall not installed in /usr/local/lib/node_modules: "angular-cli"
    root@Aishwarya:/# npm install -g angular-cli
    npm http GET https://registry.npmjs.org/angular-cli
    npm http GET https://registry.npmjs.org/angular-cli
    npm http GET https://registry.npmjs.org/angular-cli
    npm ERR! Error: CERT_UNTRUSTED
    npm ERR!     at SecurePair.<anonymous> (tls.js:1370:32)
    npm ERR!     at SecurePair.EventEmitter.emit (events.js:92:17)
    npm ERR!     at SecurePair.maybeInitFinished (tls.js:982:10)
    npm ERR!     at CleartextStream.read [as _read] (tls.js:469:13)
    npm ERR!     at CleartextStream.Readable.read (_stream_readable.js:320:10)
    npm ERR!     at EncryptedStream.write [as _write] (tls.js:366:25)
    npm ERR!     at doWrite (_stream_writable.js:223:10)
    npm ERR!     at writeOrBuffer (_stream_writable.js:213:5)
    npm ERR!     at EncryptedStream.Writable.write (_stream_writable.js:180:11)
    npm ERR!     at write (_stream_readable.js:583:24)
    npm ERR! If you need help, you may report this log at:
    npm ERR!     <http://github.com/isaacs/npm/issues>
    npm ERR! or email it to:
    npm ERR!     <npm-@googlegroups.com>

    npm ERR! System Linux 4.2.0-35-generic
    npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "angular-cli"
    npm ERR! cwd /
    npm ERR! node -v v0.10.25
    npm ERR! npm -v 1.3.10
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR!     /npm-debug.log
    npm ERR! not ok code 0
    root@Aishwarya:/#

Body:
I think it's a network issue if you are using Linux then;

sudo service network-manager restart

If windows then restarting your PC should solve this.

It could also be git version issue or node version issue if thats the issue then:

Uninstall Git, Node.js, npm

Install Git

Install Node.js witn npm

Install angular

Or simply the following could also solve the issue:

npm uninstall -g angular-cli
npm cache clean
npm install -g rxjs
npm install -g @angular/cli


问:
Build One Project from GIT Repo (Jenkins/GIT)
I am trying to check out just one maven project from  a GIT repo (Total of 49 modules) in Jenkins and do a build. The only reason is that they all need to be built a little bit differently in order to be deployed on to Tomcat. I probably might have been able to do it in SVN because I have dealt with it for a decade. But I am a spring chicken when it comes to GIT, I just don't have much idea how to get this to work. The current GIT folder structure is like:

```<code>    Maven Parent Project
        Child Project A
        Child Porject B
        Child Porject C
        Child Porject D
        .
        .
        .
        .
        .
        and so on...
</code>```

Now lets say I want to create a job that just builds ChildProjectD, how do I go about it? Is it even possible? I did install the plugin GIT Parameter, thinking it would get me somewhere. But just don't know what to put in the fields.

Any help with this would be helpful. Thanks in advance.

答:
These following guidelines may help you with initializing a Jenkins freestyle job for building a subproject rather than building all projects included in a git repo.

Install git-plugin for Jenkins

Create a freestyle job and add your git hub repository's link on SCM repository field

New Item -->

Name the item and OK -->

Select Git in SCM -->

Add repository URL -->

Add invoke top-level maven targets as Build steps -->

In Goals install -pl ChildProjectD

(optional) Add post-build and other configurations

It will build the Child project as you want instead of full project.
You can refer Jenkins GitHub Java Application Project Build Configuration Maven to get more help. Check also mvn install -pl --help for more info.

Feel free to ask questions.

Body:
I am trying to check out just one maven project from  a GIT repo (Total of 49 modules) in Jenkins and do a build. The only reason is that they all need to be built a little bit differently in order to be deployed on to Tomcat. I probably might have been able to do it in SVN because I have dealt with it for a decade. But I am a spring chicken when it comes to GIT, I just don't have much idea how to get this to work. The current GIT folder structure is like:

    Maven Parent Project
        Child Project A
        Child Porject B
        Child Porject C
        Child Porject D
        .
        .
        .
        .
        .
        and so on...

Now lets say I want to create a job that just builds ChildProjectD, how do I go about it? Is it even possible? I did install the plugin GIT Parameter, thinking it would get me somewhere. But just don't know what to put in the fields.

Any help with this would be helpful. Thanks in advance.