问:
How to export c file/function to FMU using fmusdk
This is my function. I am trying to export this code to fmu. I am using fmusdk.

For each cycle(time step),

my input should be changed to the value given during simulation.

myexecute() should be called.

the values of input and pout should be stored during simulation, so that we can plot the values after the simulation.

I tried the examples(BouncingBall and values) given in fmusdk. I have created corresponding fmus and imported them in Amesim. They are working fine.  But i am unable to figure out how to do the same for my C file/function

```<code>/*
 * Execution function
 */
void  myexecute(double *input, double *pout)
{
  (*pout) = 2 * (*input);
}
</code>```

I examined the bouncingBall.c and values.c, they have only four methods

```<code>setStartValues(ModelInstance *comp)
calculateValues(ModelInstance *comp)
getReal(ModelInstance *comp, fmi2ValueReference vr)
void eventUpdate(ModelInstance *comp, fmi2EventInfo *eventInfo, int isTimeEvent, int isNewEventIteration)
</code>```

Can someone help me in accomplishing this fmi export? In short i am looking for the contents for the above 4 functions. Explaination for the above 4 methods will also be sufficient. I can create the contents for the functions.

答:
Consider the C file given below similar to the files you mentioned  bouncingBall.c or valus.c . Since you have referred the function myexecute from another c file, replace yourCFile.c and/or yourHFile.h with the correct files.
Also your modelDescription.xml should be in sync with this C file. For ex) guid value should be the same in both files. Also the value reference for the scalar variables should be the same. Analyse <ScalarVariable name="pin" valueReference="0"> and #define pin_  0 . Similarly for pout. Create a folder structure similar to bouncingBall. Create a separate batch file, since we have to include additional files(yourCFile.c and/or yourHFile.h)

```<code>// define class name and unique id
#define MODEL_IDENTIFIER modelName
#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c90123}"

// define model size
#define NUMBER_OF_REALS 2
#define NUMBER_OF_INTEGERS 0
#define NUMBER_OF_BOOLEANS 0
#define NUMBER_OF_STRINGS 0
#define NUMBER_OF_STATES 1
#define NUMBER_OF_EVENT_INDICATORS 0

// include fmu header files, typedefs and macros
#include "fmuTemplate.h"
#include "yourHFile.h"
#include "yourCFile.c"

// define all model variables and their value references
// conventions used here:
// - if x is a variable, then macro x_ is its variable reference
// - the vr of a variable is its index in array  r, i, b or s
// - if k is the vr of a real state, then k+1 is the vr of its derivative
#define pin_        0
#define pout_       1

// define state vector as vector of value references
#define STATES { pout_ }

// called by fmi2Instantiate
// Set values for all variables that define a start value
// Settings used unless changed by fmi2SetX before fmi2EnterInitializationMode
void setStartValues(ModelInstance *comp) {
    r(pin_) = 2;
    r(pout_) = 4;
}

// called by fmi2GetReal, fmi2GetInteger, fmi2GetBoolean, fmi2GetString, fmi2ExitInitialization
// if setStartValues or environment set new values through fmi2SetXXX.
// Lazy set values for all variable that are computed from other variables.
void calculateValues(ModelInstance *comp) {
    if (comp->state == modelInitializationMode) {
        // set first time event
        comp->eventInfo.nextEventTimeDefined = fmi2True;
    }
}

// called by fmi2GetReal, fmi2GetContinuousStates and fmi2GetDerivatives
fmi2Real getReal(ModelInstance *comp, fmi2ValueReference vr){
    switch (vr) {
        case pin_  : return  r(pin_);
        case pout_ : return     r(pout_);
        default: return 0;
    }
}

// used to set the next time event, if any.
void eventUpdate(ModelInstance *comp, fmi2EventInfo *eventInfo, int isTimeEvent, int isNewEventIteration) {
    myexecute(&r(pin_), &r(pout_));
}

#include "fmuTemplate.c"
</code>```

Body:
This is my function. I am trying to export this code to fmu. I am using fmusdk.

For each cycle(time step),

my input should be changed to the value given during simulation.

myexecute() should be called.

the values of input and pout should be stored during simulation, so that we can plot the values after the simulation.

I tried the examples(BouncingBall and values) given in fmusdk. I have created corresponding fmus and imported them in Amesim. They are working fine.  But i am unable to figure out how to do the same for my C file/function

/*
 * Execution function
 */
void  myexecute(double *input, double *pout)
{
  (*pout) = 2 * (*input);
}

I examined the bouncingBall.c and values.c, they have only four methods

setStartValues(ModelInstance *comp)
calculateValues(ModelInstance *comp)
getReal(ModelInstance *comp, fmi2ValueReference vr)
void eventUpdate(ModelInstance *comp, fmi2EventInfo *eventInfo, int isTimeEvent, int isNewEventIteration)

Can someone help me in accomplishing this fmi export? In short i am looking for the contents for the above 4 functions. Explaination for the above 4 methods will also be sufficient. I can create the contents for the functions.

Body:
Consider the C file given below similar to the files you mentioned  bouncingBall.c or valus.c . Since you have referred the function myexecute from another c file, replace yourCFile.c and/or yourHFile.h with the correct files.
Also your modelDescription.xml should be in sync with this C file. For ex) guid value should be the same in both files. Also the value reference for the scalar variables should be the same. Analyse <ScalarVariable name="pin" valueReference="0"> and #define pin_  0 . Similarly for pout. Create a folder structure similar to bouncingBall. Create a separate batch file, since we have to include additional files(yourCFile.c and/or yourHFile.h)

// define class name and unique id
#define MODEL_IDENTIFIER modelName
#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c90123}"

// define model size
#define NUMBER_OF_REALS 2
#define NUMBER_OF_INTEGERS 0
#define NUMBER_OF_BOOLEANS 0
#define NUMBER_OF_STRINGS 0
#define NUMBER_OF_STATES 1
#define NUMBER_OF_EVENT_INDICATORS 0

// include fmu header files, typedefs and macros
#include "fmuTemplate.h"
#include "yourHFile.h"
#include "yourCFile.c"

// define all model variables and their value references
// conventions used here:
// - if x is a variable, then macro x_ is its variable reference
// - the vr of a variable is its index in array  r, i, b or s
// - if k is the vr of a real state, then k+1 is the vr of its derivative
#define pin_        0
#define pout_       1

// define state vector as vector of value references
#define STATES { pout_ }

// called by fmi2Instantiate
// Set values for all variables that define a start value
// Settings used unless changed by fmi2SetX before fmi2EnterInitializationMode
void setStartValues(ModelInstance *comp) {
    r(pin_) = 2;
    r(pout_) = 4;
}

// called by fmi2GetReal, fmi2GetInteger, fmi2GetBoolean, fmi2GetString, fmi2ExitInitialization
// if setStartValues or environment set new values through fmi2SetXXX.
// Lazy set values for all variable that are computed from other variables.
void calculateValues(ModelInstance *comp) {
    if (comp->state == modelInitializationMode) {
        // set first time event
        comp->eventInfo.nextEventTimeDefined = fmi2True;
    }
}

// called by fmi2GetReal, fmi2GetContinuousStates and fmi2GetDerivatives
fmi2Real getReal(ModelInstance *comp, fmi2ValueReference vr){
    switch (vr) {
        case pin_  : return  r(pin_);
        case pout_ : return     r(pout_);
        default: return 0;
    }
}

// used to set the next time event, if any.
void eventUpdate(ModelInstance *comp, fmi2EventInfo *eventInfo, int isTimeEvent, int isNewEventIteration) {
    myexecute(&r(pin_), &r(pout_));
}

#include "fmuTemplate.c"


来源: stackexchange

问:
& in URL mess up $_GET variables
We get URLs with & instead of & from a clients system: somedomain.com?param1=test&param2=test2

I expect to get $_GET['param1'] and $_GET['param2']. Instead I get $_GET['amp;param1'] and $_GET['amp;param2']

Do I fix it as an rewrite rule in .htaccess or in PHP?

UPDATE:

A temporary fix is to do the below, but it seems clumsy:

```<code>foreach ($_GET AS $key => $value)
{
    $param = str_replace('amp;', '', $key);
    $_GET[$param] = $value;
    unset($_GET[$key]);
}
</code>```

答:
It seems you have define "somedomain.com?param1=test&param2=test2" in HTML. So HTML is converting & into & reference.

Just try to put & instead of & like this : somedomain.com?param1=test&param2=test2

ContentLicense: CC BY-SA 3.0

Title: & in URL mess up $_GET variables

Body:
We get URLs with & instead of & from a clients system: somedomain.com?param1=test&param2=test2

I expect to get $_GET['param1'] and $_GET['param2']. Instead I get $_GET['amp;param1'] and $_GET['amp;param2']

Do I fix it as an rewrite rule in .htaccess or in PHP?

UPDATE:

A temporary fix is to do the below, but it seems clumsy:

foreach ($_GET AS $key => $value)
{
    $param = str_replace('amp;', '', $key);
    $_GET[$param] = $value;
    unset($_GET[$key]);
}

Body:
It seems you have define "somedomain.com?param1=test&param2=test2" in HTML. So HTML is converting & into &amp; reference.

Just try to put &amp; instead of & like this : somedomain.com?param1=test&amp;param2=test2


问:
Regex to Validate GSTIN Number
How to Validate GSTIN Number using regex.
eg.11ABCDE1234L1Z1

My current regex is:

```<code>^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$
</code>```

答:
Last digit is check digit. There is not much clarity on the internet on its validation - based on some real GSTIN examples - its alphanumeric - 0-9A-Z

The correct regex is therefore -

```<code>^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$
</code>```

Title: Regex to Validate GSTIN Number

Body:
How to Validate GSTIN Number using regex.
eg.11ABCDE1234L1Z1

My current regex is:

^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$

Body:
Last digit is check digit. There is not much clarity on the internet on its validation - based on some real GSTIN examples - its alphanumeric - 0-9A-Z

The correct regex is therefore -

^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$


问:
Issue with adding style to element with reactjs
I'm learning react and trying to add a class if a select element holds a value that I want to check against.

```<code>class App extends Component {
  test = 'volvo';
  render() {
    return (
      <select style={{marginTop: '30px', marginLeft: '20px'}}>
        <option value="volvo" className={test === 'volvo' ? "selected" : null}>Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    );
  }
}
</code>```

It's giving me an error where on the line here I have the ternary operator. Can someone tell me the proper way of doing this please?
Thanks!

答:
Since you are accessing a global variable inside the class, you have to use this keyword.

```<code>className={this.test === 'volvo' ? "selected" : null}
</code>```

Body:
I'm learning react and trying to add a class if a select element holds a value that I want to check against.

class App extends Component {
  test = 'volvo';
  render() {
    return (
      <select style={{marginTop: '30px', marginLeft: '20px'}}>
        <option value="volvo" className={test === 'volvo' ? "selected" : null}>Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    );
  }
}

It's giving me an error where on the line here I have the ternary operator. Can someone tell me the proper way of doing this please?
Thanks!

Body:
Since you are accessing a global variable inside the class, you have to use this keyword.

className={this.test === 'volvo' ? "selected" : null}


问:
How can I set default umask in gnome on Debian-Stretch?
I would like the permissions on files that I create with gnome apps (e.g., gedit and libreoffice) to respect the umask I set.

I have set umask to 027 in ~/.profile and /etc/login.defs. I've also followed the directions from here by adding a line to /etc/pam.d/common-session: How to set system wide umask?

Nothing is working.

I am able to get the umask setting to work if I create files in vi or nano from gnome-terminal (after setting umask 027 in .bashrc). But I would like to get this umask respected in gnome apps like gedit also.

答:
Gnome applications in question are likely launched by systemd user instance, which sets the umask to 022 regardless the umask configured using PAM.

This question has also been asked on U&L SE and has more answers there.


问:
Append a Parent to a Child Element using Jquery
I need Help for append a Child element to a parent Element. This is my code.I need to put the $input inside the $temp.

Thanks

```<code>function CaixaPin(){

  var $temp;
  $temp = $("<div></div>");
  $temp.addClass("caixa");

  var $input;
  for(var i=0; i<4; i++){
    $input = $("<div></div>");
    $input.addClass("caixaPin");
    $("body").append($input);
  }

  $("body").append($temp);

}

CaixaPin();
</code>```

答:
Body as well as $temp as well as input are DOM elements. You can append things to DOM elements, meaning  you will add some HTML inside the element you're appending to.

Since you're appending everything to body (i.e. $("body").append()), you will not succeed in getting a parent - child structure with regard to $temp and $input. Instead append $input to $temp after which you append $temp to body.

```<code>function CaixaPin(){

  var $parentElement;
  $parentElement = $("<div></div>");
  $parentElement.addClass("caixa");

  var $childElement;
  for(var i=0; i<4; i++){
    $childElement = $("<div></div>");
    $childElement.addClass("caixaPin");
    $parentElement.append($childElement);
  }

  $("body").append($parentElement);

}

CaixaPin();
</code>```

Body:
I need Help for append a Child element to a parent Element. This is my code.I need to put the $input inside the $temp.

Thanks

function CaixaPin(){

  var $temp;
  $temp = $("

");
  $temp.addClass("caixa");

  var $input;
  for(var i=0; i<4; i++){
    $input = $("

");
    $input.addClass("caixaPin");
    $("body").append($input);
  }

  $("body").append($temp);

}

CaixaPin();

Body:
Body as well as $temp as well as input are DOM elements. You can append things to DOM elements, meaning  you will add some HTML inside the element you're appending to.

Since you're appending everything to body (i.e. $("body").append()), you will not succeed in getting a parent - child structure with regard to $temp and $input. Instead append $input to $temp after which you append $temp to body.

function CaixaPin(){

  var $parentElement;
  $parentElement = $("<div></div>");
  $parentElement.addClass("caixa");

  var $childElement;
  for(var i=0; i<4; i++){
    $childElement = $("<div></div>");
    $childElement.addClass("caixaPin");
    $parentElement.append($childElement);
  }

  $("body").append($parentElement);

}

CaixaPin();


问:
How to ignore certain folders in HG?
I have my project folder - Project.  In Project I have other sub projects - SUBPROJECT1, SUBPROJECT2, SUBPROJECT3.

In each sub project I have folders, among which I have BIN and OBJ.  However, I want the latter to be ignored such that when I commit I don`t have the changes made to BIN and OBJ.  How can I do that?

答: With .hgignore.

ContentLicense: CC BY-SA 2.5

Title: How to ignore certain folders in HG?

Body: With .hgignore.


问:
list tags and tag content using github3
We tag commits on a weekly basis, and I want to issue a report to see the tag names and their content, I tried the following using python 3.x and github3

```<code>import github3
g = github3.login(token='qwerty')
r = g.repository(owner='me', repository='mine')
</code>```

so far so good, now I tried looking around for a method that would extract the tags, r has a method called tags, also, looking at the documentation I found RepoTags.
Furthermore I found this question on Stack here.
Bottom line I'm a new developer and I couldn't get it to work, here are some of my more relevant tries and errors if anyone can point me in the right direction, the end result is to get a list of tags that are available for that repo, and then iter through them to get the content of each tag.

```<code>t1 = tags(1)
t1.as_json
</code>```

that returned <bound method GitHubCore.as_json of <GitHubIterator [1, /repos/owner/repository_name/tags]>>

I tried tag = github3.repos.tag.RepoTag that returned nothing, when I try to see the methods the object 'tag' contains, none of them returned anything useful to me.

答:
I'm not entirely certain what your final goal is, but here is how one would iterate over the tags on a repository.

```<code>import github3

gh = github3.login(token='myAwesomeToken')
repository = gh.repository(owner='owner',
                           repository='myAwesomeProjectWithLotsofTags')
for tag in repository.tags():
    assert isinstance(tag, github3.repos.tag.RepoTag)
    print('{} @ {}'.format(tag.name, tag.commit))
</code>```

For future context, most (if not all) of the methods in github3.py that return lists actually return an iterator that generates the objects you're expecting. You actually have to iterate over them (as is explained in the documentation) to retrieve the items. This allows users to conserve API requests instead of trying to list everything or requiring the user to handle paging.

Title: list tags and tag content using github3

Body:
We tag commits on a weekly basis, and I want to issue a report to see the tag names and their content, I tried the following using python 3.x and github3

import github3
g = github3.login(token='qwerty')
r = g.repository(owner='me', repository='mine')

so far so good, now I tried looking around for a method that would extract the tags, r has a method called tags, also, looking at the documentation I found RepoTags.
Furthermore I found this question on Stack here.
Bottom line I'm a new developer and I couldn't get it to work, here are some of my more relevant tries and errors if anyone can point me in the right direction, the end result is to get a list of tags that are available for that repo, and then iter through them to get the content of each tag.

t1 = tags(1)
t1.as_json

that returned <bound method GitHubCore.as_json of <GitHubIterator [1, /repos/owner/repository_name/tags]>>

I tried tag = github3.repos.tag.RepoTag that returned nothing, when I try to see the methods the object 'tag' contains, none of them returned anything useful to me.

Body:
I'm not entirely certain what your final goal is, but here is how one would iterate over the tags on a repository.

import github3

gh = github3.login(token='myAwesomeToken')
repository = gh.repository(owner='owner',
                           repository='myAwesomeProjectWithLotsofTags')
for tag in repository.tags():
    assert isinstance(tag, github3.repos.tag.RepoTag)
    print('{} @ {}'.format(tag.name, tag.commit))

For future context, most (if not all) of the methods in github3.py that return lists actually return an iterator that generates the objects you're expecting. You actually have to iterate over them (as is explained in the documentation) to retrieve the items. This allows users to conserve API requests instead of trying to list everything or requiring the user to handle paging.

ContentLicense: CC BY-SA 4.0


问:
ConfigParser removes quotes from empty values
I have an INI windows file with the following format:

```<code>[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""
</code>```

but if I get values using ConfigParser

```<code>init_values= ConfigParser.RawConfigParser(allow_no_value=True)
init_values.optionxform = str
init_values.read(init_file)
</code>```

and modify one of them (p.e. property 1)

```<code>init_values.set('STRINGS', 'property 1', '"world"')
init_values.write(configfile)
</code>```

I get the following result:

```<code>[STRINGS]
property 1 = "world"
property 2 =
PROPERTY 3 =
</code>```

All the quotes from empty values are removed.

How can I force to use quotes even in empty values?

答:
```<code>init_values.set('STRINGS', 'property 1', '"world"')
</code>```

If you look at what you are doing here, you are explicitly adding quotes to the value. If you were to remove the quotes around world, you would just get the following output:

```<code>[STRINGS]
property 1 = world
property 2 =
property 3 =
</code>```

That is because INI files don’t actually use quotes to signalize string values (since every value is a string).

What may be a problem though is that the parser explicitly recognizes "" as an empty string value and replaces it by the empty string, while quotes around other values are kept as they are. This is a built-in behavior of the 2.7 parser and cannot really be changed without implementing it yourself.

Note that in Python 3, this behavior was changed, so "" is being recognized as the string '""'.

Body:
I have an INI windows file with the following format:

[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""

but if I get values using ConfigParser

init_values= ConfigParser.RawConfigParser(allow_no_value=True)
init_values.optionxform = str
init_values.read(init_file)

and modify one of them (p.e. property 1)

init_values.set('STRINGS', 'property 1', '"world"')
init_values.write(configfile)

I get the following result:

[STRINGS]
property 1 = "world"
property 2 =
PROPERTY 3 =

All the quotes from empty values are removed.

How can I force to use quotes even in empty values?

Body:
init_values.set('STRINGS', 'property 1', '"world"')

If you look at what you are doing here, you are explicitly adding quotes to the value. If you were to remove the quotes around world, you would just get the following output:

[STRINGS]
property 1 = world
property 2 =
property 3 =

That is because INI files don’t actually use quotes to signalize string values (since every value is a string).

What may be a problem though is that the parser explicitly recognizes "" as an empty string value and replaces it by the empty string, while quotes around other values are kept as they are. This is a built-in behavior of the 2.7 parser and cannot really be changed without implementing it yourself.

Note that in Python 3, this behavior was changed, so "" is being recognized as the string '""'.


问:
while loop condition needs to check if dictionary contains items and return to main menu if not
I have the following code:
https://repl.it/JRi4/2
in which I am trying to implement a while loop in the searchplayer() sub.

Basically, I need to check to see if the dictionary player_info is full, and only then continue with the search. If it is empty (no items in player_info) then it needs to print "Add player details" and return to the mainmenu()

The code in question is here:

```<code>def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   mainmenu()

main()
</code>```

I have tried the following, that does not work:

```<code>def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   while player_info:
     if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   print("Nothing in player_info")
   mainmenu()

main()
</code>```

Error

```<code>player_info not defined
</code>```

The error suggests player_info is not defined, but it has been declared as a global variable

答:
your code will work perfectly if your code execute addplayers function first because here is global variable declared. If you want to access other function first than it will sure show you and error. so better you declare the global variable first. I mean in main() as your code described.

Update: as your below comment.

as your first question global variable worked fine from any sub but python has to know the variable is declared global.

Example from your code: when your program run your just give the choice 2 for executing searchplayer(). It will run and enter input as you instructed and when time to come access the global player_info it will show an error. Because python has not get yet any global variable.

```<code>=====WELCOME to the MAIN MENU=============
1..........Add New Players & Goals
2..........Search by Players (return average goals)
3----------Update Player Goals
4----------View All players
5..........Quit

=========================================

Enter choice: 2
===============SEARCH by player: Calculate average goals==================
Player name :  messi
Traceback (most recent call last):
  File "python", line 91, in <module>
  File "python", line 11, in main
  File "python", line 30, in mainmenu
  File "python", line 83, in searchplayer
NameError: name 'player_info' is not defined
</code>```

and I am again saying global variable can access from any sub but python has to know this variable is global. If python know any how the variable is global then you can operate it any where. That's why I was suggesting you to declare the variable as global in the main function. You can declare it anywhere or any function but execute the function first that's why python know the variable is global. I also mentioned that your code will work perfectly and explained it why.

Body:
I have the following code:
https://repl.it/JRi4/2
in which I am trying to implement a while loop in the searchplayer() sub.

Basically, I need to check to see if the dictionary player_info is full, and only then continue with the search. If it is empty (no items in player_info) then it needs to print "Add player details" and return to the mainmenu()

The code in question is here:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   mainmenu()

main()

I have tried the following, that does not work:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   while player_info:
     if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   print("Nothing in player_info")
   mainmenu()

main()

Error

player_info not defined

The error suggests player_info is not defined, but it has been declared as a global variable

Body:
your code will work perfectly if your code execute addplayers function first because here is global variable declared. If you want to access other function first than it will sure show you and error. so better you declare the global variable first. I mean in main() as your code described.

Update: as your below comment.

as your first question global variable worked fine from any sub but python has to know the variable is declared global.

Example from your code: when your program run your just give the choice 2 for executing searchplayer(). It will run and enter input as you instructed and when time to come access the global player_info it will show an error. Because python has not get yet any global variable.

=====WELCOME to the MAIN MENU=============
1..........Add New Players & Goals
2..........Search by Players (return average goals)
3----------Update Player Goals
4----------View All players
5..........Quit

=========================================

Enter choice: 2
===============SEARCH by player: Calculate average goals==================
Player name :  messi
Traceback (most recent call last):
  File "python", line 91, in <module>
  File "python", line 11, in main
  File "python", line 30, in mainmenu
  File "python", line 83, in searchplayer
NameError: name 'player_info' is not defined

and I am again saying global variable can access from any sub but python has to know this variable is global. If python know any how the variable is global then you can operate it any where. That's why I was suggesting you to declare the variable as global in the main function. You can declare it anywhere or any function but execute the function first that's why python know the variable is global. I also mentioned that your code will work perfectly and explained it why.


问:
Hiding Empty Cells
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

```<code>Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub
</code>```

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

答:
```<code>Sheets("Sheet1").Range("A9:A12").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
</code>```

SpecialCells results in run-time error if no cells are found, but that can be checked:

```<code>If [CountBlank(Sheet1!A9:A12)] Then _
    [Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
</code>```

or ignored:

```<code>On Error Resume Next
[Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
</code>```

Title: Hiding Empty Cells

Body:
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

Body:
Sheets("Sheet1").Range("A9:A12").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True

SpecialCells results in run-time error if no cells are found, but that can be checked:

If [CountBlank(Sheet1!A9:A12)] Then _
    [Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True

or ignored:

On Error Resume Next
[Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True


问:
This leads to App crash. All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes)
Here is my entire build.gradle(Module:app) How to fix this? This is causing app crash. I have tried to add some more code by reading earlier/previous posts about it. But it didn't helped.
However it lead to successful gradle sync and successful installation of app.
Vut app crashes.

apply plugin: 'com.android.application'

```<code>android {
compileSdkVersion 25
buildToolsVersion "26.0.0"
defaultConfig {
    applicationId "com.example.akash.nbrider"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
     }
}
}

dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
         androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
         {
              exclude group: 'com.android.support', module: 'support-annotations'
         })
          compile 'com.android.support:appcompat-v7:25.3.1'
          // compile 'com.android.support:mediarouter-v7:25.3.1'
         compile 'com.android.support:design:25.3.1'
         compile 'com.android.support.constraint:constraint-layout:1.0.2'
         compile 'com.google.android.gms:play-services:8.4.0'
         /*compile 'com.google.android.gms:play-services-location:10.2.0'
         compile 'com.google.android.gms:play-services-maps:10.2.0'*/
}
</code>```

enter image description here

答:
Problem is with these two lines

```<code>buildToolsVersion "26.0.0"
...
compile 'com.android.support:appcompat-v7:25.3.1'
</code>```

They should use the same main version number. If there is v. 26 library you should use that one. Otherwise, downgrade buildToolsVersion to 25.

The easiest way to install 25 buildTools would be to just manually change to 25 in build.Gradle, Sync Gradle and you should get clickable link.

Body:
Here is my entire build.gradle(Module:app) How to fix this? This is causing app crash. I have tried to add some more code by reading earlier/previous posts about it. But it didn't helped.
However it lead to successful gradle sync and successful installation of app.
Vut app crashes.

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "26.0.0"
defaultConfig {
    applicationId "com.example.akash.nbrider"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
     }
}
}

dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
         androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
         {
              exclude group: 'com.android.support', module: 'support-annotations'
         })
          compile 'com.android.support:appcompat-v7:25.3.1'
          // compile 'com.android.support:mediarouter-v7:25.3.1'
         compile 'com.android.support:design:25.3.1'
         compile 'com.android.support.constraint:constraint-layout:1.0.2'
         compile 'com.google.android.gms:play-services:8.4.0'
         /*compile 'com.google.android.gms:play-services-location:10.2.0'
         compile 'com.google.android.gms:play-services-maps:10.2.0'*/
}

enter image description here

Body:
Problem is with these two lines

buildToolsVersion "26.0.0"
...
compile 'com.android.support:appcompat-v7:25.3.1'

They should use the same main version number. If there is v. 26 library you should use that one. Otherwise, downgrade buildToolsVersion to 25.

The easiest way to install 25 buildTools would be to just manually change to 25 in build.Gradle, Sync Gradle and you should get clickable link.


问:
How do you use T-SQL Full-Text Search to get results like Google?

What I Need

I have a database with fields that can contain long phrases of words. I wanted the ability to quickly search for a keyword or phrase in these columns, but when searching a phrase, I want to be able to search the phrase like Google would, returning all rows that contain all of the specified words, but in no particular order or "nearness" to each other. Ranking the results by relevance is unnecessary at this point.

After reading about SQL Server's Full-Text Search, I thought it would be just what I needed: a searchable index based on each word in a text-based column. My end goal is to safely accept user input and turn it into a query that leverages the speed of Full-Text Search, while maintaining ease-of-use for the users.

The Problem: Full-Text Search functions don't search like Google

I see the FREETEXT function can take an entire phrase, break it up into "useful" words (ignoring words like 'and', 'or', 'the', etc), and then return a list of matching rows very quickly, even with a complex search term. But when you try to use it, you may notice that instead of an AND search for each of the terms, it seems to only do an OR search. Maybe there's a way to change its behavior, but I haven't found anything useful.

Then there's CONTAINS, which can accept a boolean query phrase, but sometimes with odd results.

Take a look at the following queries on this table:

Data

```<code>PKID    Name
-----   -----
1       James Kirk
2       James Cameron
3       Kirk Cameron
4       Kirk For Cameron
</code>```

Queries

Q1: SELECT Name FROM tblName WHERE FREETEXT(Name, 'james')
Q2: SELECT Name FROM tblName WHERE FREETEXT(Name, 'james kirk')
Q3: SELECT Name FROM tblName WHERE FREETEXT(Name, 'kirk for cameron')
Q4: SELECT Name FROM tblName WHERE CONTAINS(Name, 'james')
Q5: SELECT Name FROM tblName WHERE CONTAINS(Name, '"james kirk"')
Q6: SELECT Name FROM tblName WHERE CONTAINS(Name, '"kirk james"')
Q7: SELECT Name FROM tblName WHERE CONTAINS(Name, 'james AND kirk')
Q8: SELECT Name FROM tblName WHERE CONTAINS(Name, 'kirk AND for AND cameron')
```

<h2>Query 1:</h2>

<pre class="lang-sql prettyprint-override"><code>SELECT Name FROM tblName WHERE FREETEXT(Name, 'james')
</code>```

Returns "James Kirk" and "James Cameron". Alright, lets narrow it down...

Query 2:

SELECT Name FROM tblName WHERE FREETEXT(Name, 'james kirk')
```

<p>Guess what. Now you'll get "James Kirk", "James Cameron", and "Kirk For Cameron". Same thing happens for <strong>Query 3</strong>, so let's just skip that.</p>

<h2>Query 4:</h2>

<pre class="lang-sql prettyprint-override"><code>SELECT Name FROM tblName WHERE CONTAINS(Name, 'james')
</code>```

Same results as Query 1. Okay. Narrow the results maybe...?

Query 5:

SELECT Name FROM tblName WHERE CONTAINS(Name, '"james kirk"')
```

<p>After discovering that you need to enclose the string in double-quotes if there are spaces, I find that this query works great on this particular dataset for the results I desire! Only "James Kirk" is returned. Wonderful! Or is it...</p>

<h2>Query 6:</h2>

<pre class="lang-sql prettyprint-override"><code>SELECT Name FROM tblName WHERE CONTAINS(Name, '"kirk james"')
</code>```

Crap. No. It is matching that exact phrase. Hmmm... After checking the syntax for T-SQL's CONTAINS function, I see that you can throw boolean keywords in there, and it looks like that might be the answer. Let's see...

Query 7:

SELECT Name FROM tblName WHERE CONTAINS(Name, 'james AND kirk')
```

<p>Neat. I get all three results, as expected. Now I just write a function to cram the word <code>AND</code> between all the words. Done, right? What now...</p>

<h2>Query 8:</h2>

<pre class="lang-sql prettyprint-override"><code>SELECT Name FROM tblName WHERE CONTAINS(Name, 'kirk AND for AND cameron')
</code>```

This query knows exactly what it's looking for, except for some reason, there are no results. Why? Well after reading about Stopwords and Stoplists, I will make an educated guess and say that because I'm asking for the intersection of the index results for "kirk", "for", and "cameron", and the word "for" will not have any results (what with it being a stopword and all), then the result of any intersection with that result is also empty. Whether or not it actually functions like that is irrelevant to me, since that is the observable behavior of the CONTAINS function every time I do a boolean search with a stopword in there.

So I need a new solution.

Here comes NEAR

Looks promising. If I can take a user query and put commas between it, this will... wait this is the same thing as using boolean AND in CONTAINS queries. But does it ignore stopwords correctly?

SELECT Name FROM tblName WHERE CONTAINS(Name, 'NEAR(kirk, for, cameron)')
```

Nope. No results. Remove the word "for", and you get all three results again. :(

What now?

答:
I am using ISAbout with combination of THESAURUS, INFLECTIONAL and Wildcards

Advantages are

1 - Order of words in the search string doesn't matter

2 - Search similar words (THESAURUS)

3 - Treat runs,running,ran,run as same (INFLECTIONAL)

4 - Near doesn't return result if search string has even one element which isn't in the resulting string, but ISAbout will always return the most desirable result

5 - You can set weight of different words, which will further help you to optimize correctness of your result

```<code>SELECT   K.RANK, name, Description
FROM      Diagnosis AS C
INNER JOIN
CONTAINSTABLE(diagnosis,name,<br> 'isAbout(FORMSOF (THESAURUS, "CHRONIC") weight(1.0),FORMSOF (INFLECTIONAL, "CHRONIC") weight(1.0),CHRONIC* weight(1.0)
FORMSOF (THESAURUS, "FAILURE") weight(1.0),FORMSOF (INFLECTIONAL, "FAILURE") weight(1.0),FAILURE* weight(1.0),
FORMSOF (THESAURUS, "DIASTOLIC") weight(1.0),FORMSOF (INFLECTIONAL, "DIASTOLIC") weight(1.0),DIASTOLIC* weight(1.0))')
AS K
ON C.ID = K.[KEY];
</code>```

I am still looking for ways to optimize it.

Note : I remove stop words from my search string programmatically.

Body:
What I Need

I have a database with fields that can contain long phrases of words. I wanted the ability to quickly search for a keyword or phrase in these columns, but when searching a phrase, I want to be able to search the phrase like Google would, returning all rows that contain all of the specified words, but in no particular order or "nearness" to each other. Ranking the results by relevance is unnecessary at this point.

After reading about SQL Server's Full-Text Search, I thought it would be just what I needed: a searchable index based on each word in a text-based column. My end goal is to safely accept user input and turn it into a query that leverages the speed of Full-Text Search, while maintaining ease-of-use for the users.

The Problem: Full-Text Search functions don't search like Google

I see the FREETEXT function can take an entire phrase, break it up into "useful" words (ignoring words like 'and', 'or', 'the', etc), and then return a list of matching rows very quickly, even with a complex search term. But when you try to use it, you may notice that instead of an AND search for each of the terms, it seems to only do an OR search. Maybe there's a way to change its behavior, but I haven't found anything useful.

Then there's CONTAINS, which can accept a boolean query phrase, but sometimes with odd results.

Take a look at the following queries on this table:

Data

PKID    Name
-----   -----
1       James Kirk
2       James Cameron
3       Kirk Cameron
4       Kirk For Cameron

Queries

Q1: SELECT Name FROM tblName WHERE FREETEXT(Name, 'james')
Q2: SELECT Name FROM tblName WHERE FREETEXT(Name, 'james kirk')
Q3: SELECT Name FROM tblName WHERE FREETEXT(Name, 'kirk for cameron')
Q4: SELECT Name FROM tblName WHERE CONTAINS(Name, 'james')
Q5: SELECT Name FROM tblName WHERE CONTAINS(Name, '"james kirk"')
Q6: SELECT Name FROM tblName WHERE CONTAINS(Name, '"kirk james"')
Q7: SELECT Name FROM tblName WHERE CONTAINS(Name, 'james AND kirk')
Q8: SELECT Name FROM tblName WHERE CONTAINS(Name, 'kirk AND for AND cameron')

Query 1:

SELECT Name FROM tblName WHERE FREETEXT(Name, 'james')

Returns "James Kirk" and "James Cameron". Alright, lets narrow it down...

Query 2:

SELECT Name FROM tblName WHERE FREETEXT(Name, 'james kirk')

Guess what. Now you'll get "James Kirk", "James Cameron", and "Kirk For Cameron". Same thing happens for Query 3, so let's just skip that.

Query 4:

SELECT Name FROM tblName WHERE CONTAINS(Name, 'james')

Same results as Query 1. Okay. Narrow the results maybe...?

Query 5:

SELECT Name FROM tblName WHERE CONTAINS(Name, '"james kirk"')

After discovering that you need to enclose the string in double-quotes if there are spaces, I find that this query works great on this particular dataset for the results I desire! Only "James Kirk" is returned. Wonderful! Or is it...

Query 6:

SELECT Name FROM tblName WHERE CONTAINS(Name, '"kirk james"')

Crap. No. It is matching that exact phrase. Hmmm... After checking the syntax for T-SQL's CONTAINS function, I see that you can throw boolean keywords in there, and it looks like that might be the answer. Let's see...

Query 7:

SELECT Name FROM tblName WHERE CONTAINS(Name, 'james AND kirk')

Neat. I get all three results, as expected. Now I just write a function to cram the word AND between all the words. Done, right? What now...

Query 8:

SELECT Name FROM tblName WHERE CONTAINS(Name, 'kirk AND for AND cameron')

This query knows exactly what it's looking for, except for some reason, there are no results. Why? Well after reading about Stopwords and Stoplists, I will make an educated guess and say that because I'm asking for the intersection of the index results for "kirk", "for", and "cameron", and the word "for" will not have any results (what with it being a stopword and all), then the result of any intersection with that result is also empty. Whether or not it actually functions like that is irrelevant to me, since that is the observable behavior of the CONTAINS function every time I do a boolean search with a stopword in there.

So I need a new solution.

Here comes NEAR

Looks promising. If I can take a user query and put commas between it, this will... wait this is the same thing as using boolean AND in CONTAINS queries. But does it ignore stopwords correctly?

SELECT Name FROM tblName WHERE CONTAINS(Name, 'NEAR(kirk, for, cameron)')

Nope. No results. Remove the word "for", and you get all three results again. :(

What now?

Body:
I am using ISAbout with combination of THESAURUS, INFLECTIONAL and Wildcards

Advantages are

1 - Order of words in the search string doesn't matter

2 - Search similar words (THESAURUS)

3 - Treat runs,running,ran,run as same (INFLECTIONAL)

4 - Near doesn't return result if search string has even one element which isn't in the resulting string, but ISAbout will always return the most desirable result

5 - You can set weight of different words, which will further help you to optimize correctness of your result

SELECT   K.RANK, name, Description
FROM      Diagnosis AS C
INNER JOIN
CONTAINSTABLE(diagnosis,name,<br> 'isAbout(FORMSOF (THESAURUS, "CHRONIC") weight(1.0),FORMSOF (INFLECTIONAL, "CHRONIC") weight(1.0),CHRONIC* weight(1.0)
FORMSOF (THESAURUS, "FAILURE") weight(1.0),FORMSOF (INFLECTIONAL, "FAILURE") weight(1.0),FAILURE* weight(1.0),
FORMSOF (THESAURUS, "DIASTOLIC") weight(1.0),FORMSOF (INFLECTIONAL, "DIASTOLIC") weight(1.0),DIASTOLIC* weight(1.0))')
AS K
ON C.ID = K.[KEY];

I am still looking for ways to optimize it.

Note : I remove stop words from my search string programmatically.


问:
Storing IDs of table rows
sorry to bother some of you again. But I still haven't found a working answer to my problem.

I have a good old fashioned HTML table. Each reach has its unique ID. What I want to achieve with JavaScript is that this ID gets stored in a variable once I cklick a link on each row.

Might sound easy to you, I am new to JS and I can't figure it out to the end. Could someone help me please?

Thanks!

答:
The Onclick event of what you are clicking on can call a function like

```<code>function RecordClick( elem ) {
    mylocalVar = elem.id;
}
</code>```

by saying
    onclick="RecordClick(this);"

Title: Storing IDs of table rows

Body:
The Onclick event of what you are clicking on can call a function like

function RecordClick( elem ) {
    mylocalVar = elem.id;
}

by saying
    onclick="RecordClick(this);"


问:
MahApps MetroProgressBar does not work inside ControlTemplate
I would like to use MetroProgressBar in my UserControl.

```<code><UserControl x:Class="WpfApplication7.UserControl1">
    <StackPanel Background="#ccc">
        <controls:MetroProgressBar IsIndeterminate="True"/>
    </StackPanel>
</UserControl>
</code>```

It works fine. But now I need to support external content in the user control.
So I created a new one "UserControl2" to demo:

```<code><UserControl x:Class="WpfApplication7.UserControl2">
    <UserControl.Resources>
        <Style TargetType="{x:Type local:UserControl2}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:UserControl2}">
                        <StackPanel Background="#ccc">
                            <controls:MetroProgressBar IsIndeterminate="True"/>
                            <!--<ContentPresenter/>-->
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
</UserControl>
</code>```

Then I put the both controls to the form:

```<code><StackPanel>
        <local:UserControl1 Background="#ccc"/>
        <local:UserControl2 Background="#ccc" Margin="0,6,0,0"/>
</StackPanel>
</code>```

As result I see that UserControl2 does not show Progress Bar.
How can I fix it?

Note: In the designer UserControl2 is rendered as expected with progress bar.

答:
In your style for UserControl2, set properties EllipseDiameter and EllipseOffset to some value (default is 4), as shown below:

```<code> <Style TargetType="{x:Type local:UserControl2}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:UserControl2}">
                    <StackPanel Background="#ccc">
                        <controls:MetroProgressBar EllipseDiameter="12"
                                                   EllipseOffset="12"
                                                   IsIndeterminate="True"/>
                        <!--<ContentPresenter/>-->
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Body:
I would like to use MetroProgressBar in my UserControl.

<UserControl x:Class="WpfApplication7.UserControl1">
    <StackPanel Background="#ccc">
        <controls:MetroProgressBar IsIndeterminate="True"/>
    </StackPanel>
</UserControl>

It works fine. But now I need to support external content in the user control.
So I created a new one "UserControl2" to demo:

<UserControl x:Class="WpfApplication7.UserControl2">
    <UserControl.Resources>

    </UserControl.Resources>
</UserControl>

Then I put the both controls to the form:

<StackPanel>
        <local:UserControl1 Background="#ccc"/>
        <local:UserControl2 Background="#ccc" Margin="0,6,0,0"/>
</StackPanel>

As result I see that UserControl2 does not show Progress Bar.
How can I fix it?

Note: In the designer UserControl2 is rendered as expected with progress bar.

Body:
In your style for UserControl2, set properties EllipseDiameter and EllipseOffset to some value (default is 4), as shown below:

 <Style TargetType="{x:Type local:UserControl2}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:UserControl2}">
                    <StackPanel Background="#ccc">
                        <controls:MetroProgressBar EllipseDiameter="12"
                                                   EllipseOffset="12"
                                                   IsIndeterminate="True"/>
                        <!--<ContentPresenter/>-->
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


问:
how to convert certain columns as rows in r
I have a data frame like this

```<code>Htno         Subname             marks      credits
15mq1a0501     abc                43          3
15mq1a0501     xyz                55          6
15mq1a0502     abc                56          3
15mq1a0502     xyz                60          6
15mq1a0503     abc                10          0
15mq1a0503     xyz                56          6
</code>```

now i need a data frame to be converted like this

```<code>Htno               abc         xyz       Totalmarks        Totalcredits
15mq1a0501          43         55         98                  9
15mq1a0502          56         60        116                  9
15mq1a0503          10         56         66                  6
</code>```

I used dplyr package but I am not able to do so.

答:
You could use the following:

```<code>require(tidyverse)
df %>%
  spread(Subname, marks) %>%
  group_by(HTno) %>%
  summarise(abc = max(abc, na.rm = T), xyz = max(xyz, na.rm = T), Totalcredits = sum(credits)) %>%
  mutate(Totalmarks = abc + xyz)
</code>```

The result would be:

```<code>        HTno   abc   xyz Totalcredits Totalmarks
      <fctr> <dbl> <dbl>        <dbl>      <dbl>
1 15mq1a0501    43    55            9         98
2 15mq1a0502    56    60            9        116
3 15mq1a0503    10    56            6         66
</code>```

Body:
I have a data frame like this

Htno         Subname             marks      credits
15mq1a0501     abc                43          3
15mq1a0501     xyz                55          6
15mq1a0502     abc                56          3
15mq1a0502     xyz                60          6
15mq1a0503     abc                10          0
15mq1a0503     xyz                56          6

now i need a data frame to be converted like this

Htno               abc         xyz       Totalmarks        Totalcredits
15mq1a0501          43         55         98                  9
15mq1a0502          56         60        116                  9
15mq1a0503          10         56         66                  6

I used dplyr package but I am not able to do so.

Body:
You could use the following:

require(tidyverse)
df %>%
  spread(Subname, marks) %>%
  group_by(HTno) %>%
  summarise(abc = max(abc, na.rm = T), xyz = max(xyz, na.rm = T), Totalcredits = sum(credits)) %>%
  mutate(Totalmarks = abc + xyz)

The result would be:

        HTno   abc   xyz Totalcredits Totalmarks
      <fctr> <dbl> <dbl>        <dbl>      <dbl>
1 15mq1a0501    43    55            9         98
2 15mq1a0502    56    60            9        116
3 15mq1a0503    10    56            6         66


问:
In ObjectiveC using delegate how do I send a message without using a UIButton?
I recently learned to use delegates to send messages from one class to another whenever a button is pressed and I'd like to find out how to send a message without a button action. Apple documentation suggests a likely method is performSelector:(SEL)aSelector; but I had no luck when I tried to use it. Instead, this is what I tried.

In MicroTune.h, I defined a delegate and gave it a property

```<code>    @class Synth;

    @protocol TuningDelegate <NSObject>
        -(void)setTuning:(NSData *)tuningData;
    @end

    @interface MicroTune : NSObject
        {
        …
        }

    @property (assign) id<TuningDelegate> delegate;
    @end
</code>```

In Synth.h, I declared the class so it acts as a delegate

```<code>    #import "MicroTune.h"

    @interface Synth : NSObject <TuningDelegate>
</code>```

and in Synth.m, I created a method to let me know the message arrived

```<code>    #import "Synth.h"

    - (void)setTuning:(NSData *)tuningData
    {
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:tuningData];
        NSLog(@" hip hip %@", array);
    }
</code>```

EDIT

And, also in Synth.m, to make sure the delegate is recognised, I added the following

```<code>    - (id)initWithSampleRate:(float)sampleRate_
        { if ((self = [super init]))
            {
                microTuneClassObject.delegate = self;

                // etc. etc.

            } return self;
        }
                    (Use of undeclared identifier 'microTuneClassObject')
</code>```

and also tried

```<code>    MicroTune.delegate = self;
        (Property 'delegate' not found on object of type 'MicroTune')
</code>```

and

```<code>    self.MicroTune.delegate = self;
        (Property 'MicroTune' not found on object of type 'Synth *')
</code>```

And finally, in MicroTune.m, I defined a method to send the message

```<code>    #import "MicroTune.h"

    - (void)sendTuning:(NSData *)tuningData
    {
        [synthLock lock];
        [self.delegate setTuning:(NSData *)tuningData];
        [synthLock unlock];
    }
</code>```

but Xcode gave the following message.

```<code>      No type or protocol named 'TuningDelegate'
</code>```

Can someone kindly explain what I need to do to send the message ? Thanks.

CONCLUSION

The solution can be found in my supplementary answer.

答:
In MicroTune.h file,

instead of #import "Synth.h" write @class Synth

Body:
I recently learned to use delegates to send messages from one class to another whenever a button is pressed and I'd like to find out how to send a message without a button action. Apple documentation suggests a likely method is performSelector:(SEL)aSelector; but I had no luck when I tried to use it. Instead, this is what I tried.

In MicroTune.h, I defined a delegate and gave it a property

    @class Synth;

    @protocol TuningDelegate <NSObject>
        -(void)setTuning:(NSData *)tuningData;
    @end

    @interface MicroTune : NSObject
        {
        …
        }

    @property (assign) id<TuningDelegate> delegate;
    @end

In Synth.h, I declared the class so it acts as a delegate

    #import "MicroTune.h"

    @interface Synth : NSObject <TuningDelegate>

and in Synth.m, I created a method to let me know the message arrived

    #import "Synth.h"

    - (void)setTuning:(NSData *)tuningData
    {
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:tuningData];
        NSLog(@" hip hip %@", array);
    }

EDIT

And, also in Synth.m, to make sure the delegate is recognised, I added the following

    - (id)initWithSampleRate:(float)sampleRate_
        { if ((self = [super init]))
            {
                microTuneClassObject.delegate = self;

                // etc. etc.

            } return self;
        }
                    (Use of undeclared identifier 'microTuneClassObject')

and also tried

    MicroTune.delegate = self;
        (Property 'delegate' not found on object of type 'MicroTune')

and

    self.MicroTune.delegate = self;
        (Property 'MicroTune' not found on object of type 'Synth *')

And finally, in MicroTune.m, I defined a method to send the message

    #import "MicroTune.h"

    - (void)sendTuning:(NSData *)tuningData
    {
        [synthLock lock];
        [self.delegate setTuning:(NSData *)tuningData];
        [synthLock unlock];
    }

but Xcode gave the following message.

      No type or protocol named 'TuningDelegate'

Can someone kindly explain what I need to do to send the message ? Thanks.

CONCLUSION

The solution can be found in my supplementary answer.


问:
" PHP Warning: pg_connect(): Unable to connect to PostgreSQL server: FATAL: password authentication failed for user ..." in Raspberry Pi (Stretch)
So sorry to bother everyone, I'm new to PostgreSQL, but my project requires me to build an automation system that connects to a server running PostgreSQL server. Long story short, let's just say I am required to perform a data insertion/manipulation from a Web Form into the server via PHP pg_connect(). The Web Form is located locally in /var/www/html/web_form.html and calls to a PHP script that performs the data insertion,

```<code>    <form name="some_name" action="script.php" method="POST">
</code>```

so the data insertion is done to a local server.

I'm using a Raspberry Pi 3 to simulate the "server" (as so not to "disturb" the true running server during such an early development). The Raspberry Pi is running a Raspbian Stretch distro. Well, it was originally Jessie, but then I decided to involve the Stretch repo from

```<code>    deb http://mirrordirector.raspbian.org/raspbian/ stretch main contrib non-free rpi
</code>```

with a priority of 100. It also has postgresql-9.6.3 (from Stretch), php7.0.19-1 (also from Stretch), and apache2.4.25 (from official Raspbian). Please do note that the Stretch repo do replaces A LOT of Jessie's official stable packages, and also known to be "not quite stable" itself, so it might also be the source of the problem.

I can access the database in the server from remote computers, whether using direct psql, Python (psycopg2), or even the exact same Web Form via PHP (tried from remote computer), so it will mostly won't be because of PDO problems (I've checked phpinfo() , but feel free to give advice on this, since I don't really understand PDO myself). On local, I can access the database via psql, but not local access via PHP (pg_connect).

I've meddled with this problem for hours now in vain. Please help me.

Here's my Raspberry Pi's configurations:

1.
A snippet of the PHP code:

```<code>    $conn_str="host=localhost port=5432 dbname=my_db_name user=my_user_name password=my_password";
    $db = pg_connect($conn_str);
    if(!$db){
        $errormessage=pg_last_error();
        echo "Error 0: " . $errormessage;
        exit();
    }
</code>```

Please mind that this same code has perfectly worked on another computer. I've succeeded to perform data insertion when the Web Form is located in a remote computer accessing the said server, or when the Web Form is accessing the remote computer's own local PostgreSQL server, but not when it is done in this particular problem server. When running in browser, it only shows:

```<code>    Error 0:
</code>```

the result when running in console:

```<code>PHP Warning:  pg_connect(): Unable to connect to PostgreSQL server: FATAL:  password authentication failed for user "raspiserver"

FATAL:  password authentication failed for user "raspiserver" in php shell code on line 1
</code>```

I also have tried to change host=localhost to host=127.0.0.1 or host=0.0.0.0. I'm sure that the error came from that block of code, since that block is already on the first lines in my PHP code, while the other error reporting codes I put, each has distinct Error X: number.

2.
The PostgreSQL configurations:

For the pg_hba.conf content :

```<code>    # Database administrative login by Unix domain socket
    local   all             postgres                                peer

    # TYPE  DATABASE        USER            ADDRESS                 METHOD

    # "local" is for Unix domain socket connections only
    local   my_db_name     my_user_name     127.0.0.1/32            md5
    local   all     all                                             md5
    # IPv4 local connections:
    host    all             all             127.0.0.1/32            md5

    # IPv6 local connections:
    host    all             all             ::1/128                 md5
    # Allow replication connections from localhost, by a user with the
    # replication privilege.
    # local   replication     postgres                                peer
    #host    replication     postgres        127.0.0.1/32            md5
    #host    replication     postgres        ::1/128                 md5

    #host   all             all             0.0.0.0/0               md5
    host    another_db_name      my_user_name             192.168.52.0/24         trust
    host    my_db_name     my_user_name             192.168.52.0/24         trust
</code>```

I already tried to comment/uncomment LINE 7, or change both LINE 7 and 8 to either md5 , trust , or password . I also have tried to remove 127.0.0.1/32 from LINE 7, or change it to 127.0.0.0/24 or 0.0.0.0/0 . And, yes, I did performed

```<code>    sudo /etc/init.d/postgresql reload
    sudo /etc/init.d/postgresql restart
</code>```

(even sudo reboot) for every change I've made.

For the postgresql.conf content :

I already set listen_addresses = '*' and password_encryption = on , with the rest remained unchanged.

3.
Firewall :

sudo iptables -L -n doesn't show any entries :

```<code>    Chain INPUT (policy ACCEPT)
    target     prot opt source               destination

    Chain FORWARD (policy ACCEPT)
    target     prot opt source               destination

    Chain OUTPUT (policy ACCEPT)
    target     prot opt source               destination
</code>```

What is wrong with my configurations?
Are Stretch the cause?
Or is it because the implementation of PostgreSQL-9.6?

I've already googled here and there, but most of the solutions only advice to change the pg_hba.conf to trust , or assume that the user name is not exist.

I'm desperate, please help.

(Please do mind that I don't know anything regarding PHP, PostgreSQL, Apache, or server, so please don't expect that I really know what I've done so far. Please do analyze everything.... Also, English is not my native, so I might mixed around some "jargons" here and there (if any).... Sorry for that... )

答:
This particular declaration in pg_hba.conf is incorrect:

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD
local   my_db_name     my_user_name     127.0.0.1/32            md5
</code>```

because when the TYPE field is local, the line must have 4 fields, not 5: there is no ADDRESS field because it doesn't apply to Unix domain sockets (which is what local really means), only to TCP connections (which are declared with TYPE being host or hostssl)

When you reload PostgreSQL with a pg_hba.conf with this line, it will fail with

```<code>LOG:  invalid authentication method "127.0.0.1/32"
</code>```

but you will see that only if looking in the server log. As a result of the failure, it will ignore your new version of pg_hba.conf.

Anyway this other line already in your file

```<code>host    all             all             127.0.0.1/32            md5
</code>```

probably does what you want. In this case just remove the offending line, reload again, and check the server log for a message indicating the success of the reload.

Body:
So sorry to bother everyone, I'm new to PostgreSQL, but my project requires me to build an automation system that connects to a server running PostgreSQL server. Long story short, let's just say I am required to perform a data insertion/manipulation from a Web Form into the server via PHP pg_connect(). The Web Form is located locally in /var/www/html/web_form.html and calls to a PHP script that performs the data insertion,

    <form name="some_name" action="script.php" method="POST">

so the data insertion is done to a local server.

I'm using a Raspberry Pi 3 to simulate the "server" (as so not to "disturb" the true running server during such an early development). The Raspberry Pi is running a Raspbian Stretch distro. Well, it was originally Jessie, but then I decided to involve the Stretch repo from

    deb http://mirrordirector.raspbian.org/raspbian/ stretch main contrib non-free rpi

with a priority of 100. It also has postgresql-9.6.3 (from Stretch), php7.0.19-1 (also from Stretch), and apache2.4.25 (from official Raspbian). Please do note that the Stretch repo do replaces A LOT of Jessie's official stable packages, and also known to be "not quite stable" itself, so it might also be the source of the problem.

I can access the database in the server from remote computers, whether using direct psql, Python (psycopg2), or even the exact same Web Form via PHP (tried from remote computer), so it will mostly won't be because of PDO problems (I've checked phpinfo() , but feel free to give advice on this, since I don't really understand PDO myself). On local, I can access the database via psql, but not local access via PHP (pg_connect).

I've meddled with this problem for hours now in vain. Please help me.

Here's my Raspberry Pi's configurations:

1.
A snippet of the PHP code:

    $conn_str="host=localhost port=5432 dbname=my_db_name user=my_user_name password=my_password";
    $db = pg_connect($conn_str);
    if(!$db){
        $errormessage=pg_last_error();
        echo "Error 0: " . $errormessage;
        exit();
    }

Please mind that this same code has perfectly worked on another computer. I've succeeded to perform data insertion when the Web Form is located in a remote computer accessing the said server, or when the Web Form is accessing the remote computer's own local PostgreSQL server, but not when it is done in this particular problem server. When running in browser, it only shows:

    Error 0:

the result when running in console:

PHP Warning:  pg_connect(): Unable to connect to PostgreSQL server: FATAL:  password authentication failed for user "raspiserver"

FATAL:  password authentication failed for user "raspiserver" in php shell code on line 1

I also have tried to change host=localhost to host=127.0.0.1 or host=0.0.0.0. I'm sure that the error came from that block of code, since that block is already on the first lines in my PHP code, while the other error reporting codes I put, each has distinct Error X: number.

2.
The PostgreSQL configurations:

For the pg_hba.conf content :

    # Database administrative login by Unix domain socket
    local   all             postgres                                peer

    # TYPE  DATABASE        USER            ADDRESS                 METHOD

    # "local" is for Unix domain socket connections only
    local   my_db_name     my_user_name     127.0.0.1/32            md5
    local   all     all                                             md5
    # IPv4 local connections:
    host    all             all             127.0.0.1/32            md5

    # IPv6 local connections:
    host    all             all             ::1/128                 md5
    # Allow replication connections from localhost, by a user with the
    # replication privilege.
    # local   replication     postgres                                peer
    #host    replication     postgres        127.0.0.1/32            md5
    #host    replication     postgres        ::1/128                 md5

    #host   all             all             0.0.0.0/0               md5
    host    another_db_name      my_user_name             192.168.52.0/24         trust
    host    my_db_name     my_user_name             192.168.52.0/24         trust

I already tried to comment/uncomment LINE 7, or change both LINE 7 and 8 to either md5 , trust , or password . I also have tried to remove 127.0.0.1/32 from LINE 7, or change it to 127.0.0.0/24 or 0.0.0.0/0 . And, yes, I did performed

    sudo /etc/init.d/postgresql reload
    sudo /etc/init.d/postgresql restart

(even sudo reboot) for every change I've made.

For the postgresql.conf content :

I already set listen_addresses = '*' and password_encryption = on , with the rest remained unchanged.

3.
Firewall :

sudo iptables -L -n doesn't show any entries :

    Chain INPUT (policy ACCEPT)
    target     prot opt source               destination

    Chain FORWARD (policy ACCEPT)
    target     prot opt source               destination

    Chain OUTPUT (policy ACCEPT)
    target     prot opt source               destination

What is wrong with my configurations?
Are Stretch the cause?
Or is it because the implementation of PostgreSQL-9.6?

I've already googled here and there, but most of the solutions only advice to change the pg_hba.conf to trust , or assume that the user name is not exist.

I'm desperate, please help.

(Please do mind that I don't know anything regarding PHP, PostgreSQL, Apache, or server, so please don't expect that I really know what I've done so far. Please do analyze everything.... Also, English is not my native, so I might mixed around some "jargons" here and there (if any).... Sorry for that... )

Body:
This particular declaration in pg_hba.conf is incorrect:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   my_db_name     my_user_name     127.0.0.1/32            md5

because when the TYPE field is local, the line must have 4 fields, not 5: there is no ADDRESS field because it doesn't apply to Unix domain sockets (which is what local really means), only to TCP connections (which are declared with TYPE being host or hostssl)

When you reload PostgreSQL with a pg_hba.conf with this line, it will fail with

LOG:  invalid authentication method "127.0.0.1/32"

but you will see that only if looking in the server log. As a result of the failure, it will ignore your new version of pg_hba.conf.

Anyway this other line already in your file

host    all             all             127.0.0.1/32            md5

probably does what you want. In this case just remove the offending line, reload again, and check the server log for a message indicating the success of the reload.


问:
Error while trying to parse a website url using python . how to debug it?
```<code>#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits:
    print ' ', h['url']
    resp = urllib.urlopen(h['url'])
        res = resp.read()

    soup = BeautifulSoup(res)
        print soup.prettify()
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('sachin')
</code>```

What is the wrong in this code ?

Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?

答:
What is the wrong in this code ?

Your indentation is all wonky in the for loop, and this line:

```<code>import BeautifulSoup
</code>```

should be deleted, as it masks this earlier import:

```<code>from BeautifulSoup import BeautifulSoup
</code>```

Body:
#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits:
    print ' ', h['url']
    resp = urllib.urlopen(h['url'])
        res = resp.read()

    soup = BeautifulSoup(res)
        print soup.prettify()
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('sachin')

What is the wrong in this code ?

Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?

Body:
What is the wrong in this code ?

Your indentation is all wonky in the for loop, and this line:

import BeautifulSoup

should be deleted, as it masks this earlier import:

from BeautifulSoup import BeautifulSoup


问:
small/tiny and overlap button, toolbox and etc in windbg on windows 10
I installed windbg on windows 10 (it worked fine on windows 7 for example)
The toolbar is too small, some text boxes are overlapped with other objects.

the text in some places was too small as well and I solved it by changing the font size of windbg, but it didn't solve the toolbox and the text-box issue

I think that maybe this problem is not related to windbg only, and it will reproduced in another applications

Any help would be appreciated.

you can see a screenshot here:

Thanks!

答: I'm guessing you are running with High DPI? WinDbg is probably not fully DPI aware.</p>


问:
how to register and install hook in prestashop 1.7?
I have added one module hook manage box in PrestaShop 1.7 . Module is installed and i have created one hook called dispalybeforehome but it is not showing me in my module. how to register it ?</p>

答:
In your module during the installation, with the install method you should add this snippet:

```<code>$this->registerHook('displayBeforeHome');
</code>```

For example:

```<code>public function install()
{
    return parent::install() and $this->registerHook('displayBeforeHome');
}
</code>```

Then you have to create the hookDisplayBeforeHome method in your module:

```<code>public function hookDisplayBeforeHome($params)
{
    // do your stuff
    return 'IT WORKS!';
}
</code>```

Then in the template add the smarty snippet to call the hook:

```<code>{hook h='displayBeforeHome'}
</code>```

That's all ;)

Body:
In your module during the installation, with the install method you should add this snippet:

$this->registerHook('displayBeforeHome');

For example:

public function install()
{
    return parent::install() and $this->registerHook('displayBeforeHome');
}

Then you have to create the hookDisplayBeforeHome method in your module:

public function hookDisplayBeforeHome($params)
{
    // do your stuff
    return 'IT WORKS!';
}

Then in the template add the smarty snippet to call the hook:

{hook h='displayBeforeHome'}

That's all ;)


问:
What data structure should I use to store a collection of items in C#?
I have following string : [Value:"Car" - Name:"Manufactor" [Value:"Audi" - Name:"A6"][Value:"BMW" - Name:"M4"]]]

I need to split the string and save data into suitable data structure. Starting bracket "[" indicates the beginning of the collection, and
matching ending bracket "]" indicates the end of the collection. The "-" character seperates key and values. So I was wondering what is most
logical datastructure to use here? Is using a tree good solution? I have splitted the string up in parts, I only need help to choose a logical datastructure.

Thanks!

答:
string is not well-formed I guess (3 opening brackets and 4 closing ones)

that makes your string ambiguous, especially with these 3 closing brackets at the end


问:
Spring Batch - FlatFileItemReader for different delimited files
I have two different files, one delimited by pipe separator "|" and one by comma ",".

I am using Spring Batch to process these files using FlatFileItemReader. I dont want to have two readers and two writers for the files.
Can I have somehow one generic FlatFileItemReader for both files?

Also the objects to which the files will be mapped are different.

答:
You can inject a DelimitedLineTokenizer and you can set the delimiter as per requirement. you can make it generic using StepExecutionListener and need to override the beforeStep() method. You will set delimiter in StepExecution.
When you parse the file which are "," seperated then
stepExecution.getExecutionContext().putString("delimiter", ",");
and when file is seperated with "|" then stepExecution.getExecutionContext().putString("delimiter", "|");

But you need to create two jobs. Need to specify listener accordingly.

You can see the example of above explain logic from Spring Batch on Walking Techie

Code for generic Reader:

```<code>@Bean
  @StepScope
  public FlatFileItemReader<Domain> reader(@Value("#{stepExecutionContext[delimiter]}") String delimiter) {
    FlatFileItemReader<Domain> reader = new FlatFileItemReader<>();
    reader.setResource(new ClassPathResource("sample-data.csv"));
    reader.setLineMapper(new DefaultLineMapper<Domain>() {{
      setLineTokenizer(new DelimitedLineTokenizer() {{
        setNames(new String[]{"id", "name"});
        setDelimiter(delimiter);
      }});
      setFieldSetMapper(new BeanWrapperFieldSetMapper<Domain>() {{
        setTargetType(Domain.class);
      }});
    }});
    return reader;
  }
</code>```

You can find the many examples on spring batch in spring boot from Spring Batch Tutorial. You will find here all kind of problems related to spring batch.

Body:
You can inject a DelimitedLineTokenizer and you can set the delimiter as per requirement. you can make it generic using StepExecutionListener and need to override the beforeStep() method. You will set delimiter in StepExecution.
When you parse the file which are "," seperated then
stepExecution.getExecutionContext().putString("delimiter", ",");
and when file is seperated with "|" then stepExecution.getExecutionContext().putString("delimiter", "|");

But you need to create two jobs. Need to specify listener accordingly.

You can see the example of above explain logic from Spring Batch on Walking Techie

Code for generic Reader:

@Bean
  @StepScope
  public FlatFileItemReader<Domain> reader(@Value("#{stepExecutionContext[delimiter]}") String delimiter) {
    FlatFileItemReader<Domain> reader = new FlatFileItemReader<>();
    reader.setResource(new ClassPathResource("sample-data.csv"));
    reader.setLineMapper(new DefaultLineMapper<Domain>() {{
      setLineTokenizer(new DelimitedLineTokenizer() {{
        setNames(new String[]{"id", "name"});
        setDelimiter(delimiter);
      }});
      setFieldSetMapper(new BeanWrapperFieldSetMapper<Domain>() {{
        setTargetType(Domain.class);
      }});
    }});
    return reader;
  }

You can find the many examples on spring batch in spring boot from Spring Batch Tutorial. You will find here all kind of problems related to spring batch.


答:
After trying your entire code, what I advise you to do here is switch your SearchPlayer with this one:

```<code>def searchplayer():
    print("===============SEARCH by player: Calculate average goals==================")

    if len(player_info.keys())==0:
        print("you have no players registered")
    else:
        name = input("Player name : ")
        while name not in player_info.keys():
            print("Please enter a valid player name:")
            name = input("Player name: ")
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))

    print()
    mainmenu()
</code>```

one more thing, you didn't ask about it but you should add a checker for the type of input when asking from user to make decisions by handling exceptions as follows:

```<code>try:
    choice=int(input("Enter choice:"))
except:
    print("Input must be int from 1-5")
    mainmenu()
</code>```

it is useful to prevent your app from crashing by mistake when i input strings instead of int.

if you don't want to use recursion you could do this:

```<code>proceed = True

def main():
    while proceed:
        mainmenu()
</code>```

and change:

```<code>sys.exit()
</code>```

with:

```<code>proceed = False
</code>```

( i just chose  to take off sys.exit() from the code because it was generating some warning )

and take off mainmenu() for all your methods. that should do it nicely

so your entire code should be like this (I'm not familiar with repl.it sorry):

```<code>#SOLUTION==================FOOTBALL COACH app

#The program allows a user to enter a number of students (their names and test
#scores) and then search for a student, returning their average score for the
#three tests

#1------Create a similar program for a football coach (he wants to store player
#names + goals for 3 matches)
#2 -----main menu that allows for 1. Adding players + goals and 2. Search by
#Player 3. Quit
#3-----When complete, go back and add additional menu options for "View all
#players" and Update". This allows the coach to update the number of goals for
#any given player as well as view all

import sys #note the sys.exit() command will not work without this

player_info={}
proceed = True

def main():
    while proceed:
       mainmenu()

def mainmenu():
    global proceed
    print("=====WELCOME to the MAIN MENU=============")
    print("""
  1..........Add New Players & Goals
  2..........Search by Players (return average goals)
  3----------Update Player Goals
  4----------View All players
  5..........Quit

  =========================================
  """)
    try:
        choice=int(input("Enter choice:"))
    except:
        print("Input must be int from 1-5")
        mainmenu()

    if choice==1:
        playerinfo=addplayers()
    elif choice==2:
        searchplayer()
    elif choice==3:
        update()
    elif choice==4:
        viewall()
    elif choice==5:
        proceed = False
    else:
        print("You must make a valid choice - 1, 2 or 3")

def viewall():

    for keys, values in player_info.items():
        print(keys, values)
    print()

def update():
    playername=input("Which player's goals do you wish to update?:")
    m1=int(input("Match 1 new entry:"))
    m2=int(input("Match 2 new entry:"))
    m3=int(input("Match 3 new entry:"))
    if playername in player_info:
        #myDict["A"] = "Application"
        player_info[playername]="Boo"
        player_info[playername]={"Match 1 goals":m1,"Match 2 goals":m2,"Match 3 goals":m3}

def addplayers():
    global player_info #this needs to be declared as a global variable so it can be used by searchplayer()
    player_info= {} #create a dictionary that stores the player name: player goals
    num_players = int(input("Please enter number of players you wish to enter:"))
    print ("You are entering %s players" %num_players)
    player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
    for i in range(0,num_players):
        player_name = input("Enter Player Name :")
        player_info[player_name] = {}
        for entry in player_data:
            player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
        print()

def searchplayer():
    print("===============SEARCH by player: Calculate average goals==================")
    if not player_info:
        print("you have no players registered")
    else:
        name = input("Player name : ")
        while name not in player_info.keys():
            print("Please enter a valid player name:")
            name = input("Player name: ")
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))

    print()

main()
</code>```

Hope that helped

Title: while loop condition needs to check if dictionary contains items and return to main menu if not

Body:
I have the following code:
https://repl.it/JRi4/2
in which I am trying to implement a while loop in the searchplayer() sub.

Basically, I need to check to see if the dictionary player_info is full, and only then continue with the search. If it is empty (no items in player_info) then it needs to print "Add player details" and return to the mainmenu()

The code in question is here:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   mainmenu()

main()

I have tried the following, that does not work:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   while player_info:
     if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   print("Nothing in player_info")
   mainmenu()

main()

Error

player_info not defined

The error suggests player_info is not defined, but it has been declared as a global variable

Body:
After trying your entire code, what I advise you to do here is switch your SearchPlayer with this one:

def searchplayer():
    print("===============SEARCH by player: Calculate average goals==================")

    if len(player_info.keys())==0:
        print("you have no players registered")
    else:
        name = input("Player name : ")
        while name not in player_info.keys():
            print("Please enter a valid player name:")
            name = input("Player name: ")
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))

    print()
    mainmenu()

one more thing, you didn't ask about it but you should add a checker for the type of input when asking from user to make decisions by handling exceptions as follows:

try:
    choice=int(input("Enter choice:"))
except:
    print("Input must be int from 1-5")
    mainmenu()

it is useful to prevent your app from crashing by mistake when i input strings instead of int.

if you don't want to use recursion you could do this:

proceed = True

def main():
    while proceed:
        mainmenu()

and change:

sys.exit()

with:

proceed = False

( i just chose  to take off sys.exit() from the code because it was generating some warning )

and take off mainmenu() for all your methods. that should do it nicely

so your entire code should be like this (I'm not familiar with repl.it sorry):

#SOLUTION==================FOOTBALL COACH app

#The program allows a user to enter a number of students (their names and test
#scores) and then search for a student, returning their average score for the
#three tests

#1------Create a similar program for a football coach (he wants to store player
#names + goals for 3 matches)
#2 -----main menu that allows for 1. Adding players + goals and 2. Search by
#Player 3. Quit
#3-----When complete, go back and add additional menu options for "View all
#players" and Update". This allows the coach to update the number of goals for
#any given player as well as view all

import sys #note the sys.exit() command will not work without this

player_info={}
proceed = True

def main():
    while proceed:
       mainmenu()

def mainmenu():
    global proceed
    print("=====WELCOME to the MAIN MENU=============")
    print("""
  1..........Add New Players & Goals
  2..........Search by Players (return average goals)
  3----------Update Player Goals
  4----------View All players
  5..........Quit

  =========================================
  """)
    try:
        choice=int(input("Enter choice:"))
    except:
        print("Input must be int from 1-5")
        mainmenu()

    if choice==1:
        playerinfo=addplayers()
    elif choice==2:
        searchplayer()
    elif choice==3:
        update()
    elif choice==4:
        viewall()
    elif choice==5:
        proceed = False
    else:
        print("You must make a valid choice - 1, 2 or 3")

def viewall():

    for keys, values in player_info.items():
        print(keys, values)
    print()

def update():
    playername=input("Which player's goals do you wish to update?:")
    m1=int(input("Match 1 new entry:"))
    m2=int(input("Match 2 new entry:"))
    m3=int(input("Match 3 new entry:"))
    if playername in player_info:
        #myDict["A"] = "Application"
        player_info[playername]="Boo"
        player_info[playername]={"Match 1 goals":m1,"Match 2 goals":m2,"Match 3 goals":m3}

def addplayers():
    global player_info #this needs to be declared as a global variable so it can be used by searchplayer()
    player_info= {} #create a dictionary that stores the player name: player goals
    num_players = int(input("Please enter number of players you wish to enter:"))
    print ("You are entering %s players" %num_players)
    player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
    for i in range(0,num_players):
        player_name = input("Enter Player Name :")
        player_info[player_name] = {}
        for entry in player_data:
            player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
        print()

def searchplayer():
    print("===============SEARCH by player: Calculate average goals==================")
    if not player_info:
        print("you have no players registered")
    else:
        name = input("Player name : ")
        while name not in player_info.keys():
            print("Please enter a valid player name:")
            name = input("Player name: ")
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))

    print()

main()

Hope that helped


答:
When you create your table on the server-side you put this in your HTML (as I understand your scenario):

```<code>...
<tr>
    <td>
        <a href="...">Some link name</a>
    </td>
</tr>
...
</code>```

So why not do this:

```<code><script>
    var rowID = -1;
</script>
...
<tr>
    <td>
        <a href="javascript: rowID = 111; void(0);">Some link name</a>
    </td>
</tr>
...
</code>```

This is not the best way of doing it, but it gets the job done. If you're using some library like jQuery, you could do it in a completely different way and using closures as well.

Title: Storing IDs of table rows

Body:
sorry to bother some of you again. But I still haven't found a working answer to my problem.

I have a good old fashioned HTML table. Each reach has its unique ID. What I want to achieve with JavaScript is that this ID gets stored in a variable once I cklick a link on each row.

Might sound easy to you, I am new to JS and I can't figure it out to the end. Could someone help me please?

Thanks!

Body:
When you create your table on the server-side you put this in your HTML (as I understand your scenario):

...
<tr>
    <td>
        <a href="...">Some link name</a>
    </td>
</tr>
...

So why not do this:

<script>
    var rowID = -1;
</script>
...
<tr>
    <td>
        <a href="javascript: rowID = 111; void(0);">Some link name</a>
    </td>
</tr>
...

This is not the best way of doing it, but it gets the job done. If you're using some library like jQuery, you could do it in a completely different way and using closures as well.


问:
Determine reference equality of two objects in different scopes while debugging
Assuming I have a reference type class Foo { } and I am passing the reference of an instance of it to two separate methods

```<code>void Main()
{
   Foo f = new Foo();

   Bar(f);
   Baz(f);
}

void Bar(Foo f)
{
  // ...
}

void Baz(Foo f)
{
  // ...
}
</code>```

how can I find out whether the objects I see in Bar and Baz point to the same object in memory while I am debugging? I guess looking at GetHashCode() is not necessarily an indicator, because I could have overridden GetHashCode() in Foo to always return 0 for instance.

Independently of the fact that it's impossible in C# and my little knowledge of pointers, I guess looking at the address the references point to would give me the certainty.

What options do I have?

答:
There is a little feature in Visual Studio debugger that exactly suits your needs without having to implement something.

Just set the break points on your methods. When one of the break points hits, add the object you're interested in (the f parameter of Foo type) into the Watches list. You can indeed find that object in the Autos or Locals windows too.

Then do the trick: right click on the object entry in the list and select Make Object ID. A numerical ID appears to the right of the object's value in the list.

Now continue debugging. When your second break point hits, you'll see in your Locals, Autos and maybe Watches windows that the f object appears with the same ID. That means - it's the same object instance. If there were no ID or it were different, then this would be a different instance of Foo.

Body:
Assuming I have a reference type class Foo { } and I am passing the reference of an instance of it to two separate methods

void Main()
{
   Foo f = new Foo();

   Bar(f);
   Baz(f);
}

void Bar(Foo f)
{
  // ...
}

void Baz(Foo f)
{
  // ...
}

how can I find out whether the objects I see in Bar and Baz point to the same object in memory while I am debugging? I guess looking at GetHashCode() is not necessarily an indicator, because I could have overridden GetHashCode() in Foo to always return 0 for instance.

Independently of the fact that it's impossible in C# and my little knowledge of pointers, I guess looking at the address the references point to would give me the certainty.

What options do I have?


问:
& in URL mess up $_GET variables
We get URLs with & instead of & from a clients system: somedomain.com?param1=test&param2=test2

I expect to get $_GET['param1'] and $_GET['param2']. Instead I get $_GET['amp;param1'] and $_GET['amp;param2']

Do I fix it as an rewrite rule in .htaccess or in PHP?

UPDATE:

A temporary fix is to do the below, but it seems clumsy:

```<code>foreach ($_GET AS $key => $value)
{
    $param = str_replace('amp;', '', $key);
    $_GET[$param] = $value;
    unset($_GET[$key]);
}
</code>```

答:
Convert characters ? and & to some tokens like:

? to __Q__ with str_replace('?', '__Q__', $toUrl)

& to __AND__ with str_replace('&', '__AND__', $toUrl)

And pass this data on url.

While getting this data from url, decode these back.

str_replace('__Q__', '?', $fromUrl)

str_replace('__AND__', '&', $fromUrl)

Though its tricky, it works.

Title: & in URL mess up $_GET variables

Body:
We get URLs with & instead of & from a clients system: somedomain.com?param1=test&param2=test2

I expect to get $_GET['param1'] and $_GET['param2']. Instead I get $_GET['amp;param1'] and $_GET['amp;param2']

Do I fix it as an rewrite rule in .htaccess or in PHP?

UPDATE:

A temporary fix is to do the below, but it seems clumsy:

foreach ($_GET AS $key => $value)
{
    $param = str_replace('amp;', '', $key);
    $_GET[$param] = $value;
    unset($_GET[$key]);
}