text stringlengths 1 2.12k | source dict |
|---|---|
java, performance, android, formatting
pressNumber = PRESS_MTONCE;
doOnClick = CHANGE_ON_CLICK;
doOnClickRelease = RETURN_ON_RELEASE;
doOnPass = NTG_ON_PASS;
doOnRelease = NTG_ON_RELEASE;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, Vector2f position){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (null);
this.position.add(position);
this.size.add(new Vector2f(1,1));
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
pressNumber = PRESS_MTONCE;
doOnClick = CHANGE_ON_CLICK;
doOnClickRelease = RETURN_ON_RELEASE;
doOnPass = NTG_ON_PASS;
doOnRelease = NTG_ON_RELEASE;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, Vector2f position, Vector2f size){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (null);
this.position.add(position);
this.size.add(size);
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
pressNumber = PRESS_MTONCE;
doOnClick = CHANGE_ON_CLICK;
doOnClickRelease = RETURN_ON_RELEASE;
doOnPass = NTG_ON_PASS;
doOnRelease = NTG_ON_RELEASE;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, GUIBase stateReleased, Vector2f position){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (stateReleased);
this.position.add(position);
this.size.add(new Vector2f(1,1));
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
this.stateReleased.position.set(0,this.position.get(0));
this.stateReleased.scale.get(0).multiply(this.size.get(0));
this.stateReleased.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
pressNumber = PRESS_MTONCE;
doOnClick = CHANGE_ON_CLICK;
doOnClickRelease = RETURN_ON_RELEASE;
doOnPass = NTG_ON_PASS;
doOnRelease = NTG_ON_RELEASE;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, GUIBase stateReleased, Vector2f position, Vector2f size){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (stateReleased);
this.position.add(position);
this.size.add(size); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
this.position.add(position);
this.size.add(size);
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
this.stateReleased.position.set(0,this.position.get(0));
this.stateReleased.scale.get(0).multiply(this.size.get(0));
this.stateReleased.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
pressNumber = PRESS_MTONCE;
doOnClick = CHANGE_ON_CLICK;
doOnClickRelease = RETURN_ON_RELEASE;
doOnPass = NTG_ON_PASS;
doOnRelease = NTG_ON_RELEASE;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (null);
this.position.add(new Vector2f(0,0));
this.size.add(new Vector2f(1,1));
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, GUIBase stateReleased, int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (stateReleased);
position.add(new Vector2f(0,0));
this.size.add(new Vector2f(1,1));
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
this.stateReleased.position.set(0,this.position.get(0));
this.stateReleased.scale.get(0).multiply(this.size.get(0));
this.stateReleased.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, Vector2f position, int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (null);
this.position.add(position);
this.size.add(new Vector2f(1,1)); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
this.position.add(position);
this.size.add(new Vector2f(1,1));
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, Vector2f position, Vector2f size, int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.stateDefault = stateDefault;
this.statePressed = statePressed;
this.stateReleased = null;
this.position.add(position);
this.size.add(size);
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, GUIBase stateReleased, Vector2f position, int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (stateReleased);
this.position.add(position);
this.size.add(new Vector2f(1,1));
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
this.stateReleased.position.set(0,this.position.get(0));
this.stateReleased.scale.get(0).multiply(this.size.get(0));
this.stateReleased.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public Button(GUIBase stateDefault, GUIBase statePressed, GUIBase stateReleased, Vector2f position, Vector2f size, int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.stateDefault = (stateDefault);
this.statePressed = (statePressed);
this.stateReleased = (stateReleased);
this.position.add(position);
this.size.add(size); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
this.position.add(position);
this.size.add(size);
this.stateDefault.position.set(0,this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0,true);
this.statePressed.position.set(0,this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0,false);
this.stateReleased.position.set(0,this.position.get(0));
this.stateReleased.scale.get(0).multiply(this.size.get(0));
this.stateReleased.show.set(0,false);
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
state.add(STATE_DEFAULT);
name.add("button"+(name.size()));
}
public void setBehavior( int pressNumber,int doOnClick, int doOnClickRelease, int doOnPass, int doOnRelease){
this.pressNumber = pressNumber;
this.doOnClick = doOnClick;
this.doOnClickRelease = doOnClickRelease;
this.doOnPass = doOnPass;
this.doOnRelease = doOnRelease;
}
public void setName(int index,String name){this.name.set(index,name);}
public void checkClickAt(Vector2f click,int index){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
if(((pos.x>position.get(index).x-size.get(index).x)&&(pos.x<position.get(index).x+size.get(index).x))&&
((pos.y>position.get(index).y-size.get(index).y)&&(pos.y<position.get(index).y+size.get(index).y))){
if(!hasClickedOff.get(index)) {
click(index);
}
}else {
}
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
}
}
public void checkClickAt(Vector2f click){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
for (int i = 0; i < name.size(); i++) {
if (((pos.x > position.get(i).x - size.get(i).x) && (pos.x < position.get(i).x + size.get(i).x)) &&
((pos.y > position.get(i).y - size.get(i).y) && (pos.y < position.get(i).y + size.get(i).y))) {
if(!hasClickedOff.get(i)){
click(i);
}
}else {
boolean tmp = false;
if(isPressed.get(i)) {
tmp = true;
release(i);
}
if(tmp){hasClickedOff.set(i,true);}
}
}
}
public void checkPassAt(Vector2f click,int index){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
if(((pos.x>position.get(index).x-size.get(index).x)&&(pos.x<position.get(index).x+size.get(index).x))&&
((pos.y>position.get(index).y-size.get(index).y)&&(pos.y<position.get(index).y+size.get(index).y))){
if(!hasClickedOff.get(index)) {
passOn(index);
}
}else{if(isHovering.get(index)){
passOff(index);
}}
}
public void checkPassAt(Vector2f click){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
for (int i = 0; i < name.size(); i++) {
if (((pos.x > position.get(i).x - size.get(i).x) && (pos.x < position.get(i).x + size.get(i).x)) &&
((pos.y > position.get(i).y - size.get(i).y) && (pos.y < position.get(i).y + size.get(i).y))) {
if(!hasClickedOff.get(i)) {
passOn(i);
}
}else{if(isHovering.get(i)){passOff(i);}}
}
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void checkReleaseIn(Vector2f click,int index){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
if(((pos.x>position.get(index).x-size.get(index).x)&&(pos.x<position.get(index).x+size.get(index).x))&&
((pos.y>position.get(index).y-size.get(index).y)&&(pos.y<position.get(index).y+size.get(index).y))) {
release(index);
}
}
public void checkReleaseIn(Vector2f click){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
for (int i = 0; i < name.size(); i++) {
if (((pos.x > position.get(i).x - size.get(i).x) && (pos.x < position.get(i).x + size.get(i).x)) &&
((pos.y > position.get(i).y - size.get(i).y) && (pos.y < position.get(i).y + size.get(i).y))) {
release(i);
}
}
}
public void checkReleaseOut(Vector2f click,int index){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
if(((pos.x<position.get(index).x-size.get(index).x)||(pos.x>position.get(index).x+size.get(index).x))||
((pos.y<position.get(index).y-size.get(index).y)||(pos.y>position.get(index).y+size.get(index).y))) {
boolean tmp = false;
if(isPressed.get(index)){
tmp = true;
release(index);
}
if(tmp){hasClickedOff.set(index,true);}
}
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void checkReleaseOut(Vector2f click){
Vector2f pos = Vector2f.scale(Vector2f.sub(click,Vector2f.scale(stateDefault.screenDimensions,0.5f)),2f);
for (int i = 0; i < name.size(); i++) {
if (((pos.x < position.get(i).x - size.get(i).x) || (pos.x > position.get(i).x + size.get(i).x)) ||
((pos.y > position.get(i).y - size.get(i).y) || (pos.y < position.get(i).y + size.get(i).y))) {
boolean tmp = false;
if(isPressed.get(i)){
tmp = true;
release(i);
}
if(tmp){hasClickedOff.set(i,true);}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void click(int index){
switch (pressNumber){
case CANNOT_PRESS:
Log.w("clickButton","You can't press this button!");
break;
case PRESS_ONCE:
switch (doOnClick){
case STAY_ON_CLICK:
if(!hasBeenPressed.get(index)){
isPressed.set(index,true);
hasBeenPressed.set(index,true);
}
break;
case CHANGE_ON_CLICK:
if(!hasBeenPressed.get(index)){
isPressed.set(index,true);
hasBeenPressed.set(index,true);
state.set(index,STATE_PRESSED);
}
break;
default:
Log.e("clickButton","doOnClick can't be : " + doOnClick + ", it must either be STAY_ON_CLICK or CHANGE_ON_CLICK.");
break;
}
break;
case PRESS_MTONCE:
switch (doOnClick){
case STAY_ON_CLICK:
isPressed.set(index,true);
hasBeenPressed.set(index,true);
break;
case CHANGE_ON_CLICK:
isPressed.set(index,true);
hasBeenPressed.set(index,true);
state.set(index,STATE_PRESSED);
break;
default:
Log.e("clickButton","invalid value for doOnClick : "+doOnClick);
break;
}
break;
default:
Log.e("clickButton","invalid value for pressNumber : "+pressNumber);
break;
}
updateIcon(index);
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void release(int index){
if(isPressed.get(index)){
switch (doOnClickRelease){
case STAY_ON_RELEASE:
isPressed.set(index,false);
hasBeenPressed.set(index,true);
state.set(index,STATE_PRESSED);
break;
case CHANGE_ON_RELEASE:
isPressed.set(index,false);
hasBeenPressed.set(index,true);
state.set(index,STATE_RELEASED);
break;
case RETURN_ON_RELEASE:
isPressed.set(index,false);
hasBeenPressed.set(index,true);
state.set(index,STATE_DEFAULT);
break;
default:
Log.e("releaseButton","invalid value for doOnClickRelease : "+doOnClickRelease);
break;
}
updateIcon(index);
}else {
switch (doOnRelease){
case NTG_ON_RELEASE:
state.set(index,STATE_DEFAULT);
break;
case CLICK_ON_RELEASE:
click(index);
release(index);
break;
default:
Log.e("releaseButton","invalid value for doOnRelease : "+doOnRelease);
break;
}
}
isHovering.set(index,true);
hasClickedOff.set(index,false);
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void passOn(int index){
switch (doOnPass){
case NTG_ON_PASS:
isHovering.set(index,true);
break;
case PREVIEW_ON_PASS:
state.set(index,STATE_PRESSED);
isHovering.set(index,true);
break;
case CHANGE_ON_PASS:
state.set(index,STATE_RELEASED);
isHovering.set(index,true);
break;
case CLICK_ON_PASS:
click(index);
isHovering.set(index,true);
break;
default:
Log.e("passOnButton","invalid value for doOnPass : "+doOnPass);
break;
}
updateIcon(index);
}
public void passOff(int index){
Log.w("passOff","passOff");
if(doOnPass != CLICK_ON_PASS){
Log.w("checkPassAt","!ClickOnPass");
state.set(index,STATE_DEFAULT);
isHovering.set(index,false);
}
updateIcon(index);
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void updateIcon(int index){
//Log.w("updateButtonIcon","state : "+state.get(index));
switch (state.get(index)){
case STATE_DEFAULT:
stateDefault.show.set(index,true);
statePressed.show.set(index,false);
if(stateReleased != null){stateReleased.show.set(index,false);}
break;
case STATE_PRESSED:
stateDefault.show.set(index,false);
statePressed.show.set(index,true);
if(stateReleased != null){stateReleased.show.set(index,false);}
break;
case STATE_RELEASED:
stateDefault.show.set(index,false);
statePressed.show.set(index,false);
if (stateReleased!= null){stateReleased.show.set(index,true);}else
{Log.e("updateButtonIcon",name.get(index)+" has no stateReleased icon!");}
break;
default:
throw new IllegalStateException("Unexpected value: " + state.get(index));
}
stateDefault.position.set(index,position.get(index));
statePressed.position.set(index,position.get(index));
if(stateReleased != null) {
stateReleased.position.set(index, position.get(index));
}
}
public Button copy(){
Button button = new Button(stateDefault,statePressed,stateReleased,pressNumber,doOnClick,doOnClickRelease,doOnPass,doOnRelease);
button.position = new ArrayList<>(position);
button.size = new ArrayList<>(size);
button.state = new ArrayList<>(state);
button.isPressed = new ArrayList<>(isPressed);
button.hasBeenPressed = new ArrayList<>(isPressed);
button.name = new ArrayList<>(name);
button.isHovering = new ArrayList<>(isHovering);
return button;
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void addInstance(){
isPressed.add(false);
hasBeenPressed.add(false);
position.add(new Vector2f(0,0));
size.add(new Vector2f(1,1));
state.add(STATE_DEFAULT);
stateDefault.instance(0);
stateDefault.position.set(stateDefault.position.size()-1,new Vector2f(0,0));
statePressed.instance(0);
statePressed.position.set(statePressed.position.size()-1,new Vector2f(0,0));
stateReleased.instance(0);
stateReleased.position.set(stateReleased.position.size()-1,new Vector2f(0,0));
Log.w("addInstance","added instance");
}
public void addInstance(Vector2f position,Vector2f size){
isPressed.add(false);
hasBeenPressed.add(false);
this.position.add(position);
size.add(size);
state.add(STATE_DEFAULT);
stateDefault.addInstance(position,0,size);
statePressed.addInstance(position,0,size);
stateReleased.addInstance(position,0,size);
Log.w("addInstance","added instance");
}
public void instance(int index){
isPressed.add(isPressed.get(index));
hasBeenPressed.add(hasBeenPressed.get(index));
this.position.add(position.get(index));
size.add(size.get(index));
state.add(state.get(index));
stateDefault.instance(index);
statePressed.instance(index);
stateReleased.instance(index);
Log.w("Instance","instanced"+index);
}
public void removeInstance(int index){
isPressed.remove(index);
hasBeenPressed.remove(index);
this.position.remove(index);
size.remove(index);
state.remove(index);
stateDefault.removeInstance(index);
statePressed.removeInstance(index);
stateReleased.removeInstance(index);
Log.w("removedInstance","instance removed "+index);
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void reset(int index){
isPressed.set(index,false);
hasBeenPressed.set(index,false);
state.set(index,STATE_DEFAULT);
}
public void setPosition(int index, Vector2f pos){
position.set(index,pos);
stateDefault.position.set(index,pos);
statePressed.position.set(index,pos);
stateReleased.position.set(index,pos);
}
public void setSize(int index, Vector2f s){
size.set(index,s);
stateDefault.scale.set(index,s);
statePressed.scale.set(index,s);
stateReleased.scale.set(index,s);
}
}
If anything is unclear, please tell me in the comments, I will update as soon as possible.
I would like to know what improvements I should do and if my code has some overly complex stuff. I'm especially looking at the amount of initialisers and if there's a better way to do this and som tips as to what I should include in the initialisation. | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
Answer: Making variables public is not terrible in a toy project. In anything more significant than that, it makes maintenance very hard. For instance, right now anybody that can see a Button can change its state or add or remove from any of the various lists, and the button has no way of knowing that its internal state has been modified in unsupported and unintended ways.
Code should not make micro-optimizations for performance reasons until there is a clearly tested bottleneck in the code. There is a long history of micro-optimizations that have no noticeable impact on users and make code harder to maintain. First use repeatable performance testing to find actual performance bottlenecks, then fix them.
Variables that are not intended to be reassigned should be marked as final.
Classes that are not carefully and explicitly designed for extension should be marked final.
Prefer the most generally applicable type when making assignments. None of the code cares about what List implementation is used, so values should be assigned to List, not ArrayList.
//I'm using arraylists to make it so that I can instance the button. I'm not an Android developer, so maybe that's the problem, but I have no idea what this means.
Both sets of constants should probably be enums. The inline comments should be javadoc. Using multiple enums for the different types of settings lets the compile ensure clients are not setting invalid values, such as accidentally passing in CHANGE_ON_CLICK for a button press. Type safety is a Good Thing. The variables then no longer need to document their type in the name.
Try to avoid abbreviations. For instance, PRESS_MTONCE is not meaningful to most readers. I needed to look at the comment to see it meant PRESS_MORE_THAN_ONCE. NTG_ON_PASS is maybe "nothing"? Very hard to tell.
There are 12 constructors. That's about 9 too many. It's unmaintainable. Either use a Builder or make some of the variables properties that can/must be set after construction. | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
The copy method should be either a copy constructor (public Button(Button buttonToCopy)) or can be facilitated as part of the builder.
It is neither necessary nor desirable to have parenthesis around simple assignments such as this.stateDefault = (stateDefault).
In idiomatic java, there is whitespace between ) and {
In idiomatic java, there is whitespace after a comma.
In idiomatic java, there is whitespace between a control flow keyword (if, for, etc) and an open paren.
In idiomatic java, there is whitespace around operators (==, &&, =`, etc).
In idiomatic java, there is whitespace between } and else.
Code is much harder to read when it's squished on one line. This:
public void setName(int index,String name){this.name.set(index,name);} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
is much harder to read than this:
public void setName(int index,String name) {
this.name.set(index,name);
}
An empty else block is confusing and should be avoided.
Avoid nesting if checks when they can be combined.
Code such as in checkClickAt would benefit from extracting variables. For instance, position.get(index); -> indexPosition.
Common code can be extracted for the two checkClickAt methods - the if block which checks if the click was inside a space. That code will be useful in later methods as well. It might look like:
private boolean isClickInside(Vector2f click, int index) {
Vector2f clickPosition =
Vector2f.scale(Vector2f.sub(click, Vector2f.scale(stateDefault.screenDimensions, 0.5f)), 2f);
Vector2f indexPosition = position.get(index);
Vector2f indexSize = size.get(index);
return (((clickPosition.x > indexPosition.x - indexSize.x) && (clickPosition.x < indexPosition.x + indexSize.x))
&& ((clickPosition.y > indexPosition.y - indexPosition.y) && (clickPosition.y < indexPosition.y + indexSize.y)));
}
wasPressed would be a better name than tmp.
release checks isPressed, so there's no need to do it in checkClickAt also. Alternately, the two if checks can be combined.
else if is preferable to else { if .
The second checkPassAt can be modified to call the first, since it loops over and does the same thing.
checkReleaseOut can be simplified by having the second instance call the first, since it loops over and does the same thing.
There's more work to be done, but I'm out of juice. If you were to make all these changes, your class might look more like:
public final class Button {
private final GUIBase stateDefault;
private final GUIBase statePressed;
private final GUIBase stateReleased; | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
private final List<Boolean> isPressed = new ArrayList<>();
private final List<Boolean> hasBeenPressed = new ArrayList<>();
private final List<Boolean> isHovering = new ArrayList<>();
private final List<Boolean> hasClickedOff = new ArrayList<>();
private final List<Vector2f> position = new ArrayList<>();
private final List<Vector2f> size = new ArrayList<>();
private final List<String> name = new ArrayList<>();
private PressBehavior pressBehavior;
private ClickBehavior doOnClick;
private ClickReleaseBehavior doOnClickRelease;
private PassBehavior doOnPass;
private ReleaseBehavior doOnRelease;
private final List<Integer> state = new ArrayList<>();
public static final int STATE_DEFAULT = 12;
public static final int STATE_PRESSED = 13;
public static final int STATE_RELEASED = 14; | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public static Button.Builder builder(GUIBase stateDefault, GUIBase statePressed) {
return new Button.Builder(stateDefault, statePressed);
}
public Button(Button buttonToCopy) {
this.stateDefault = buttonToCopy.stateDefault;
this.statePressed = buttonToCopy.statePressed;
this.stateReleased = buttonToCopy.stateReleased;
this.position.clear();
this.size.clear();
this.state.clear();
this.isPressed.clear();
this.hasBeenPressed.clear();
this.name.clear();
this.isHovering.clear();
this.position.addAll(buttonToCopy.position);
this.size.addAll(buttonToCopy.size);
this.state.addAll(buttonToCopy.state);
this.isPressed.addAll(buttonToCopy.isPressed);
this.hasBeenPressed.addAll(buttonToCopy.hasBeenPressed);
this.name.addAll(buttonToCopy.name);
this.isHovering.addAll(buttonToCopy.isHovering);
this.pressBehavior = buttonToCopy.pressBehavior;
this.doOnClick = buttonToCopy.doOnClick;
this.doOnClickRelease = buttonToCopy.doOnClickRelease;
this.doOnPass = buttonToCopy.doOnPass;
this.doOnRelease = buttonToCopy.doOnRelease;
}
private Button(
GUIBase stateDefault,
GUIBase statePressed,
GUIBase stateReleased,
Vector2f position,
Vector2f size) {
this.stateDefault = stateDefault;
this.statePressed = statePressed;
this.stateReleased = stateReleased;
position.add(position);
this.size.add(size);
this.stateDefault.position.set(0, this.position.get(0));
this.stateDefault.scale.get(0).multiply(this.size.get(0));
this.stateDefault.show.set(0, true);
this.statePressed.position.set(0, this.position.get(0));
this.statePressed.scale.get(0).multiply(this.size.get(0));
this.statePressed.show.set(0, false); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
if (this.stateReleased != null) {
this.stateReleased.position.set(0, this.position.get(0));
this.stateReleased.scale.get(0).multiply(this.size.get(0));
this.stateReleased.show.set(0, false);
}
isPressed.add(false);
hasBeenPressed.add(false);
isHovering.add(false);
hasClickedOff.add(false);
state.add(STATE_DEFAULT);
name.add("button" + (name.size()));
}
public void setBehavior(
PressBehavior pressBehavior,
ClickBehavior clickBehavior,
ClickReleaseBehavior clickReleaseBehavior,
PassBehavior passBehavior,
ReleaseBehavior releaseBehavior) {
this.pressBehavior = pressBehavior;
this.doOnClick = clickBehavior;
this.doOnClickRelease = clickReleaseBehavior;
this.doOnPass = passBehavior;
this.doOnRelease = releaseBehavior;
}
public void setName(int index, String name) {
this.name.set(index, name);
}
public void checkClickAt(Vector2f click, int index) {
if (isClickInside(click, index) && !hasClickedOff.get(index)) {
click(index);
}
}
public void checkClickAt(Vector2f click) {
for (int i = 0; i < name.size(); i++) {
if (isClickInside(click, i) && !hasClickedOff.get(i)) {
click(i);
} else if (isPressed.get(i)) {
release(i);
hasClickedOff.set(i, true);
}
}
}
public void checkPassAt(Vector2f click, int index) {
if (isClickInside(click, index) && !hasClickedOff.get(index)) {
passOn(index);
} else if (isHovering.get(index)) {
passOff(index);
}
}
public void checkPassAt(Vector2f click) {
for (int i = 0; i < name.size(); i++) {
checkPassAt(click, i);
}
}
public void checkReleaseIn(Vector2f click, int index) {
if (isClickInside(click, index)) {
release(index);
}
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void checkReleaseIn(Vector2f click) {
for (int i = 0; i < name.size(); i++) {
checkReleaseIn(click, i);
}
}
public void checkReleaseOut(Vector2f click, int index) {
if (isClickInside(click, index) && isPressed.get(index)) {
release(index);
hasClickedOff.set(index, true);
}
}
public void checkReleaseOut(Vector2f click) {
for (int i = 0; i < name.size(); i++) {
checkReleaseOut(click, i);
}
}
public void click(int index) {
switch (pressBehavior) {
case CANNOT_PRESS:
Log.w("clickButton", "You can't press this button!");
break;
case PRESS_ONCE:
switch (doOnClick) {
case STAY:
if (!hasBeenPressed.get(index)) {
isPressed.set(index, true);
hasBeenPressed.set(index, true);
}
break;
case CHANGE:
if (!hasBeenPressed.get(index)) {
isPressed.set(index, true);
hasBeenPressed.set(index, true);
state.set(index, STATE_PRESSED);
}
break;
default:
Log.e("clickButton",
"doOnClick can't be : " + doOnClick + ", it must either be STAY_ON_CLICK or CHANGE_ON_CLICK.");
break;
}
break;
case PRESS_MORE_THAN_ONCE:
switch (doOnClick) {
case STAY:
isPressed.set(index, true);
hasBeenPressed.set(index, true);
break;
case CHANGE:
isPressed.set(index, true);
hasBeenPressed.set(index, true);
state.set(index, STATE_PRESSED);
break;
default:
Log.e("clickButton", "invalid value for doOnClick : " + doOnClick);
break;
}
break;
default:
Log.e("clickButton", "invalid value for pressBehavior : " + pressBehavior);
break;
}
updateIcon(index);
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void release(int index) {
if (isPressed.get(index)) {
switch (doOnClickRelease) {
case STAY:
isPressed.set(index, false);
hasBeenPressed.set(index, true);
state.set(index, STATE_PRESSED);
break;
case CHANGE:
isPressed.set(index, false);
hasBeenPressed.set(index, true);
state.set(index, STATE_RELEASED);
break;
case RETURN:
isPressed.set(index, false);
hasBeenPressed.set(index, true);
state.set(index, STATE_DEFAULT);
break;
default:
Log.e("releaseButton", "invalid value for doOnClickRelease : " + doOnClickRelease);
break;
}
updateIcon(index);
} else {
switch (doOnRelease) {
case NOTHING:
state.set(index, STATE_DEFAULT);
break;
case CLICK:
click(index);
release(index);
break;
default:
Log.e("releaseButton", "invalid value for doOnRelease : " + doOnRelease);
break;
}
}
isHovering.set(index, true);
hasClickedOff.set(index, false);
}
public void passOn(int index) {
switch (doOnPass) {
case NOTHING:
isHovering.set(index, true);
break;
case PREVIEW:
state.set(index, STATE_PRESSED);
isHovering.set(index, true);
break;
case CHANGE:
state.set(index, STATE_RELEASED);
isHovering.set(index, true);
break;
case CLICK:
click(index);
isHovering.set(index, true);
break;
default:
Log.e("passOnButton", "invalid value for doOnPass : " + doOnPass);
break;
}
updateIcon(index);
}
public void passOff(int index) {
Log.w("passOff", "passOff");
if (doOnPass != PassBehavior.CLICK) {
Log.w("checkPassAt", "!ClickOnPass");
state.set(index, STATE_DEFAULT);
isHovering.set(index, false);
}
updateIcon(index);
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void updateIcon(int index) {
// Log.w("updateButtonIcon","state : "+state.get(index));
switch (state.get(index)) {
case STATE_DEFAULT:
stateDefault.show.set(index, true);
statePressed.show.set(index, false);
if (stateReleased != null) {
stateReleased.show.set(index, false);
}
break;
case STATE_PRESSED:
stateDefault.show.set(index, false);
statePressed.show.set(index, true);
if (stateReleased != null) {
stateReleased.show.set(index, false);
}
break;
case STATE_RELEASED:
stateDefault.show.set(index, false);
statePressed.show.set(index, false);
if (stateReleased != null) {
stateReleased.show.set(index, true);
} else {
Log.e("updateButtonIcon", name.get(index) + " has no stateReleased icon!");
}
break;
default:
throw new IllegalStateException("Unexpected value: " + state.get(index));
}
stateDefault.position.set(index, position.get(index));
statePressed.position.set(index, position.get(index));
if (stateReleased != null) {
stateReleased.position.set(index, position.get(index));
}
}
public void addInstance() {
isPressed.add(false);
hasBeenPressed.add(false);
position.add(new Vector2f(0, 0));
size.add(new Vector2f(1, 1));
state.add(STATE_DEFAULT);
stateDefault.instance(0);
stateDefault.position.set(stateDefault.position.size() - 1, new Vector2f(0, 0));
statePressed.instance(0);
statePressed.position.set(statePressed.position.size() - 1, new Vector2f(0, 0));
stateReleased.instance(0);
stateReleased.position.set(stateReleased.position.size() - 1, new Vector2f(0, 0));
Log.w("addInstance", "added instance");
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public void addInstance(Vector2f position, Vector2f size) {
isPressed.add(false);
hasBeenPressed.add(false);
this.position.add(position);
size.add(size);
state.add(STATE_DEFAULT);
stateDefault.addInstance(position, 0, size);
statePressed.addInstance(position, 0, size);
stateReleased.addInstance(position, 0, size);
Log.w("addInstance", "added instance");
}
public void instance(int index) {
isPressed.add(isPressed.get(index));
hasBeenPressed.add(hasBeenPressed.get(index));
this.position.add(position.get(index));
size.add(size.get(index));
state.add(state.get(index));
stateDefault.instance(index);
statePressed.instance(index);
stateReleased.instance(index);
Log.w("Instance", "instanced" + index);
}
public void removeInstance(int index) {
isPressed.remove(index);
hasBeenPressed.remove(index);
this.position.remove(index);
size.remove(index);
state.remove(index);
stateDefault.removeInstance(index);
statePressed.removeInstance(index);
stateReleased.removeInstance(index);
Log.w("removedInstance", "instance removed " + index);
}
public void reset(int index) {
isPressed.set(index, false);
hasBeenPressed.set(index, false);
state.set(index, STATE_DEFAULT);
}
public void setPosition(int index, Vector2f pos) {
position.set(index, pos);
stateDefault.position.set(index, pos);
statePressed.position.set(index, pos);
stateReleased.position.set(index, pos);
}
public void setSize(int index, Vector2f s) {
size.set(index, s);
stateDefault.scale.set(index, s);
statePressed.scale.set(index, s);
stateReleased.scale.set(index, s);
}
private boolean isClickInside(Vector2f click, int index) {
Vector2f clickPosition =
Vector2f.scale(Vector2f.sub(click, Vector2f.scale(stateDefault.screenDimensions, 0.5f)), 2f); | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
Vector2f indexPosition = position.get(index);
Vector2f indexSize = size.get(index);
return (((clickPosition.x > indexPosition.x - indexSize.x) && (clickPosition.x < indexPosition.x + indexSize.x))
&& ((clickPosition.y > indexPosition.y - indexPosition.y) && (clickPosition.y < indexPosition.y + indexSize.y)));
}
public static final class Builder {
private final GUIBase stateDefault;
private final GUIBase statePressed;
private GUIBase stateReleased;
private Vector2f position = new Vector2f(0, 0);
private Vector2f size = new Vector2f(1, 1);
private PressBehavior pressBehavior = PressBehavior.PRESS_MORE_THAN_ONCE;
private ClickBehavior clickBehavior = ClickBehavior.CHANGE;
private ClickReleaseBehavior clickReleaseBehavior = ClickReleaseBehavior.RETURN;
private PassBehavior passBehavior = PassBehavior.NOTHING;
private ReleaseBehavior releaseBehavior = ReleaseBehavior.NOTHING;
private Builder(GUIBase stateDefault, GUIBase statePressed) {
this.stateDefault = stateDefault;
this.statePressed = statePressed;
}
public Builder stateReleased(GUIBase stateReleased) {
this.stateReleased = stateReleased;
return this;
}
public Builder position(Vector2f position) {
this.position = position;
return this;
}
public Builder size(Vector2f size) {
this.size = size;
return this;
}
public Builder onPress(PressBehavior pressBehavior) {
this.pressBehavior = pressBehavior;
return this;
}
public Builder onClick(ClickBehavior clickBehavior) {
this.clickBehavior = clickBehavior;
return this;
}
public Builder onClickRelease(ClickReleaseBehavior clickReleaseBehavior) {
this.clickReleaseBehavior = clickReleaseBehavior;
return this;
}
public Builder onPass(PassBehavior passBehavior) {
this.passBehavior = passBehavior;
return this;
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
java, performance, android, formatting
public Builder onRelease(ReleaseBehavior releaseBehavior) {
this.releaseBehavior = releaseBehavior;
return this;
}
public Button build() {
final Button newButton = new Button(stateDefault, statePressed, stateReleased, position, size);
newButton.setBehavior(pressBehavior, clickBehavior, clickReleaseBehavior, passBehavior, releaseBehavior);
return newButton;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, android, formatting",
"url": null
} |
performance, c, physics
Title: C program that finds local acceleration due to gravity (g)
Question: I have written a program in C that calculates local g, by using height from the sea level and latitude.
NOTE: I have to add an image of the equation because that website is no longer active.
Here's my code:
#include <stdio.h>
#include <math.h>
double local_g(double latitide, double height_sea_lvl);
double local_g(double latitide, double height_sea_lvl)
{
const double A = 0.0053024;
const double B = 0.0000058;
double H2 = (0.000003 * height_sea_lvl);
double s1 = (A * sin(latitide));
double s2 = (B * sin(2 * latitide));
return (double)(9.780327 * (1 + s1 - s2) - H2);
}
int main(void)
{
printf("Enter latitude:\t");
double latitude = 0, height = 0;
if (scanf("%lf", &latitude) != 1)
{
fprintf(stderr, "bad input\n");
return 1;
}
printf("Enter height above sea level (in metres):\t");
if (scanf("%lf", &height) != 1)
{
fprintf(stderr, "bad input\n");
return 1;
}
printf("Your local g (accleration due to gravity): %0.10f\n", local_g(latitude, height));
return 0;
}
I compiled the above program using GCC v11.2.0 on Arch Linux
gcc -O3 -Ofast -Og -Os -s local_g.c -lm -o local_g
Can anyone suggests any sort of improvement for the above code, as I have followed most of the good C practices mentioned in many answer (highly up-voted one) on https://stackoverflow.com. | {
"domain": "codereview.stackexchange",
"id": 43035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, physics",
"url": null
} |
performance, c, physics
Answer: There's no need for the forward declaration of local_g() (especially as it's immediately followed by the definition). But it should be declared with static linkage.
Typo in the argument: should be latitude. Although this sounds trivial, consistently correct spelling can make large programs easier to search.
We specify the units when prompting for altitude, but not for latitude. The use directly in sin() suggests we need input in radians, which is certainly not what most users would expect. I'd suggest that input in degrees would be friendlier.
Top marks for actually testing whether the scanf() conversions were successful. Consider using the EXIT_FAILURE value as return value rather than bare 1 (it's defined in <stdlib.h>).
I've no idea whether the formula is correct (and it's obviously a simplification - real geodesy uses a parametric model that accounts for the non-uniform density of the Earth's crust). It doesn't match the formula in the image (which has A·sin²L and B·sin²2L rather than A·sin L and B·sin 2L), so I'm surprised this passes even the basic testing. Also, the height constant seems to have been mistranscribed - should be 3.086e-6 rather than 3e-6.
It seems that the constants A and B are directly taken from the formula, so those names are probably okay if there's no more descriptive word that fits. The other variables could be a bit more descriptive, I think.
The cast of the computation result (a double) to the same type is unnecessary clutter and should be omitted.
Printing to ten decimal places is probably too much given the claimed precision of the formula (±0.005%, i.e. 0.0005 m/s²). We should include units in the output (use of values with mis-assumed units is a known cause of engineering problems, especially if you have to work with US teams at any point). | {
"domain": "codereview.stackexchange",
"id": 43035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, physics",
"url": null
} |
performance, c, physics
There are no significant performance concerns in this function. Some platforms may have faster float computation than double (though that's not generally the case, and float can be slower) - that's something we can't determine for you, so you need to profile (and decide whether the loss of precision is worth any speed gain). You might consider -ffastmath compilation option, which will sacrifice correctness with strange values (subnormals, NaNs etc) for speed.
Your compiler flags don't include any warning options. I recommend at least -Wall -Wextra, and normally use quite a few more. When I compiled with my usual set of warnings, the code passed cleanly, but it's worth getting early notice of problems you introduce. | {
"domain": "codereview.stackexchange",
"id": 43035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, physics",
"url": null
} |
python
Title: Any better script using regular expressions?
Question: import re
from collections import Counter
def reader(filename):
with open(filename) as f:
file = f.read()
regex = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
final = re.findall(regex, file)
return final
def count(final):
print(Counter(final))
if __name__ == '__main__':
file_name = input("Enter file name: ")
count(reader(file_name))
Answer: If you are not planning to reuse these functions elsewhere, it does not make a whole lot of sense to split the logic like so. It does not make a lot of sense to use this python script as a CLI tool, either - grep -o | wc -l will do it for you, but I digress.
Feeding the filename after you run the script results in some poor usability - I would rather use argparse or, if you plan to do it interactively, not exit after one run. I would instead go with something like
import re
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
with open(args.filename) as f:
print(len(re.findall(pattern, f.read()))) | {
"domain": "codereview.stackexchange",
"id": 43036,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
algorithm, strings, haskell, palindrome
Title: Manacher Algorithm in Haskell
Question: Please review the manacher algorithm in haskell. Find the longest Palindrome in a String.
module Main where
import qualified Data.Vector as V
import Data.Maybe
import Data.Ord
-- manacher algorithm
-- $ ghci
-- $ :l manacher.hs
-- > manacher "aba"
manacher :: String -> String
manacher arg0 = filter (/= '|') . V.toList $ maximum' getList
where
getList :: [V.Vector Char]
getList = foreveryvchars 1 $ format arg0
-- get the maximum length palindrome
maximum' :: [V.Vector Char] -> V.Vector Char
maximum' = foldr1 (\x y -> if V.length x > V.length y then x else y)
-- for every character try to match the left with right side
foreveryvchars :: Int -> V.Vector Char -> [V.Vector Char]
foreveryvchars center vchars =
case vchars V.!? center of
Nothing -> []
_ -> let (k, v) = match center 1 vchars
in v : foreveryvchars
((\x -> if x == 0 then center + 1 else center + x) k) vchars
-- Takes the center and expand till it matches
-- returns the length and the palindrome it found around the center
match::Int -> Int -> V.Vector Char -> (Int, V.Vector Char)
match center radius vchars = let left = getleft center radius vchars
right = getright center radius vchars
in
case left /= Nothing && right /= Nothing && left == right of
True -> match center (radius + 1) vchars
_ -> (radius - 1, V.slice (center - (radius - 1) ) (1 + ((radius -1 ) * 2)) vchars)
getleft center radius vchars = vchars V.!? (center - radius)
getright center radius vchars = vchars V.!? (center + radius)
--
format :: String -> V.Vector Char
format = stov . convert
-- Insert pipe after each character
convert::String -> String
convert [] = '|':[]
convert (x:xs) = '|':x:convert xs | {
"domain": "codereview.stackexchange",
"id": 43037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, strings, haskell, palindrome",
"url": null
} |
algorithm, strings, haskell, palindrome
-- Convert String to Data.Vector
stov::String -> V.Vector Char
stov = V.fromList
main::IO()
main = print "hello world"
Answer: Write clearly.
Adding comments to your functions is good, but your first choice should be for the functions (and their arguments) to have self-explainatory names. Second, one hopes that the type signature will explain what the function does (sometimes adding type aliases can help with this). Only then, if there's still details that need explanation, write the comments in clear, complete sentences. Alternately, I think it's fine to just give a URL to a canonical source for the function.
Additionally, any time there's a part of the code you struggled with or had to scrap an attempt at, try to leave a comment explaining why you ended up with the solution you did.
match says it returns the "length", but the thing it actually returns is more like the "radius".
Also, be a little more careful with your whitespace. Also camel-case and pascal-case are conventional in Haskell, e.g. sToV.
Use -Wall.
It stands for "warnings: all". Use it to find places where GHC already knows you can improve your code. Unfortunately, it doesn't actually mean "all", there are other flags you can set to make GHC even pickier.
Sometimes less is more. Sometimes more is more.
If there's a particular parametric type you use a lot, give it an alias (or a newtype, depending on the situation) like type PaddedVec = V.Vector (Maybe Char).
On the other hand, if you have an alias (like stov) that you only use once, probably just inline it. If you want to be named, you can group it with its usage with a where clause.
Be sure you're using built-in functionality as well as you can.
maximum' is "just" maximumBy (compare `on` V.length).
You can use where together with guards to simplify the function you were calling match.
Ironically, in Haskell you rarely actually need to use a lambda. | {
"domain": "codereview.stackexchange",
"id": 43037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, strings, haskell, palindrome",
"url": null
} |
algorithm, strings, haskell, palindrome
Adding a bunch of '|' chars isn't great.
It's not clear that there's a better solution that doesn't involve any padding at all (I tried and failed), but choosing an arbitrary "dummy" character could fail (if the source text contains that character), and it locks your implementation to the one data-type (Char). Consider for example how you would adapt this algorithm to work on lists of integers? I would suggest instead mapping all the values to Justs, and padding with Nothing.
here's my version:
module Main where
import Data.Foldable (maximumBy)
import Data.Function (on)
import Data.Maybe (catMaybes)
import qualified Data.Vector as V
type PaddedVec a = V.Vector (Maybe a)
-- https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher.27s_algorithm
manacher :: (Eq a) => [a] -> [a]
manacher = catMaybes . V.toList . grabLongest . scan . V.fromList . padded
where grabLongest = maximumBy (compare `on` V.length)
padded [] = Nothing : [] -- Can't just use Data.List.intersperse; we need them wrapping outside too.
padded (x : xs) = Nothing : Just x : padded xs
scan = forEveryIndex 0 -- Starting at 1 could cause a fold1-exception if the input is empty
-- For every index, find the largest palindrome centered there, skipping some per Manacher's algorithm.
forEveryIndex :: (Eq a) => Int -> PaddedVec a -> [PaddedVec a]
forEveryIndex center vec = if center < (V.length vec)
then pal : forEveryIndex (center + (max 1 radius)) vec
else []
where (pal, radius) = findAround center 1 vec | {
"domain": "codereview.stackexchange",
"id": 43037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, strings, haskell, palindrome",
"url": null
} |
algorithm, strings, haskell, palindrome
-- Find the longest palindorme centered at an index (and its "radius").
findAround :: (Eq a) => Int -> Int -> PaddedVec a -> (PaddedVec a, Int)
findAround center radius vec
| Nothing <- left = (priorSlice, priorRadius) -- This is an "outer" Nothing.
| Nothing <- right = (priorSlice, priorRadius)
| left /= right = (priorSlice, priorRadius)
| otherwise = findAround center (radius + 1) vec
where left = vec V.!? (center - radius) -- left :: Maybe (Maybe a)
right = vec V.!? (center + radius) -- use `forall a.` above to make these explicit.
priorRadius = radius - 1
priorSlice = V.slice (center - priorRadius) (1 + (priorRadius * 2)) vec
main :: IO()
main = do print $ manacher "hello world"
print $ manacher "abacaba"
print $ manacher "helloll world"
print $ manacher "helloll wowrld"
print $ manacher ""
print $ manacher "x" | {
"domain": "codereview.stackexchange",
"id": 43037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, strings, haskell, palindrome",
"url": null
} |
c++, performance
Title: Optimizing performance of string comparison function (particularly interested in redundancies)
Question: I've been working on the below function which compares two input strings and returns a similarity score. I've managed to tweak it down to a level of performance I'm pretty happy with, but I'm relatively new to C++ and wondering how I might push it further! In particular if there's any way to cut down on redundancies.
My code works in the following manner:
Decomposes each string into a vector of bigrams (e.g. "John Smith" becomes Jo oh hn n S Sm mi it th) and creates a union of elements from both.
For each element in the union, count the frequency at which it occurs in each of the constituent vectors and store the frequency values in a new pair of vectors.
Return the score as the dot product of both frequency vectors over the geometric mean of their inner products.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
double similarity(std::string string1, std::string string2) {
std::vector<std::pair<char, char>> s1, s2, sunion;
size_t l1 = string1.size() - 1;
s1.reserve(l1);
for (int i = 0; i < l1; i += 1){
s1.push_back(std::pair<char, char>(string1.at(i), string1.at(i+1)));
}
size_t l2 = string2.size() - 1;
sunion.reserve(l1+l2);
sunion = s1;
s2.reserve(l2);
for (int i = 0; i < l2; i += 1){
s2.push_back(std::pair<char, char>(string2.at(i), string2.at(i+1)));
sunion.push_back(std::pair<char, char>(string2.at(i), string2.at(i+1)));
}
std::sort(sunion.begin(), sunion.end());
sunion.erase(std::unique(sunion.begin(), sunion.end()), sunion.end()); | {
"domain": "codereview.stackexchange",
"id": 43038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
size_t lu = sunion.size();
std::vector<int> f1, f2;
f1.reserve(lu);
f2.reserve(lu);
for (int i = 0; i < lu; i += 1){
std::pair<char, char> bi = sunion[i];
f1.push_back(std::count(s1.begin(), s1.end(), bi));
f2.push_back(std::count(s2.begin(), s2.end(), bi));
}
double jacc = std::inner_product(f1.begin(), f1.end(), f2.begin(), 0.0)
/ std::sqrt(std::inner_product(f1.begin(), f1.end(), f1.begin(), 0.0)
* std::inner_product(f2.begin(), f2.end(), f2.begin(), 0.0));
return jacc;
} | {
"domain": "codereview.stackexchange",
"id": 43038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
Answer: Most of the time is spent in std::count and the std::sort + std::unique, in that order.
This algorithm to compute a histogram (which is what the loop with std::counts in it is doing) is not efficient, it requires S passes over the vector of bigrams where S is the number of unique bigrams, but a histogram like that could be computed in one pass, and without requiring to compute the unique bigrams first. Switching to a different algorithm takes out both of the big ticket items together.
An alternative histogram algorithm that makes only one pass is, at a high level, "for each item, increment histogram[item]". The items here are bigrams, and they could come directly from the input string, saving on the cost of explicitly creating vectors of bigrams, which became a significant time waster when the histogram algorithm was changed.
The histograms could be std::array<uint32_t, 256 * 256> (which will cost a lot of unused size for typical string) or some kind of sparse map (eg unordered map) indexed by a pair if you prefer. For the array, a pair of chars needs to be turned into an index, which is no big deal but be aware that char is often signed and the index shouldn't be negative. They could be converted to unsigned char, or masked with & 0xFF. The array would contain many zeroes, which wouldn't be good to pass to the inner_product functions. That wouldn't be wrong, but it force those functions to waste time on multiplying lots of zeroes together. To avoid that, the same vectors f1 and f2 could be created. I changed them to std::vector<int64_t> because I had some overflow problems with the giant strings that I used for benchmarking.
For example:
std::array<uint32_t, 256 * 256> c1 = {};
std::array<uint32_t, 256 * 256> c2 = {};
for (size_t i = 0; i < l1; i++)
{
c1[(string1[i] & 0xFF) + (string1[i + 1] & 0xFF) * 256]++;
}
for (size_t i = 0; i < l2; i++)
{
c2[(string2[i] & 0xFF) + (string2[i + 1] & 0xFF) * 256]++;
} | {
"domain": "codereview.stackexchange",
"id": 43038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
std::vector<int64_t> f1, f2;
for (size_t i = 0; i < 256 * 256; i++)
{
if (c1[i] | c2[i])
{
f1.push_back(c1[i]);
f2.push_back(c2[i]);
}
}
On my PC, with the big 100000000-character strings I generated, that took the time taken from about 17.5 second down to 0.15 seconds, a decent improvement. Of course, the improvement won't be so big in all cases, in fact for small strings this approach may be worse due to the need to iterate through 65536-element arrays.
Pushing even further
Computing histograms quickly is difficult, and what I just showed is just the most basic algorithm that isn't slow, it's not the state of the art of computing histograms. The focus is usually on counting bytes, so other results do not necessarily translate to this problem with pairs of characters, but this should still suffer from the issue that plagues the basic histogram algorithm: incrementing the same element of the histogram (which can happen by chance) in quick succession does not pipeline well (and may result in memory dependence mis-speculation and rollback) because the increments depend on each other. Powturbo Histogram uses some techniques to avoid that problem, as do unusual new techniques that abuse VGF2P8AFFINEQB. There is not a lot of information in that twitter post, but I invented a histogram calculation algorithm that uses VGF2P8AFFINEQB as well, and it wouldn't work in this case: it's good for 7-bit ASCII, still decent for bytes, but anything larger than that would be bad, a pair of chars is far out of reach. Some of the techniques used in Powturbo Histogram may be worth trying. | {
"domain": "codereview.stackexchange",
"id": 43038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c, comparative-review, error-handling, io, posix
Title: Retry read/write until all bytes are transferred or error occurs
Question: Currently I have a wrapper function for the read/write system calls, the purpose of which is to eliminate partial transfer scenarios, by retrying until either all data is transferred or the system call fails in trying to do so.
Includes:
#include <errno.h>
#include <unistd.h>
Code:
int force(ssize_t(*const func)(int, void *, size_t), const int file, void *ptr, size_t size) {
for (ssize_t r;; ptr = (char *)ptr+r) {
if ((r = func(file, ptr, size)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
if (size -= r)
continue;
return 0;
}
}
This function would be used as such:
extern struct Conf conf;
int file = open("file", O_RDONLY);
if (force(read, file, &conf, sizeof(struct Conf)))
handle_error();
If write is passed, ptr may point to const data because write does not modify the data pointed to. But const casts are considered improper. Should I keep this wrapper, or should I write separate and mostly duplicated, but 'proper' wrappers?
int force_read(const int file, void *ptr, size_t size) {
for (ssize_t r;; ptr = (char *)ptr+r) {
if ((r = read(file, ptr, size)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
if (size -= r)
continue;
return 0;
}
}
int force_write(const int file, const void *ptr, size_t size) {
for (ssize_t r;; ptr = (const char *)ptr+r) {
if ((r = write(file, ptr, size)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
if (size -= r)
continue;
return 0;
}
} | {
"domain": "codereview.stackexchange",
"id": 43039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, comparative-review, error-handling, io, posix",
"url": null
} |
c, comparative-review, error-handling, io, posix
Answer: The second choice should be used for a separate reason, an asymmetry between read and write. In the event that read is called via the above function, and EOF is reached before the requested bytes are read, read will return 0, resulting in a forever loop. write does not need to handle a 0 return, unless size is 0, which can be handled by checking size before the first iteration instead after. The read wrapper may return a different value such as 1 signaling an end of file. Local variable names should also be lowercase.
int Read(const int file, void *ptr, size_t size) {
for (ssize_t r; size; size -= r, ptr = (char *)ptr+r) {
if ((r = read(file, ptr, size))) {
if (r == -1)
return -1;
continue;
}
return memset(ptr, 0, size), 1;
}
return 0;
}
int Write(const int file, const void *ptr, size_t size) {
for (ssize_t r; size; size -= r, ptr = (const char *)ptr+r) {
if ((r = write(file, ptr, size)) == -1)
return -1;
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, comparative-review, error-handling, io, posix",
"url": null
} |
python, python-3.x, strings, comparative-review, formatting
Title: Python function to output a string that is justified to the right
Question: I just solved this exercise from Think Python, 2nd edition:
Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
So, I've got these two options that have the same output. Which one is 'better' and why? And are there any good practices among programmers that I'm missing? I'm just starting out and I'd like to avoid bad habits.
Is it better to use .format() to add padding and justify a string or other functions like rjust(), ljust(), center() and zfill()?
1st option
def right_justify(s):
print('{:>70}'.format(s))
right_justify('allen')
2nd option
def right_justify(s):
print(s.rjust(70))
right_justify('allen')
Output(both):
allen
Answer: Cheating
Both functions look like you've failed to do the assignment. The problem description talks about the len(...) function, and how it behaves with strings. You are not using it to write the function. Ok, maybe it doesn't explicitly say you have to use it, but it seems implied! Instead, you've scoured the standard library and determined two different functions which do the work for you. I think the point of the question is re-inventing the wheel ... writing a function like .rjust(w) yourself!
Which option is better?
Consider what the functions do: | {
"domain": "codereview.stackexchange",
"id": 43040,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, strings, comparative-review, formatting",
"url": null
} |
python, python-3.x, strings, comparative-review, formatting
With '{:>70}'.format(s), the format function has to scan the '{:>70}' string for {}, break it up into field and format codes, take arguments from the .format(...) parameter and/or keyword list, and interpolate those into the string at the appropriate places, applying the required formatting. In short, it powerful, but computationally expensive.
If s is not a string, the function will still work, implicitly formatting the result with str(s), which is one of the advantages of the additional power in this approach.
With s.rjust(70), it is taking a string and padding it on the left with (by default) spaces. Simple and fast.
If s is not a string (or another class which defines .rjust()), it will raise an exception.
So, ...
the first is "better", in terms of the Robustness Principle in the sense that it works with more arguments.
the second is "better" in terms of efficiency
Additional possibilities
You can cheat and write the function even shorter, using f-strings:
def right_justify(s: str) -> None:
"""
Print out the given argument right-justified to 70 characters,
followed by a newline.
Note: If the string is longer than 70 characters, it is printed
without modification.
"""
print(f'{s:>70}')
Well, it was shorter until I added argument type-hints, a return value type-hint, and a """docstring""" ... which are all "best practices".
But, the assignment goal is still not satisfied. Without these magical format functions or .rjust methods, can you write a function which will accomplish the goal yourself? | {
"domain": "codereview.stackexchange",
"id": 43040,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, strings, comparative-review, formatting",
"url": null
} |
c++, performance, image, opencv
Title: C++ program that replaces given color in an image using OpenCV
Question: I have created a C++ program that changes the color of a pixel to another color. But the main feature is that it not only changes 100% accurate colors; instead it matches two colors by using a method in which it takes the difference between the two colors' BGR values and then, the differences are squared to compare it with the square of tolerance rate.
I'm quite new to OpenCV, so if I'm using any sort of bad practices or if there's a more efficient way to do that - or any suggestion - please let me know.
I'm using GCC v11.2.0 on Arch Linux and OpenCV v4.5.5.
Here's the formula:
$$
\left( \Delta red^{2} \right) + \left( \Delta green^{2} \right) +\left( \Delta blue^{2} \right) \leqslant tolerance^{2}
$$
$$
tolerance \propto \Delta pixels
$$
Here's the code:
#include <iostream>
#include <opencv2/opencv.hpp>
static bool Color_Comparison(const cv::Vec3b &c1, const cv::Vec3b &c2, const unsigned int &tolerance)
{
unsigned int blue = (c1[0] - c2[0]);
unsigned int green = (c1[1] - c2[1]);
unsigned int red = (c1[2] - c2[2]);
return (((red * red) + (green * green) + (blue * blue)) <= (tolerance * tolerance));
}
static cv::String change_filename(const cv::String &fl)
{
std::size_t ind = fl.find_last_of('.');
if (ind == cv::String::npos)
return fl;
cv::String name;
name.append(fl.begin(), fl.begin() + ind);
name.append("_replace");
name.append(fl.begin() + ind, fl.end());
return name;
} | {
"domain": "codereview.stackexchange",
"id": 43041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, image, opencv",
"url": null
} |
c++, performance, image, opencv
int main(int argc, char const **argv)
{
using namespace cv;
if (argc == 1)
{
std::cerr << "bad format: format is <INPUT_FILENAME>" << std::endl;
return EXIT_FAILURE;
}
Mat img = imread(String(argv[1]));
if (img.empty() == false)
{
Vec3b lightsaber = Vec3b(192, 196, 191), lightsaber_replace = Vec3b(10, 10, 255);
unsigned int tolerance = 30;
std::size_t delta_pixel = 0;
for (int x = 0; x < img.rows; x++)
{
for (int y = 0; y < img.cols; y++)
{
Vec3b &temp_clr = img.at<Vec3b>(x, y);
if (Color_Comparison(temp_clr, lightsaber, tolerance) == true)
{
temp_clr = lightsaber_replace;
delta_pixel++;
}
}
}
String save_name = change_filename(String(argv[1]));
if (imwrite(save_name, img) == true)
{
std::cout << "number of pixels modified: " << delta_pixel << "\n";
std::cout << "File saved at: " << save_name << std::endl;
return EXIT_SUCCESS;
}
else
{
std::cerr << "file not saved" << std::endl;
return EXIT_FAILURE;
}
}
else
{
std::cerr << "image not found or could not be opened: " << argv[1] << std::endl;
return -1;
}
return 0;
}
Here's some results (on a particular image):
Before:
After:
I have compiled the above program using this command:
g++ -O3 -Ofast -Og -s -Os $(pkg-config --cflags --libs opencv4) main.cc -o main
And the text output on the terminal was:
number of pixels modified: 3260
File saved at: ./luke_replace.jpg
Benchmark using time ./main ./luke.jpg in zsh (on Intel i5-7200U):
0.25s user 0.02s system 99% cpu 0.270 total
image source | {
"domain": "codereview.stackexchange",
"id": 43041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, image, opencv",
"url": null
} |
c++, performance, image, opencv
image source
Answer: Be consistent
You have many inconsistencies in your code. For example, you use EXIT_SUCCESS and EXIT_FAILURE in some places, but you return -1 in another case. Use EXIT_FAILURE in that case (which by the way is 1, not -1).
You use std::endl in some places, "\n" in others. I recommend you use the latter, as it is equivalent except the former also flushes the output, which is usually not necessary and negatively impacts performance.
Simplify expressions
A statement like if ((something) == true) can be written simpler as if (something).
Some of your expressions have a lot of unnecessary parentheses, consider removing them as an abundance of parentheses usually reduces legibility of your code. For example:
unsigned int blue = (c1[0] - c2[0]);
...
return (((red * red) + (green * green) + (blue * blue)) <= (tolerance * tolerance));
Can be rewritten as:
unsigned int blue = c1[0] - c2[0];
...
return red * red + green * green + blue * blue <= tolerance * tolerance;
You can also avoid explicit casts or mentioning of types in some cases. For example, you can write:
Mat img = imread(argv[1]);
...
Vec3b lightsaber = {192, 196, 191}; | {
"domain": "codereview.stackexchange",
"id": 43041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, image, opencv",
"url": null
} |
c++, performance, image, opencv
You might even consider using auto in some places to further avoid having to explicitly write type names.
Also try to avoid unnecessary nesting of code inside if-statements.
Let the user specify the output filename
Instead of trying to derive the filename for the output from the filename of the input, consider letting the user specify both filenames. That simplifies your code a lot, and also avoids some peculiar behavior. If the input filename doesn't contain a dot for example, your code would overwrite the input instead of creating a new file, without any warning.
Make better use of library functions
There are two ways to further reduce the amount of code that needs to be written. The first is by using the fact that cv::Mat provides begin() and end()-like functions, so you can use STL algorithms like std::transform() to iterate over all the pixels. Second, OpenCV itself has a lot of functionality, including the ability to calculate the \$L^2\$-squared norm of the distance between two vectors.
Example rewrite
Here is what the code could look like:
#include <iostream>
#include <opencv2/opencv.hpp>
int main(int argc, char const **argv)
{
using namespace cv;
if (argc != 3) {
std::cerr << "Wrong number of arguments: format is <INPUT_FILENAME> <OUTPUT_FILENAME\n";
return EXIT_FAILURE;
}
Mat img = imread(argv[1]);
if (img.empty()) {
std::cerr << "Error reading " << argv[1] << '\n';
return EXIT_FAILURE;
}
const Vec3b lightsaber = {192, 196, 191};
const Vec3b lightsaber_replace = {10, 10, 255};
const unsigned int tolerance = 30;
std::size_t delta_pixel = 0;
std::transform(img.begin<Vec3b>(), img.end<Vec3b>(), img.begin<Vec3b>(), [&](auto& pixel){
if (norm(pixel, lightsaber, NORM_L2SQR) < tolerance * tolerance) {
delta_pixel++;
return lightsaber_replace;
} else {
return pixel;
}
}); | {
"domain": "codereview.stackexchange",
"id": 43041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, image, opencv",
"url": null
} |
c++, performance, image, opencv
if (!imwrite(argv[2], img)) {
std::cerr << "Error writing " << argv[2] << '\n';
return EXIT_FAILURE;
}
std::err << "Number of pixels modified: " << delta_pixel << '\n';
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 43041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, image, opencv",
"url": null
} |
html, css, animation, sass
Title: Prey Throbber using CSS Animation
Question: I'm migrating to web development and wanted to learn CSS animations better. I was playing Prey last night and realized the "throbber" on the elevator screen would be interesting to reimplement. For anyone not familar with the game, it can be seen briefly here (although that's not required for the review).
Here's the end result as a snippet:
.throbber-wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
justify-items: center;
align-items: center;
background-color: #2eb9e8;
width: 10em;
height: 10em;
}
.throbber-wrapper > div {
display: inline-block;
background-color: #93e2ff;
// For the sake of the animation so it starts without full boxes waiting to be animated.
width: 0;
height: 0;
opacity: 0;
animation: cellShrink 1000ms infinite;
}
@keyframes cellShrink {
0% {
width: 100%;
height: 100%;
opacity: 100%;
}
100% {
width: 10%;
height: 10%;
opacity: 10%;
}
} | {
"domain": "codereview.stackexchange",
"id": 43042,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, animation, sass",
"url": null
} |
html, css, animation, sass
100% {
width: 10%;
height: 10%;
opacity: 10%;
}
}
.throbber-wrapper .b2 {
animation-delay: 62.5ms;
}
.throbber-wrapper .b3 {
animation-delay: 125ms;
}
.throbber-wrapper .b4 {
animation-delay: 187.5ms;
}
.throbber-wrapper .b8 {
animation-delay: 250ms;
}
.throbber-wrapper .b7 {
animation-delay: 312.5ms;
}
.throbber-wrapper .b6 {
animation-delay: 375ms;
}
.throbber-wrapper .b5 {
animation-delay: 437.5ms;
}
.throbber-wrapper .b9 {
animation-delay: 500ms;
}
.throbber-wrapper .b10 {
animation-delay: 562.5ms;
}
.throbber-wrapper .b11 {
animation-delay: 625ms;
}
.throbber-wrapper .b12 {
animation-delay: 687.5ms;
}
.throbber-wrapper .b16 {
animation-delay: 750ms;
}
.throbber-wrapper .b15 {
animation-delay: 812.5ms;
}
.throbber-wrapper .b14 {
animation-delay: 875ms;
}
.throbber-wrapper .b13 {
animation-delay: 937.5ms;
}
<div class="throbber-wrapper">
<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
<div class="b4"></div>
<div class="b5"></div>
<div class="b6"></div>
<div class="b7"></div>
<div class="b8"></div>
<div class="b9"></div>
<div class="b10"></div>
<div class="b11"></div>
<div class="b12"></div>
<div class="b13"></div>
<div class="b14"></div>
<div class="b15"></div>
<div class="b16"></div>
</div>
The color isn't perfect, but that's not my main concern. The main challenge when writing this was getting the timing of the squares right and written in a sane way (I think I only achieved the first goal there). A full cycle is one second, divided by 16 cells gives 62.5ms, so I decided to delay the animation of each cell by 62.5ms longer than the previous cell. That unfortunately meant manually IDing each cell, and manually writing delays for each cell. I was able to reduce the duplication a bit using SCSS nesting, but it's still atrocious.
What I'd like help with: | {
"domain": "codereview.stackexchange",
"id": 43042,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, animation, sass",
"url": null
} |
html, css, animation, sass
This code has a disgusting amount of duplication. I would like to know about any tricks that can neaten it up.
Any other CSS, SCSS, or even HTML tricks that can help make this code cleaner.
HTML (this is a component, not a full page):
<div class="throbber-wrapper">
<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
<div class="b4"></div>
<div class="b5"></div>
<div class="b6"></div>
<div class="b7"></div>
<div class="b8"></div>
<div class="b9"></div>
<div class="b10"></div>
<div class="b11"></div>
<div class="b12"></div>
<div class="b13"></div>
<div class="b14"></div>
<div class="b15"></div>
<div class="b16"></div>
</div>
SCSS:
.throbber-wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
justify-items: center;
align-items: center;
background-color: #2eb9e8;
width: 10em;
height: 10em;
}
.throbber-wrapper > div {
display: inline-block;
background-color: #93e2ff;
// For the sake of the animation so it starts without full boxes waiting to be animated.
width: 0;
height: 0;
opacity: 0;
animation: cellShrink 1000ms infinite;
}
@keyframes cellShrink {
0% {
width: 100%;
height: 100%;
opacity: 100%;
}
100% {
width: 10%;
height: 10%;
opacity: 10%;
}
}
.throbber-wrapper {
& .b2 {
animation-delay: 62.5ms;
}
& .b3 {
animation-delay: 125ms;
}
& .b4 {
animation-delay: 187.5ms;
}
& .b8 {
animation-delay: 250ms;
}
& .b7 {
animation-delay: 312.5ms;
}
& .b6 {
animation-delay: 375ms;
}
& .b5 {
animation-delay: 437.5ms;
}
& .b9 {
animation-delay: 500ms;
}
& .b10 {
animation-delay: 562.5ms;
}
& .b11 {
animation-delay: 625ms;
}
& .b12 {
animation-delay: 687.5ms;
}
& .b16 {
animation-delay: 750ms;
}
& .b15 {
animation-delay: 812.5ms;
}
& .b14 {
animation-delay: 875ms;
}
& .b13 {
animation-delay: 937.5ms;
}
} | {
"domain": "codereview.stackexchange",
"id": 43042,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, animation, sass",
"url": null
} |
html, css, animation, sass
& .b14 {
animation-delay: 875ms;
}
& .b13 {
animation-delay: 937.5ms;
}
}
Answer: Since you're using SCSS, why not use a SCSS @each loop with :nth-child() for setting the animation delay? It would also remove the need for classes on your child elements.
Store the animation order of elements in a list and loop over it. Use the index of your position in the loop for an :nth-child() selector, and the current value as the animation delay multiplier.
SCSS:
@keyframes cellShrink {
0% {
width: 100%;
height: 100%;
opacity: 100%;
}
100% {
width: 10%;
height: 10%;
opacity: 10%;
}
}
.throbber-wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
justify-items: center;
align-items: center;
background-color: #2eb9e8;
width: 10em;
height: 10em;
}
.throbber-wrapper div {
display: inline-block;
background-color: #93e2ff;
width: 0;
height: 0;
opacity: 0;
animation: cellShrink 1000ms infinite;
}
$order: 1, 2, 3, 4, 8, 7, 6, 5, 9, 10, 11, 12, 16, 15, 14, 13;
@each $block in $order {
$n: index($order, $block);
.throbber-wrapper div:nth-child(#{$n}) {
animation-delay: #{($block - 1) * 62.5}ms;
}
}
HTML:
<div class="throbber-wrapper">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div> | {
"domain": "codereview.stackexchange",
"id": 43042,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, animation, sass",
"url": null
} |
python, homework, django
Title: Python module to generate context for Django template using data requested from API
Question: As part of a university assignment, I have been tasked with populating and rendering a provided Django template with COVID-19-related quarantine data retrieved from a government API. To challenge myself, I wanted to write the code in a professional manner (to the best of my abilities): e.g., using features such as type hints, yield expressions, conditional expressions, chained assignments.
Now, I am looking to evaluate my success in that regard as well as aspects I can improve going forward.
The essence of the task is getting the relevant data from the API and manipulating it into the format expected by the template. An imposed constraint is that only data from the previous seven days are acceptable.
The *.py files have been formatted using Black and isort.
get_data.py: Module authored by me and seeking code review for.
import json
from datetime import date, timedelta
from typing import Iterator, List, Literal, Optional, Tuple
import requests
def _generate_valid_dates() -> Iterator[str]:
"""[yesterday, yesterday - 7)"""
YESTERDAY = date.today() - timedelta(days=1)
for i in range(7):
next_date = YESTERDAY - timedelta(days=i)
yield next_date.strftime("%d/%m/%Y")
def _call_api(
dataset: Literal["occupancy", "confines"], date: str
) -> Optional[List[dict]]:
"""
- Response JSON body parsed as a list of dict(s) or `None` if connection error.
- `date` expects `f"%d/%m/%Y"`.
"""
ENDPOINT = "https://api.data.gov.hk/v2/filter?q="
if dataset == "occupancy":
QUERY = {
"resource": "http://www.chp.gov.hk/files/misc/occupancy_of_quarantine_centres_eng.csv",
"section": 1,
"format": "json",
"sorts": [[8, "desc"]], # by units available
"filters": [[1, "eq", [date]]],
} | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
python, homework, django
elif dataset == "confines":
QUERY = {
"resource": "http://www.chp.gov.hk/files/misc/no_of_confines_by_types_in_quarantine_centres_eng.csv",
"section": 1,
"format": "json",
"filters": [[1, "eq", [date]]],
}
url = ENDPOINT + json.dumps(QUERY)
res = requests.get(url)
return res.json() if res.ok else None
def _sum_all_centres(occupancy_data: List[dict]) -> Tuple[int, int, int]:
"""`(units_in_use, units_available, persons_quarantined)`"""
units_in_use = units_available = persons_quarantined = 0
for centre in occupancy_data:
units_in_use += centre["Current unit in use"]
units_available += centre["Ready to be used (unit)"]
persons_quarantined += centre["Current person in use"]
return units_in_use, units_available, persons_quarantined
def generate_context() -> dict:
"""```
schema = {
"connected": bool,
"has_data": bool,
"data": {
"date": f"%d/%m/%Y",
"units_in_use": int,
"units_available": int,
"persons_quarantined": int,
"non_close_contacts": int,
"count_consistent": bool,
},
"centres": [
{"name": str, "units": int},
{"name": str, "units": int},
{"name": str, "units": int},
],
}
```"""
ctx = {}
has_data = False
dates = _generate_valid_dates()
while not has_data:
try:
date_ = next(dates)
except StopIteration:
break # all valid dates checked
occupancy_data = _call_api("occupancy", date_)
confines_data = _call_api("confines", date_)
if occupancy_data is None or confines_data is None:
ctx["connected"] = False
break # connection error
ctx["connected"] = True | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
python, homework, django
ctx["connected"] = True
try:
(units_in_use, units_available, persons_quarantined) = _sum_all_centres(
occupancy_data
)
confines_data = confines_data[0] # singleton for one date
count_consistent = (
confines_data["Current number of close contacts of confirmed cases"]
+ confines_data["Current number of non-close contacts"]
== persons_quarantined
)
centres = [
{
"name": centre["Quarantine centres"],
"units": centre["Ready to be used (unit)"],
}
for centre in occupancy_data[:3]
]
except (IndexError, KeyError):
# IndexError: confines_data is empty
# KeyError: some missing field in a dataset
continue # proceed to next date
has_data = ctx["has_data"] = True
ctx["data"] = {
"date": date_,
"units_in_use": units_in_use,
"units_available": units_available,
"persons_quarantined": persons_quarantined,
"non_close_contacts": confines_data["Current number of non-close contacts"],
"count_consistent": count_consistent,
}
ctx["centres"] = centres
return ctx
dashboard3.html: Template provided with the assignment. | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
python, homework, django
dashboard3.html: Template provided with the assignment.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Quarantine Centres Dashboard</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<style>
body {
font-family: sans-serif; /* personal preference */
display: flex;
flex-flow: column nowrap;
justify-content: flex-start;
align-items: center;
}
h1 {
font-size: 1.5em;
}
#main-content {
width: 100%;
max-width: 40em;
}
#main-content > div {
padding: 1em;
margin-bottom: 0.5em;
background-color: rgb(150, 200, 200);
box-shadow: 0.1em 0.1em 0.2em rgb(100, 100, 100);
font-size: 1.2em;
}
#main-content div.error-message {
background-color: rgb(200, 180, 160);
}
span.stat {
font-weight: bold;
font-size: 1.1em;
}
.material-icons {
display: inline-flex;
vertical-align: text-bottom;
}
</style>
</head>
<body>
<h1>Quarantine Centres Dashboard</h1>
<div id="main-content">
{% if connected %}
{% if has_data %}
<div>
<span class="material-icons">calendar_today</span>
Quarantine data for
<span class="stat">{{ data.date }}</span>
</div>
<div>
<span class="material-icons" title="in use">outlined_flag</span>
Quarantine units in use:
<span class="stat">{{ data.units_in_use }}</span>
<br>
<span class="material-icons" title="available">checklist_rtl</span>
Quarantine units available:
<span class="stat">{{ data.units_available }}</span>
</div> | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
python, homework, django
<div><span class="material-icons">insights</span>
Highest availability is at:
<ul class="centres">
{% for centre in centres %}
<li class="centre">
<span class="name">{{ centre.name }}</span>:
<span class="stat">{{ centre.units }} unit{{ centre.units | pluralize }}</span>
</li>
{% endfor %}
</ul>
</div>
<div>
<span class="material-icons">people</span>
Number of persons quarantined:
<span class="stat">{{ data.persons_quarantined }}</span>
<br>
<span class="material-icons" title="non-close contacts">safety_divider</span>
Non-close contacts:
<span class="stat">{{ data.non_close_contacts }}</span>
</div>
{% if data.count_consistent %}
<div>
<span class="material-icons">check</span>
Count is consistent with quarantine records
</div>
{% else %}
<div class="error-message">
<span class="material-icons">warning</span>
Warning: Count is not consistent with quarantine records
</div>
{% endif %}
{# no data available #}
{% else %}
<div class="error-message">
<span class="material-icons">error</span>
Sorry, no data found within the past 7 days.
</div>
{# end-if has data #}
{% endif %}
{# not connected #}
{% else %}
<div class="error-message">
<span class="material-icons">error</span>
Sorry, something went wrong. Please try again later.
</div>
{# end-if connected #}
{% endif %}
</div>
</body>
</html>
views.py: Uses the generate_context() function from get_data.py in rendering dashboard3.html.
from django.shortcuts import render | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
python, homework, django
from django.shortcuts import render
from .libs import get_data
def dashboard(request):
ctx = get_data.generate_context()
return render(request, "qtine_dash/dashboard3.html", ctx)
Answer: <rant>
The *.py files have been formatted using Black
Learn from it, yes. Use it long-term... my opinion is no. There's a great quote from the official PEP8 definition:
A Foolish Consistency is the Hobgoblin of Little Minds
The authors of PEP8 intended for it to be a style guide and not syntactically or zealously enforced. Sometimes the computer is wrong. I've worked in a couple of professional settings where black was mandated, and I hated the shackles. Part of, as you describe,
writing the code in a professional manner
is understanding the rules and then understanding when they should be broken. Other linters - flake8, etc. - are more configurable and nuanced, and less nuclear.
</rant>
Change _generate_valid_dates so that it does not strftime. Internal data generation and formatting should be separate, and formatting should only occur at the edges of your program. Likewise, _call_api should accept a date object and not a string.
For your QUERY, factor out the common elements to a pre-initialisation statement before your if.
Do not string-concatenate your url. It's bizarre to JSON-serialize to query parameters. It's typical to see either standard RFC1738/3986-encoded query parameters as passed in a GET, or JSON as passed in a POST. For the former, pass your QUERY dict to the params kwarg of get. This assumes that you control the URL format for www.chp.gov.hk which you might not.
Don't None-fail, as in
return res.json() if res.ok else None
Instead, response.raise_for_status and handle the exception at the outer level.
Since this is a singleton:
confines_data = _call_api("confines", date_)
confines_data = confines_data[0] # singleton for one date
you can just tuple-unpack:
confines_data, = _call_api("confines", date_) | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
python, homework, django
you can just tuple-unpack:
confines_data, = _call_api("confines", date_)
Declare a language (probably en) in your HTML.
Try to separate your styles out to a separate .css file.
It's very common these days to see non-terminated HTML5 tags like <br>. I still prefer to write <br/> because, for people who are used to visually parsing XML, this is more consistent. | {
"domain": "codereview.stackexchange",
"id": 43043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, homework, django",
"url": null
} |
c++, algorithm, pathfinding, priority-queue
Title: Priority Queue for D* Lite
Question: So, I needed a priority queue for D* lite and I wanted to know whether this is an acceptable implementation or not.
#ifndef BCC940D8_CEDF_4B76_8CE4_D8C9A4D1A787
#define BCC940D8_CEDF_4B76_8CE4_D8C9A4D1A787
#include <queue>
#include <vector>
#include <list>
#include <functional>
#include "Node.hpp"
#include "Key.hpp"
namespace Pathfinding::Datastructures
{
class NodeComperator
{
public:
bool operator() (const Node * lhs, const Node * rhs)
{
return lhs->key > rhs->key;
}
};
class PriorityQueue final : public std::priority_queue<Node *, std::vector<Node *>, NodeComperator>
{
public:
void remove(Node *node)
{
auto it = std::find_if(this->c.begin(), this->c.end(),
[&node](const Node * element)
{
return *element == *node;
});
this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp);
}
void insert(Node *node)
{
this->push(node);
}
void reset()
{
c.clear();
std::make_heap(this->c.begin(), this->c.end(), this->comp);
}
Key topKey() const
{
if (this->empty())
{
return Key();
}
return this->top()->key;
}
Node *popD()
{
auto topNode = this->top();
pop();
return topNode;
}
bool contains(const Node *node)
{
return std::find_if(this->c.begin(), this->c.end(),
[&node](const Node* input)
{
return *input == *node;
}) != this->c.end();
}
private:
using std::priority_queue<Node *, std::vector<Node *>, NodeComperator>::pop;
};
} | {
"domain": "codereview.stackexchange",
"id": 43044,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, priority-queue",
"url": null
} |
c++, algorithm, pathfinding, priority-queue
#endif /* BCC940D8_CEDF_4B76_8CE4_D8C9A4D1A787 */
Nodes are sorted by key which is a tuple with two floats. "Keys are compared according to a lexicographic-ordering".
Answer: Unnecessary use of this->
It is almost never necessary to use this-> in C++. I recommend you remove all occurrences of it in your code.
Unnecessary call to std::make_heap()
It is not necessary to call std::make_heap() after clearing the underlying container.
Naming things
I would rename remove() to erase(), as the remove() function in STL does mean something different than erasing.
insert() is just equivalent to push(). I would recommend removing insert(), and just let the caller use push() instead, which is publicly inherited.
popD() looks weird. I would just rename this to pop(); it will give you the functionality you want, and in a way it's still compatible with the STL's pop().
Missing const
contains() does not modify the queue, so it should be made const. Furthermore, remove() doesn't modify node, so you should make that parameter a const pointer.
Use std::find() to find a specific node
You can use std::find to find a specific value without needing a lambda:
bool contains(const Node *node) const {
return std::find(c.begin(), c.end(), node) != c.end();
}
Simplifications possible using C++20
If you can use C++20, you can simplify your code somewhat. There are std::ranges versions of some of the algorithms, and you can use std::erase() to remove an item from the underlying vector by value. So for example, you could write:
void erase(const Node *node) {
std::erase(c, node);
std::ranges::make_heap(c);
}
Unfortunately there is no std::contains() in C++20, and it seems there won't even be any in C++23. | {
"domain": "codereview.stackexchange",
"id": 43044,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, pathfinding, priority-queue",
"url": null
} |
javascript, node.js, animation, network-file-transfer
Title: Trying to follow Single Responsibility Principle with download and show progress
Question: Let's get right into it, I have a function downloadFile(url, path); Downloads file and saves it.
donwloadFile.js
module.exports = function donwloadFile(url, path) {
return new Promise(res => {
return axios({ url, method: 'GET', responseType: 'stream', })
.then(({ data }) => {
const file = createWriteStream(path);
data.pipe(file);
file.on('finish', () => {
file.close();
res({ ok: true });
});
})
.catch(err => res({ ok: false, err }))
});
}
Just there it already seems to violate SRP which i don't know what i can do about since the two functionality are part of each other, downloading and saving.
Ignoring that however, it's perfectly fine, it gets the job done and tells you what's going on.
to download a file you provide the url and the path where to save, simple.
However my main issue is that i want to add a progressBar (using progress library) to give some feedback and in order to do that i need to have access to data parameter of axios and the code becomes as follows.
donwloadFile.js
module.exports = function donwloadFile(url, path) {
return new Promise(res => {
return axios({ url, method: 'GET', responseType: 'stream', })
.then(({ data }) => {
const file = createWriteStream(path);
data.pipe(file);
const progressBar = new ProgressBar('[:bar] :percent | Time left: :etas.', {
complete: '=',
incomplete: ' ',
renderThrottle: 1,
total: parseInt(data.headers['content-length'])
})
data.on('data', (chunk) => {
progressBar.tick(chunk.length);
}) | {
"domain": "codereview.stackexchange",
"id": 43045,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, animation, network-file-transfer",
"url": null
} |
javascript, node.js, animation, network-file-transfer
file.on('finish', () => {
file.close();
res({ ok: true });
});
})
.catch(err => res({ ok: false, err }))
});
}
and suddenly the download function isn't just downloading it's also spitting out a progressBar which is not ideal.
I had the idea of passing a callback which would be called inside data.on('data', callback)
But then we're doing the same thing again, the download function should only take two arguments, having a third one as callback makes it look like it's doing more than it says.
So my question is:
How can i keep the download function only downloads and also have the ability to show a progress bar ?
Also I'd welcome any healthy criticism, writing pretty and maintainable code has always been the bane of my existence, and i just got fed up and decided to learn some concepts. | {
"domain": "codereview.stackexchange",
"id": 43045,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, animation, network-file-transfer",
"url": null
} |
javascript, node.js, animation, network-file-transfer
Answer: Is SRP being violated?
I think the first version of donwloadFile.js is fine and obeys SRP. That said, I believe a cleaner solution is to refactor this method to return a file and then create a function that saves the file. I believe this is what @pacmaninbw suggested in his or her answer.
When to refactor?
If you find that you are copying the same lines to save a file in other parts of the code, you found yourself a refactoring opportunity. Now the question is how would you refactor. The way I have handled this in the past, and to stay true to Open/Close Principle (OCP), is to include a new version of the same method with this refactoring in place. In other words, I expand the functionality, instead of modifying it. That way, legacy code can continue to call the old downloadFile.js, while new code calls the new version. In fact, sometimes I would modify the legacy function where the legacy function will call the new function. To me, it is OK for legacy functions to depend on new functions (obviously, not the other way around).
What advantage does this approach have?
I can think of two:
You won't have to worry about failing test cases due to unforeseen side effects of this modification
If you ever retire the legacy code, you don't have to worry about dependencies (new functions don't depend on old functions). | {
"domain": "codereview.stackexchange",
"id": 43045,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, animation, network-file-transfer",
"url": null
} |
javascript, node.js, animation, network-file-transfer
So, in my humble opinion, even if downloadFile.js violates SRP, the best way to handle it might be leaving it alone and simply expand your functionality by adding a new version (or variant). That said, if the code is not in production yet, feel free to make all the modifications needed to have the cleanest implementation you could possibly get before your targeted release date.
Disclaimer: If you have core functions that you are OK with being part of the application forever, it is then OK for new functions to depend on these (core) old functions. SOLID Principles are recommendations, not gospel. It's like we striving for perfection. We will never get there no matter how hard we try. BUT, that should not stop up in trying our best to achieve it. In the end, the important thing is for us to be the best version of ourselves than we can be. Likewise, our code will NEVER be perfect. But, that should not stop us in developing the best applications we can. There are going to be situations when we would have to modify old code. We should be OK with that as long as it is not a common occurrence. The important thing is that, when opportunity present itself, we do a better job than the previous time to ensure these "violations" occur less often. | {
"domain": "codereview.stackexchange",
"id": 43045,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js, animation, network-file-transfer",
"url": null
} |
linux, assembly, base64, byte
Title: Base64 encoder in Assembly x86-64 Linux language
Question: We were asked to create a Base64 encoder for Assembly x86-64 on Linux. Was wondering how my code below could be improved, be it notation or anything else. We only had Assembly for 3 months so I'm not really that used to any kind of particular notation. That's a reason why I'm asking. Thanks for your help !
SECTION .data
Base64Table: db "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
SECTION .bss
byteStorage: resb 30000
bytesToReadAtOnce: equ 30000
b64EncStor: resb 40000
b64EncStorLen: equ $ - b64EncStor
SECTION .text
global _start
_start:
;sys read put everything from the file into the buffer "byteStorage"
mov rax, 0
mov rdi, 0
mov rsi, byteStorage
mov rdx, bytesToReadAtOnce
syscall
xor r11, r11 ; syscall strangely changes r11
xor r12, r12 ;r12 will keep track of index in byteStorage array
mov r13, 0 ;r13 will keep track of index in b64EncStor array
.encodingInProgress:
cmp rax, 0
je .weHaveFinished ;if no bits remaining, and no extra one or two
;bytes, we simply jump to the end
dec rax
inc r12
mov r8b, [byteStorage + r12 -1] ; put each input char in a register each
mov r11b, r8b
shr r11b, 2
and r11b, 0x3F
mov r11b, [Base64Table + r11]
mov [b64EncStor + r13], r11b ; our first char is now encoded
inc r13
cmp rax, 0 ;if rax = 0, rax was one before above decrementation, so we jump
je .oneExtraByte ;to .oneExtraByte
;char two
dec rax
inc r12
mov r9b, [byteStorage + r12-1] ; put each input char in a register each
and r8b, 0x3
shl r8b,4
mov r11b, r9b
shr r11b, 4
and r11b, 0xF
add r8b, r11b
mov r8b, [Base64Table + r8]
mov [b64EncStor+r13], r8b ; second char now encoded
inc r13
cmp rax, 0 ;rax was two before being decremented twice above, so we
je .twoExtraBytes ;jump to .twoExtraBytes
;char three
dec rax
inc r12 | {
"domain": "codereview.stackexchange",
"id": 43046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, assembly, base64, byte",
"url": null
} |
linux, assembly, base64, byte
;char three
dec rax
inc r12
mov r10b, [byteStorage + r12-1] ;put each input char in a register each
and r9b, 0xF
shl r9b, 2
mov r8b, r10b
shr r8b, 6
and r8b, 0x3
add r9b, r8b
mov r9b, [Base64Table + r9]
mov [b64EncStor+r13], r9b ; third char now encoded
inc r13
;char four
and r10b, 0x3F
mov r10b, [Base64Table + r10]
mov [b64EncStor+r13], r10b ; fourth char now encoded
inc r13
jmp .encodingInProgress
;--------
.oneExtraByte: ;so we need four (and not two !) bits more to reach 12
shl r8b, 4
and r8b, 0x3F ;only keep six bits from left, the two most right are zero
mov r8b, [Base64Table + r8]
mov [b64EncStor + r13], r8b
inc r13
mov r8b, "=" ;add two extra equal signs
mov [b64EncStor + r13], r8b
inc r13
mov [b64EncStor + r13], r8b
inc r13
jmp .weHaveFinished
;------
.twoExtraBytes: ;so we need two (and not four !) bits more to reach 18
;inc r12
mov r10b, [byteStorage + r12-1] ;put each input char in a register each
shl r10b, 2
and r10b, 0x3F ;only keep six bits from left, the two most right are zero
mov r10b, [Base64Table + r10]
mov [b64EncStor + r13], r10b
inc r13
mov r8b, "=" ;add one extra equal sign
mov [b64EncStor + r13], r8b
inc r13
jmp .weHaveFinished
;--------
.weHaveFinished:
;syscall for write, to output the result
mov rax, 1
mov rdi, 1
mov rsi, b64EncStor
mov rdx, r13
syscall
xor r12,r12
mov rax, 60 ; System call for exit
mov rdi, 0
syscall
Answer:
Wiping registers
mov rax, 0
mov rdi, 0
xor r11, r11
xor r12, r12
mov r13, 0 | {
"domain": "codereview.stackexchange",
"id": 43046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, assembly, base64, byte",
"url": null
} |
linux, assembly, base64, byte
Answer:
Wiping registers
mov rax, 0
mov rdi, 0
xor r11, r11
xor r12, r12
mov r13, 0
The preferred way to clear a register is to use the xor reg, reg instruction. It's small and fast. From the above it would seem that you knew this already but didn't apply it consistently. But there's more to it than just using xor. It is best to only have xor operate on the low 32 bits because the CPU will zero the high 32 bits automatically. For the 'old' registers (RAX, RBX, ... ) this will shave off a REX prefix:
xor eax, eax
xor edi, edi
xor r11d, r11d
xor r12d, r12d
xor r13d, r13d
A lurking danger
mov r8b, [Base64Table + r8]
mov r9b, [Base64Table + r9]
mov r10b, [Base64Table + r10]
Your program only ever writes to the lowest byte of the r8, r9, and r10 registers. There's no guarantee whatsoever that the whole 64-bit register will be suitable for indexing like you plan. Best add the following to your wipe list:
xor r8d, r8d
xor r9d, r9d
xor r10d, r10d
Redundant operations
shr r11b, 2
and r11b, 0x3F
The shr instruction already cleared the 2 topmost bits. There's no need for the and instruction that would do the same thing.
and r8b, 0x3
shl r8b,4
mov r11b, r9b
shr r11b, 4
and r11b, 0xF
add r8b, r11b
Here the same redundancy with shifting and anding r11b. In this case however you can consolidate both these and's:
shl r8b, 4
mov r11b, r9b
shr r11b, 4
add r8b, r11b
and r8b, 0x3F
and r9b, 0xF
shl r9b, 2
mov r8b, r10b
shr r8b, 6
and r8b, 0x3
add r9b, r8b
And again the same redundancy with shifting and anding r8b. Consolidating both and's gives:
shl r9b, 2
mov r8b, r10b
shr r8b, 6
add r9b, r8b
and r9b, 0x3F
jmp .weHaveFinished
;--------
.weHaveFinished:
The code can just as well fall through at this point. The jmp is redundant.
Optimizations
dec rax
...
cmp rax, 0 ;if rax = 0, rax was one before above decrementation
je .oneExtraByte ; we jump to .oneExtraByte | {
"domain": "codereview.stackexchange",
"id": 43046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, assembly, base64, byte",
"url": null
} |
linux, assembly, base64, byte
You can safely delay executing the dec rax instruction. The code at the ellipsis doesn't depend on the value that's in RAX. Instead of inspecting using cmp, inspect the flags from using dec. Apply this trick 3 times:
test rax, rax ; `TEST RAX, RAX` is preferred over `CMP RAX, 0`
jz .weHaveFinished
.encodingInProgress:
...
dec rax
jz .oneExtraByte
...
dec rax
jz .twoExtraBytes
...
dec rax
jnz .encodingInProgress
jmp .weHaveFinished
;----------------------------------
.oneExtraByte:
mov [b64EncStor + r13], r8b
inc r13
mov r8b, "=" ;add two extra equal signs
mov [b64EncStor + r13], r8b
inc r13
mov [b64EncStor + r13], r8b
inc r13
jmp .weHaveFinished
All of this incrementing on r13 is overkill. The code is about to end anyway. Just write it like:
mov [b64EncStor + r13], r8b
mov word [b64EncStor + r13 + 1], "=="
jmp .weHaveFinished
Style
To improve readability, you could start all of your tail-comments at the same column. (same goes for instruction mnemonics and operands)
Also be consistent with how you use whitespace. eg. I see the following:
mov [b64EncStor + r13], r11b ; our first char is now encoded
mov [b64EncStor+r13], r8b ; second char now encoded
mov [b64EncStor + r13], r8b
Wouldn't you agree that
mov [b64EncStor + r13], r11b ; our first char is now encoded
mov [b64EncStor + r13], r8b ; second char now encoded
mov [b64EncStor + r13], r8b
is nicer to look at? | {
"domain": "codereview.stackexchange",
"id": 43046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, assembly, base64, byte",
"url": null
} |
c++, performance, algorithm, divide-and-conquer
Title: Karatsuba's multiplication
Question: I am working my way through an algorithms course online, and the assignment is to implement Karatsuba's multiplication algorithm. I am also trying to practice C++, so I wanted to implement it in that language. Looking online, I notice a lot of people solve this using strings.
Is there a benefit to doing that?
If so, can somebody please explain how my code might be optimized or improved by doing that?
I've included my unit tests below, which I wrote using the catch framework.
#include <math.h>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
#include "catch.hpp"
int left (int num, int n) {
if (n < 2) {
printf("left received n < 2");
exit (EXIT_FAILURE);
}
return num / pow(10, n / 2);
}
int right (int num, int left, int n) {
if (n < 2) {
printf("right received n < 2");
exit (EXIT_FAILURE);
}
return num - (left * pow(10, n / 2));
}
int karatsuba_multiply (int x, int y) {
if (x < 1 || y < 1) {
return 0;
}
// base case: x and y are single digits, multiply normally
int num_digits = int(log10(x)) + 1;
if (num_digits == 1) {
return x * y;
}
int a = left(x, num_digits);
int b = right(x, a, num_digits);
int c = left(y, num_digits);
int d = right(y, c, num_digits);
int p = a + b;
int q = c + d;
int ac = karatsuba_multiply(a, c);
int bd = karatsuba_multiply(b, d);
int pq = karatsuba_multiply(p, q);
int adbc = pq - ac - bd;
return pow(10, num_digits) * ac + pow(10, num_digits / 2) * adbc + bd;
}
TEST_CASE("multiplies numbers", "[karatsuba]") {
REQUIRE(karatsuba_multiply(3, 4) == 12);
REQUIRE(karatsuba_multiply(0, 5) == 0);
REQUIRE(karatsuba_multiply(12, 12) == 144);
REQUIRE(karatsuba_multiply(10, 15) == 150);
REQUIRE(karatsuba_multiply(1234, 1473) == 1817682);
} | {
"domain": "codereview.stackexchange",
"id": 43047,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, divide-and-conquer",
"url": null
} |
c++, performance, algorithm, divide-and-conquer
TEST_CASE("helpers", "[karatsuba_helpers]") {
SECTION("left") {
REQUIRE(left(53, 2) == 5);
REQUIRE(left(1555, 4) == 15);
REQUIRE(left(123456, 6) == 123);
}
SECTION("right") {
REQUIRE(right(53, 5, 2) == 3);
REQUIRE(right(1555, 15, 4) == 55);
REQUIRE(right(123456, 123, 6) == 456);
}
}
Answer: Avoid mixing C and C++
You say you are practicing C++, but you use a lot of C code. While you can use most of C in a C++ program, try to avoid it.
Instead of printf("hello\n"), write std::cout << "hello\n". If you want to use printf()-like formatting, then since C++20 you can use std::format().
Prefix the math functions with std::. This will get you the C++ versions of these functions, which often have overloads for different types that might make them more efficient, for example by exploiting the fact that you are trying to raise something to an integer power.
If you do need C functions, use the header files that are prefixed with a c, like <cmath> instead of <math.h>, <cstdlib> instead of <stdlib.h>, and so on. | {
"domain": "codereview.stackexchange",
"id": 43047,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, divide-and-conquer",
"url": null
} |
c++, performance, algorithm, divide-and-conquer
Avoid using floating point functions if all you need is integers
Your code is multiplying integer numbers, but pow() and log10() are returning doubles. This causes a lot of unnecessary conversions between integers and floating point numbers, which is relatively cheap on modern processors, but still not free.
pow(10, n) can be replaced by an array lookup into a precomputed table of powers of 10. log10() is trickier, but see this StackOverflow question for possible solutions.
Even better is not to have to need these functions at all:
Avoid working in base-10
Humans typically use the decimal numeral system, but this is actually not nice for computers, which due to their binary nature, likes to see things in powers of 2. If you would implement your multiplication algorithm using hexadecimal digits, then you can do the equivalent of pow(16, n) using 1 << (n * 4), which is just two bit shift operations, which are very efficient on most CPUs. The equivalent of int(log16(x)) would be (std::bit_width(x) - 1) / 4.
However, even better would be to leave multiplying whole ints to the CPU, which is very good at that, and use the Karatsuba algorithm to multiply even larger numbers.
What about negative numbers?
Your function accepts two int values. An int can be negative. However, trying to multiply two numbers of which at least one is negative will always result in 0 with your code. This might surprise a user. Either decide not to allow negative numbers at all, which you can do by using unsigned ints instead, or allow it but then ensure you handle them correctly.
Use assert() to check for things that should never happen | {
"domain": "codereview.stackexchange",
"id": 43047,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, divide-and-conquer",
"url": null
} |
c++, performance, algorithm, divide-and-conquer
Use assert() to check for things that should never happen
In left() and right(), you check if n < 2, and exit immediately if so. It looks like this situation should never occur though, and these checks are just there to guard against programming errors. This is a good practice, but in that case, use assert(). Apart from being more compact to write, it signals that this is intended to check for programming errors, and the checks can be easily disabled by defining NDEBUG while compiling. So:
assert(n < 2); | {
"domain": "codereview.stackexchange",
"id": 43047,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, divide-and-conquer",
"url": null
} |
c++, performance, algorithm, divide-and-conquer
Note that assert() will actually call abort() instead of exit(EXIT_FAILURE), which is better since it can trigger a core dump, or if it is run inside a debugger, the debugger will see that this is an error instead of a regular program exit. | {
"domain": "codereview.stackexchange",
"id": 43047,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, algorithm, divide-and-conquer",
"url": null
} |
c#, homework
Title: A monthly expenses calculator for an assignment
Question: I've been working on this project for a day. Any feedback on the code would be appreciated. The code is for an assignment. The main concern I have with the project is that I'm not using abstract classes correctly.
Expenses.cs
using System;
using System.Collections.Generic;
using System.Linq;
using ValidateTypeLibrary;
namespace ExpensesCalculator
{
public abstract class Expenses
{
public delegate void ExpensesWarning(IDictionary<string,decimal> expenses);
public abstract decimal MonthlyLoanPayment(); // Abstract method
public void GetMonthlyExpenses(ExpensesWarning expensesWarning)
{
int option;
monthlyExpenses = new Dictionary<string,decimal>();
Console.WriteLine("Please enter the following values:");
Console.Write("a) Gross monthly income (before deductions): ");
monthlyExpenses.Add("Income", GetExpenses());
Console.Write("b) Estimated tax deducted: ");
monthlyExpenses.Add("Tax", GetExpenses());
expensesWarning(monthlyExpenses);
Console.WriteLine("c) Estimated monthly expenditures in each of the following categories: ");
Console.Write("i) Groceries: ");
monthlyExpenses.Add("Groceries", GetExpenses());
expensesWarning(monthlyExpenses);
Console.Write("ii) Water and lights: ");
monthlyExpenses.Add("Utlities", GetExpenses());
expensesWarning(monthlyExpenses);
Console.Write("iii) Travel costs (including petrol):");
monthlyExpenses.Add("Tavel", GetExpenses());
expensesWarning(monthlyExpenses);
Console.Write("ii) Cellphone and Telephone: ");
monthlyExpenses.Add("Phone", GetExpenses());
expensesWarning(monthlyExpenses);
Console.Write("ii) Other expenses: ");
monthlyExpenses.Add("Other", GetExpenses());
expensesWarning(monthlyExpenses); | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
Console.WriteLine("Would you like to rent ('1') or buy property ('2') ?: ");
option = GetOption();
if (option == 1) // User enters the value of their rent per month
{
RentPayment();
expensesWarning(monthlyExpenses);
}
else // User enters details of the house they will be applying for a loan to buy a house
{
HomeLoanPayment();
expensesWarning(monthlyExpenses);
}
Console.WriteLine("Would you like to buy a vehicle? ('1' Yes) or ('2' NO): ");
option = GetOption();
if (option == 1)
{
VehiclePayment();
expensesWarning(monthlyExpenses);
}
DisplayExpenses();
}
private void DisplayExpenses()
{
Console.WriteLine($"Your remaining month for the month after all deductions is: {GetRemainingMoney():C2}");
Console.WriteLine("Your monthly expenses in descending order:");
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Expense \t Amount");
Console.WriteLine("--------------------------------------------");
monthlyExpenses.OrderBy(key => key.Value);
for (int i = 0; i < monthlyExpenses.Count; i++)
{
if (monthlyExpenses.ElementAt(i).Key != "Income")
{
Console.WriteLine($"{monthlyExpenses.ElementAt(i).Key} \t {monthlyExpenses.ElementAt(i).Value:C2}");
}
}
}
private void HomeLoanPayment()
{
HomeLoan homeLoan = new HomeLoan();
monthlyExpenses.Add("HomeLoan", homeLoan.MonthlyLoanPayment()); // Uses the A= P(1+in) formula
Console.WriteLine($"Your monthly repayment for the house is {monthlyExpenses["HomeLoan"]:C2}"); | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
if (monthlyExpenses["HomeLoan"] > (monthlyExpenses["Income"] * 0.33M)) // The user loan should be more than a third of their gross income for a likely approval of a home loan
{
Console.WriteLine("\aApproval of home loan is unlikely");
}
else
{
Console.WriteLine("Approval of home loan is likely");
}
}
private void VehiclePayment()
{
Vehicle vehicle = new Vehicle();
monthlyExpenses.Add("VehicleLoan", vehicle.MonthlyLoanPayment());
Console.WriteLine($"Monthly repayment for vehicle is {monthlyExpenses["VehicleLoan"]:C2}");
}
private void RentPayment()
{
Console.WriteLine("Enter your monthly rent amount: ");
monthlyExpenses.Add("Rent", GetExpenses());
}
private decimal GetRemainingMoney()
{
decimal expenses = 0;
for (int i = 1; i < monthlyExpenses.Count; i++)
{
expenses += monthlyExpenses.ElementAt(i).Value;
}
return monthlyExpenses["Income"] - expenses;
}
private int GetOption()
{
var answer = Console.ReadLine();
bool option = Validate.ValidateInt(answer);
while (option==false)
{
Console.WriteLine("Please enter a valid option");
answer = Console.ReadLine();
option = Validate.ValidateInt(answer);
if (option==true && (Convert.ToInt32(answer)!=1 || Convert.ToInt32(answer) != 2))
{
Console.WriteLine("Please enter a valid answer");
answer = Console.ReadLine();
}
}
return Convert.ToInt32(answer);
}
protected decimal GetExpenses()
{
dynamic expense = "";
while (Validate.ValidateDecimal(expense) == false)
{
expense = Console.ReadLine(); | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
expense = Console.ReadLine();
if (Validate.ValidateDecimal(expense) == true && Validate.ValidatePositve(Convert.ToDouble(expense)) == true)
{
return Convert.ToDecimal(expense);
}
Console.WriteLine("Please enter a valid answer");
}
return 0;
}
public IDictionary<string, decimal> monthlyExpenses { get; set; } // Properties... stores all of the income and expenses from the user
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace ExpensesCalculator
{
public class Program : Expenses
{
static void Main(string[] args)
{
var program = new Program();
program.GetMonthlyExpenses(ExpensesAlert); // Calls the override method
}
public override decimal MonthlyLoanPayment() // Method is not needed
{
throw new NotImplementedException();
}
private static void ExpensesAlert(IDictionary<string, decimal> expenses) // Method used in the delegate
{
// This method calculates if the expenses is greater than 75% of the income
decimal total = 0;
for (int i = 1; i < expenses.Count; i++)
{
total += expenses.ElementAt(i).Value;
}
decimal expenesPercent = ( total / expenses["Income"]) * 100 ;
if (expenesPercent>=75)
{
Console.WriteLine($"\aYou current expenses ({total:C2}) exceed 75% of your total income ({expenses["Income"]:C2})!");
}
}
}
}
Vehicle.cs
using System;
using ValidateTypeLibrary;
namespace ExpensesCalculator
{
class Vehicle : Expenses
{
public override decimal MonthlyLoanPayment()
{
dynamic price, deposit, interestRate,insurance;
string name=null;
int NumOfMonths = 60; // Repayment is assumed to be repaid over five years (60 months)
Console.WriteLine("Please enter the following details: "); | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
Console.Write("Model and make: ");
name = Console.ReadLine();
while (Validate.ValidateString(name)==false)
{
Console.Write("Enter a valid answer: ");
name = Console.ReadLine();
}
Console.Write("Purcase price: ");
price = GetExpenses();
Console.Write("Total deposit: ");
deposit = GetExpenses();
Console.Write("Interest rate: ");
interestRate = GetExpenses();
Console.Write("Estimated insurance premium: ");
insurance = GetExpenses();
// A = P(1+in) this formula will be used to calculate the home loan repayment, formula was modified to return the monthly repayment
decimal A = price - deposit; // P
A = A * (1 + ((interestRate * 0.01m) * (NumOfMonths / 12))); // n = number of years
return (A / NumOfMonths) + insurance; //returns the monthly payment for the loan
}
}
}
HomeLoan.cs
using System;
using ValidateTypeLibrary;
namespace ExpensesCalculator
{
public class HomeLoan : Expenses
{
public override decimal MonthlyLoanPayment()
{
// Gets the info for the home loan
dynamic price, deposit, interestRate, NumOfMonths;
Console.WriteLine("Please enter the following details: ");
Console.Write("Purcase price of the property: ");
price = GetExpenses();
Console.Write("Total deposit: ");
deposit = GetExpenses();
Console.Write("Interest rate: ");
interestRate = GetExpenses();
Console.WriteLine("Number of months to repay (Between 240 and 360 months): ");
NumOfMonths = GetExpenses();
while (NumOfMonths < 240 || NumOfMonths > 360)
{
Console.WriteLine("Between 240 and 360 months");
NumOfMonths = GetExpenses();
}
// A = P(1+in) this formula will be used to calculate the home loan repayment, formula was modified to return the monthly repayment | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
decimal A = price - deposit; // P
A = A * (1 + ((interestRate * 0.01m) * (NumOfMonths / 12))); // n = number of years
return A / NumOfMonths; //returns the monthly payment for the loan
}
}
}
Validator.cs
using System;
namespace ValidateTypeLibrary
{
public static class Validate
{
// Validates the user input as input required from the user is int type
public static bool ValidateInt(dynamic value)
{
// int temp;
if (int.TryParse(value, out int temp))
{
return true;
}
return false;
}
// Validates the user input as input required from the user is decimal type
public static bool ValidateDecimal(dynamic value)
{
decimal temp;
if (decimal.TryParse(value, out temp))
{
return true;
}
return false;
}
// Validates the user input as input required from the user is double type
public static bool ValidateDouble(dynamic value)
{
double temp;
if (double.TryParse(value, out temp))
{
return true;
}
return false;
}
// Validates the user input as input required from the user is char type
public static bool ValidateChar(dynamic value)
{
char temp;
if (char.TryParse(value, out temp))
{
return true;
}
return false;
}
// Validates the user input as input required from the user is float type
public static bool ValidateFloat(dynamic value)
{
float temp;
if (float.TryParse(value, out temp))
{
return true;
}
return false;
}
// Validates the user input as input required from the user is string type and cannot be empty
public static bool ValidateString(string value)
{ | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
if (String.IsNullOrEmpty(value))
{
return false;
}
return true;
}
// Validates the user input as the input required from the user must be positive
public static bool ValidateNegative(double value)
{
if (value > 0)
{
return false;
}
return true;
}
// Validates the user input as the input required from the user must be negative
public static bool ValidatePositve(double value)
{
if (value < 0)
{
return false;
}
return true;
}
}
}
All the classes and libraries have been included.
Answer: If you want to use Dictionary or any Key based collection, ensure that you use a better technique to store / retrieve the value by the key. As using string as key is not an issue if you have limited usage for it, however, with bigger projects it will be hard to maintain. As alternative, you could use enum or you can store the keys as const and reuse them.
Example :
// USE ONLY ONE
// Enum OR Constant
//
// With enum
//
public enum ExpensesName
{
Income,
Tax,
Groceries
//.. etc
}
//
// OR With constant
//
public struct ExpensesName
{
public const string Income = "Income";
//.. etc
}
Now, using one of them would give you this usage :
// add income
monthlyExpenses.Add(ExpensesName.Income, GetExpenses());
// get income
var income = monthlyExpenses[ExpensesName.Income]; | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
// get income
var income = monthlyExpenses[ExpensesName.Income];
This is just a way of managing the keys. However, if you have predefined keys you could declare it with default values in the dictionary and just set their values when needed something like this :
public abstract class Expenses
{
private readonly Dictionary<string, decimal> _monthlyExpenses = new Dictionary<string, decimal>
{
{ "Income", 0 },
{ "Tax", 0 },
{ "Groceries", 0 }
// ..etc
}
public void SetIncome(decimal value)
{
// throw if negative value
if(value < 0)
throw new ArgumentOutOfRangeException();
_monthlyExpenses["Income"] = value;
}
public decimal GetIncome()
{
return _monthlyExpenses["Income"];
}
}
This would let you handle each value separately, and store them all in one predefined dictionary. It's acceptable approach for some senarios, however the better approach would be to have a class model that would hold these values something like this :
public class MonthlyExpenses
{
public decimal Income { get; set; }
public decimal Tax { get; set; }
public decimal Groceries { get; set; }
public decimal Utilities { get; set; }
public decimal Travel { get; set; }
public decimal Phone { get; set; }
public decimal Other { get; set; }
} | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
With this, you can initiate a new instance of MonthlyExpenses and assign the values as needed, then you can pass the instance into any other class or method to reuse its values. This approach is widely used, as it's more maintainable and readable, and can also be extended with more related operations (e.g. adding Validate() method to check wither the properties are having the correct values or not) and better yet, it's intellisense supported.
The second note is that mixing between user-interface logic, and the core logic, is not a good practice, it needs to be separated. So the code can be adapted with future changes without breaking the core logic such as converting from Console to ASP.NET or Console to Windows Form ..etc.
To have a better abstraction, the current abstraction needs to implement the minimum requirements, so revising the current one would be something like this :
public abstract class SimpleInterestBase
{
public decimal Principal { get; }
public decimal Deposit { get; }
public decimal InterestRate { get; }
public decimal Insurance { get; }
public int TotalMonths { get; }
public SimpleInterestBase(decimal principal, decimal deposit, decimal interestRate, decimal insurance, int numberOfMonths)
{
Principal = principal;
Deposit = deposit;
InterestRate = interestRate;
Insurance = insurance;
TotalMonths = numberOfMonths;
}
public virtual decimal GetMonthlyPayment()
{
decimal interestRatePerYear = 1 + ((InterestRate * 0.01m) * (NumberOfMonths / 12));
decimal totalAccruedAmount = Principal - Deposit;
totalAccruedAmount *= interestRatePerYear;
totalAccruedAmount /= NumberOfMonths;
return totalAccruedAmount + Insurance;
}
} | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c#, homework
}
Now, we can implement it on the HomeLoan and VehicleLoan :
public class HomeLoanSimpleInterest : SimpleInterestBase
{
public HomeLoanSimpleInterest(decimal principal, decimal deposit, decimal interestRate, decimal insurance, int numberOfMonths)
: base(principal, deposit, interestRate, insurance, numberOfMonths) { }
}
public class VehicleLoanSimpleInterest : SimpleInterestBase
{
public VehicleLoanSimpleInterest(decimal principal, decimal deposit, decimal interestRate, decimal insurance)
: base(principal, deposit, interestRate, insurance, 60) { }
}
I've changed the abstract class name to the actual purpose name, this would give a better understanding on what the class does, and why it's there.
Now, you can implement a class that would process the user input and validate it, then whenever you get the required values, you initiate the SimpleInterestBase instance (wither for home or vehicle) and return the results to the user. | {
"domain": "codereview.stackexchange",
"id": 43048,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, homework",
"url": null
} |
c++, algorithm, recursion
Title: Sequential Search - Recursion
Question: I have written this program to search for a value in an array using sequential search. And well, I've been trying to implement the same algorithm using recursive structure. is this a good implementation? or is there any other way to make it a little more...? (I'm not sure if..., to say if there is a better way to implement it.)
#include <iostream>
#include <cstdlib>
using std::cout;
using std::cin;
using std::endl;
/* function prototypes */
int
seq_search(const int [], size_t, int);
/* main function */
int
main()
{
int array[15] = {2, 6, 8, 23, 45, 43, 51, 62, 83, 78, 61, 18, 71, 34, 72};
int value = 0;
int location = 0;
for (int i = 0; i < 15; i++)
cout << array[i] << " ";
cout << endl;
cout << "Enter the search value: ";
cin >> value;
location = seq_search(array, 15, value);
if (location != -1)
cout << value << " found at position: " << location << endl;
else
cout << value << " not in array" << endl;
exit(EXIT_SUCCESS);
}
/* function definitions */
int
seq_search(const int array[],
size_t size, int search_value)
{
return (size == 1) ? -1 :
(array[size - 1] == search_value) ? size - 1 :
seq_search(array, size - 1, search_value);
}
test1:
./main
2 6 8 23 45 43 51 62 83 78 61 18 71 34 72
Enter the search item: 61
61 found at position: 10 | {
"domain": "codereview.stackexchange",
"id": 43049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion",
"url": null
} |
c++, algorithm, recursion
test2:
./main
2 6 8 23 45 43 51 62 83 78 61 18 71 34 72
Enter the search item: 5
5 not in list
This is what I wanted to implement:
int
seq_search(const int array[],
size_t size, int search_value)
{
int loc = 0;
bool found = false;
while (loc < listLength && !found) {
if (array[loc] == searchItem) {
found = true;
break;
}
else
loc++;
}
if (found)
return loc;
else
return -1;
}
Answer: Don't use recursion
Although contrary to the code in your previous question, this time you do have tail recursion, which results in efficient code that doesn't have the problem of potentially unlimited stack growth. However, I don't see any value in trying to write a recursive implementation of something that is so much more obvious when implemented iteratively. An iterative version also can be written quite compactly:
int seq_search(const int array[], size_t size, int search_value) {
for (size_t i = 0; i < size; ++i)
if (array[i] == search_value)
return i;
return -1;
} | {
"domain": "codereview.stackexchange",
"id": 43049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion",
"url": null
} |
c++, algorithm, recursion
return -1;
}
Your seq_search() can't find the first element of the array
If size == 1, you return -1. Consider searching for something in an array of just one element, this will obviously return the wrong result. But due to the recursion, it happens for longer arrays as well when the recursion reaches the case where size == 1.
Return a size_t instead of an int
An int might not be large enough to be able to represent all possible positions in the array. Especially on 64-bit machines, where an int is typically only 32 bits, but arrays can be larger than that. If you return a size_t, you don't have that problem. You can use the largest possible value of size_t to represent "item not found", since it will never be possible to have an array that large, as it would not leave memory for anything else, including the program itself.
A simple way to return the largest possible value is to just return -1, or declare a constant of type size_t with that value. See for example std::string::npos.
Use '\n' instead of std::endl
Prefer to use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and can negatively impact performance.
Make it more generic
Again, your seq_search() function has limited use, since it only works on arrays of ints. In C++, it is possible to write a single function that can search for a given value in many different types of containers, see for example std::find(). | {
"domain": "codereview.stackexchange",
"id": 43049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion",
"url": null
} |
c++, beginner, authentication
Title: Login and Register program
Question: This is my first program i write after i finished the c++ tutorials, that program can login and register,
the program ask the user to choice login or register after user choice and write his username the program will choice if this user already exist or not than will take him to next step to write the password and confirm it, after that the program will save the username and password in "txt" file. the login will read the username and password from the same file...
i feel i did a lot of code duplication special on read or write from the files.txt i think should i use classes&objects but i don't know how i feel write The code scattered and disorganized.
My question guys can you give me some advices to improve my code. something should i working on ??
// Note Please you need to create a *users.txt* files before run the program
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
//Login function
void login(){
string UserName,Password;
string UseEnter,PassEnter;
bool On_Off = true;
bool Off = true;
int countt = 0;
int left = 3; | {
"domain": "codereview.stackexchange",
"id": 43050,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, authentication",
"url": null
} |
c++, beginner, authentication
cout << "\n**** Login to your Account **** \n";
while(On_Off){
//********************************************
fstream user;
user.open("users.txt", ios::in);
if(countt < 3 && Off && user.is_open()){
if(countt > 0){
cout << "\nPassword or UserName are not correct!!" << endl;
left--;
cout << "You have *" << left << "* attempts left \n" << endl;
}
cout << "Enter UserName: ";
getline(cin,UseEnter);
cout << "Enter Password: ";
getline(cin,PassEnter);
countt++;
string read;
//====================================================*
while(getline(user,read)){
stringstream convertor(read);
convertor >> UserName >> Password;
if(UseEnter == UserName && PassEnter == Password){
Off = false;}}
//=====================================================*
}
else if(!Off){
cout << "\n**** Welcome! ****\n\n";
user.close();
On_Off = false;
}
else {
cout << "\n**** try again later!! **** \n\n";
user.close();
On_Off = false;
}
}
}
// Registry function
void registry(){
string newName,checkName,newPass,confirmPass;
int MiniPass ;
bool if_ON = true;
bool oo = true;
cout << "\n**** Create New Account **** \n"; | {
"domain": "codereview.stackexchange",
"id": 43050,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, authentication",
"url": null
} |
c++, beginner, authentication
cout << "\n**** Create New Account **** \n";
//UserName Validation
while(oo){
cout << "Enter New UserName: ";
getline(cin, newName);
MiniPass = newName.length();
fstream yusers;
yusers.open("Users.txt",ios::in);
if(if_ON && MiniPass >= 1 && yusers.is_open()){
string readd;
while(getline(yusers,readd)){
stringstream OnlyUsers(readd);
OnlyUsers >> checkName;
if(newName == checkName){
cout <<"\n*"<< newName <<"* UserName already exists Try another one\n" << endl;
if_ON = false;
}
}
yusers.close();
if(!if_ON){
if_ON = true;
}
else{
oo = false;
}
}
}
//Password Validation
while(true){
cout << "Enter New password: ";
getline(cin,newPass);
cout << "Confirm the password: ";
getline(cin,confirmPass);
MiniPass = newPass.length();
if (MiniPass < 5){
cout << "\nYour password is weak at least 5 letters\n \n";
}
else if(confirmPass == newPass){
fstream users;
users.open("Users.txt",ios::app);
if(users.is_open()){
users << newName +" "+ newPass << endl;
users.close();
}
cout << "\n===================================\n";
cout << "\nSuccessfully new account created! \n \n";
cout << "===================================\n";
break;}
else{
cout << "\nPassword confirmation not correct! \n" << endl;
}
}
login();
}
int main()
{
//User can choice Login or register by writing <login> or <register>
string LoR;
cout << "\n***** Login or Register *****\n\n";
cout << "===================================\n";
cout << "\n***** Please write (login) or (register) *****\n\n";
while(true){ | {
"domain": "codereview.stackexchange",
"id": 43050,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, authentication",
"url": null
} |
c++, beginner, authentication
while(true){
getline(cin,LoR);
if(LoR == "login"){
login();
break;
}else if(LoR == "register"){
registry();
break;
}else{
cout << "\n*Please write (login) or (register) correctly*\n" ;
}
}
return 0;
}
Answer: Please indent your code
Taking a first pass it was really difficult to determine where functions ended. While I was scanning it looked like you have random while statements outside your functions. Indentation helps readability a lot, so please do so.
Spaces after keywords / Spaces before & after operators
while() -> while ()
if() -> if ()
for() -> for ()
cout <<"\n*"<< -> cout << "\n*" <<
+" "+ -> + " " +
Don't using namespace std;
Here is a great Stack Overflow answer about why you should not have this in your program.
Naming Conventions
Stick to one naming convention in your code. I see snake_case, camelCase and PascalCase in your code (and also Pascal_Snake_Case?). It makes your code look neater and a whole lot messier.
Guard Clauses
Instead of
if (...) {
return;
} else {
...;
}
do this
if (...) {
return;
}
...;
std::endl; vs "\n"
Consider using std::cout << "..." << std::endl; instead of ending a new line. While there is performance to think about with using std::endl, for a program like this, it's negligible. Here is another Stack Overflow link that talks about this.
Checking user input
Instead of instantly entering a while loop, get user input once after the prompt. Then, have the while loops only function be checking the input, displaying the error message, and getting new input. Once you have correct input, the while loop will exit and continue with the program. Look below:
std::string user_input;
std::cout << "\n***** Login or Register *****\n" << std::endl;
std::cout << "\n=============================" << std::endl;
std::cout << "\n***** Enter (login) or (register) *****\n" << std::endl;
std::getline(std::cin, user_input); | {
"domain": "codereview.stackexchange",
"id": 43050,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, authentication",
"url": null
} |
c++, beginner, authentication
while (user_input != "login" and user_input != "register") {
std::cout << "\n*Please write (login) or (register) correctly*\n" ;
std::getline(std::cin, user_input);
}
if (user_input == "login"){
login();
}
if (user_input == "register"){
registry();
}
While there are other aspects you can improve on, I'm short on time. I'll edit this answer later, or let another reviewer provide their input. | {
"domain": "codereview.stackexchange",
"id": 43050,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, authentication",
"url": null
} |
javascript, authentication, promise, firebase, react-native
Title: React Native login, sign up and sign out using Firebase project
Question: I have built a basic app which uses firebase for authentication.
The app is pretty simple.
Sign up the user to firebase using email and password.
Sign in the user
Sign out the user
Also, I have added some code to check if the user is already signed in. If he/she is already signed in, then proceed to the dashboard, otherwise navigate back to the login page.
I'd like to see where I am going wrong, and any room for improvement.
You can find the project here: https://github.com/98gzi/FirebaseProject
FirebaseProject/App.js
import { StyleSheet } from "react-native";
import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import LoginScreen from "./src/screens/LoginScreen";
import { Provider } from "./src/context/DataContext";
import SignupScreen from "./src/screens/SignupScreen";
import IndexScreen from "./src/screens/IndexScreen";
import { setNavigator } from "./src/navigationService";
import InitialScreen from "./src/screens/InitialScreen";
const Stack = createNativeStackNavigator(); | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
const Stack = createNativeStackNavigator();
const App = () => {
return (
<Provider>
<NavigationContainer
ref={(navigator) => {
setNavigator(navigator);
}}
>
<Stack.Navigator>
<Stack.Screen
name="InitialScreen"
component={InitialScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="Signin"
component={LoginScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="Signup"
component={SignupScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="Index"
component={IndexScreen}
options={{ headerShown: false }}
/>
</Stack.Navigator>
</NavigationContainer>
</Provider>
);
};
export default App;
const styles = StyleSheet.create({});
FirebaseProject/firebase/firebaseConfig.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
// Removed code
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore();
FirebaseProject/src/components/AuthForm.js
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import React, { useEffect, useState } from "react";
const AuthForm = ({ headerText, buttonText, onSubmit, errorMessage }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
return (
<View style={styles.container}>
<Text>{headerText}</Text>
<TextInput
style={styles.input}
placeholder="Email"
value={email}
onChangeText={setEmail}
/>
<TextInput
style={styles.input}
placeholder="Password"
secureTextEntry={true}
value={password}
onChangeText={setPassword}
/>
{errorMessage ? (
<Text style={styles.errorMessage}>{errorMessage}</Text>
) : null}
<Button
title={buttonText}
onPress={() => onSubmit({ email, password })}
/>
</View>
);
};
export default AuthForm;
const styles = StyleSheet.create({
container: {
margin: 10,
},
input: {
height: 40,
margin: 12,
borderBottomWidth: 1,
borderRadius: 5,
padding: 10,
},
errorMessage: {
margin: 12,
color: "red",
marginBottom: 15,
},
});
FirebaseProject/src/context/createDataContext.js
import React, { useReducer } from "react";
export default (reducer, actions, initialState) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{children}
</Context.Provider>
);
};
return { Context, Provider };
};
FirebaseProject/src/context/DataContext.js
import createDataContext from "./createDataContext";
import { auth, db } from "../../firebase/firebaseConfig";
import {
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signOut,
} from "firebase/auth";
import { navigate } from "../navigationService";
import { addDoc, collection } from "firebase/firestore"; | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
const dataReducer = (state, action) => {
switch (action.type) {
case "signin":
return { errorMessage: "", user: action.payload };
case "signup":
return { errorMessage: "", user: action.payload };
case "add_error":
return { ...state, errorMessage: action.payload };
case "clear_error_message":
return { ...state, errorMessage: "" };
default:
return state;
}
};
const clearErrorMessage = (dispatch) => () => {
dispatch({ type: "clear_error_message" });
};
const isSignedIn = (dispatch) => () => {
onAuthStateChanged(auth, (userCred) => {
if (userCred) {
dispatch({ type: "signin", payload: userCred });
navigate("Index");
} else {
navigate("Signin");
}
});
};
const signin =
(dispatch) =>
({ email, password }) => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
dispatch({ type: "signin", payload: user });
navigate("Index");
})
.catch((error) => {
const errorCode = error.code;
console.log(errorCode);
if (errorCode === "auth/wrong-password") {
dispatch({
type: "add_error",
payload: "Incorrect Password",
});
} else if (errorCode === "auth/invalid-email") {
dispatch({
type: "add_error",
payload: "Invalid Email",
});
} else {
dispatch({
type: "add_error",
payload: error.code,
});
}
});
};
const signup =
(dispatch) =>
({ email, password }) => {
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
// Signed in
const user = userCredential.user;
await addDoc(collection(db, "users"), {
worked: true,
}); | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
await addDoc(collection(db, "users"), {
worked: true,
});
dispatch({ type: "signup", payload: user });
})
.catch((error) => {
const code = error.code;
if (code === "auth/email-already-in-use") {
dispatch({
type: "add_error",
payload: "Email already in use",
});
} else if (code === "auth/invalid-email") {
dispatch({
type: "add_error",
payload: "Invalid email",
});
} else if (code === "auth/weak-password") {
dispatch({
type: "add_error",
payload: "Weak password",
});
} else {
dispatch({
type: "add_error",
payload: error.code,
});
}
});
};
const signout = (dispatch) => () => {
signOut(auth)
.then(() => {
dispatch({ type: "signin" });
navigate("Signin");
})
.catch((err) => {
console.log(err);
dispatch({
type: "add_error",
payload: err.code,
});
});
};
export const { Context, Provider } = createDataContext(
dataReducer,
{ signup, signin, isSignedIn, signout, clearErrorMessage },
{ user: null, errorMessage: "" }
);
FirebaseProject/src/screens/DashboardScreen.js
import { StyleSheet, Text, View } from "react-native";
import React from "react";
const DashboardScreen = () => {
return (
<View>
<Text>DashboardScreen</Text>
</View>
);
};
export default DashboardScreen;
const styles = StyleSheet.create({});
FirebaseProject/src/screens/IndexScreen.js
import { StyleSheet, Text, View } from "react-native";
import React, { useContext } from "react";
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItem,
DrawerItemList,
} from "@react-navigation/drawer";
import DashboardScreen from "./DashboardScreen";
import Schedule from "./Schedule";
import { Context } from "../context/DataContext"; | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
const Drawer = createDrawerNavigator();
const SignOutButton = (props) => {
const { signout } = useContext(Context);
return (
<DrawerContentScrollView>
<DrawerItemList {...props} />
<DrawerItem label="Sign out" onPress={() => signout()} />
</DrawerContentScrollView>
);
};
const IndexScreen = () => {
return (
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => <SignOutButton {...props} />}
>
<Drawer.Screen name="Home" component={DashboardScreen} />
<Drawer.Screen name="Schedule" component={Schedule} />
</Drawer.Navigator>
);
};
export default IndexScreen;
const styles = StyleSheet.create({});
FirebaseProject/src/screens/InitialScreen.js
import { StyleSheet, Text, View } from "react-native";
import React, { useContext, useEffect } from "react";
import { Context } from "../context/DataContext";
const InitialScreen = () => {
const { isSignedIn } = useContext(Context);
useEffect(() => {
isSignedIn();
}, []);
return null;
};
export default InitialScreen;
const styles = StyleSheet.create({});
FirebaseProject/src/screens/LoginScreen.js
import {
Button,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from "react-native";
import React, { useContext, useEffect } from "react";
import AuthForm from "../components/AuthForm";
import { Context } from "../context/DataContext";
import { SafeAreaView } from "react-native-safe-area-context";
const LoginScreen = ({ navigation }) => {
const { state, signin, clearErrorMessage } = useContext(Context);
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
clearErrorMessage();
});
return unsubscribe;
}, [navigation]);
return (
<SafeAreaView>
<View>
<AuthForm
headerText="Login into Combat Coach"
buttonText="Login"
onSubmit={signin}
errorMessage={state.errorMessage}
/> | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
<TouchableOpacity onPress={() => navigation.navigate("Signup")}>
<Text style={styles.navLink}>Don't have an account? Sign up</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
export default LoginScreen;
const styles = StyleSheet.create({
navLink: {
color: "#0000EE",
textAlign: "center",
},
});
FirebaseProject/src/screens/Schedule.js
import { StyleSheet, Text, View } from "react-native";
import React from "react";
const Schedule = () => {
return (
<View>
<Text>Schedule</Text>
</View>
);
};
export default Schedule;
const styles = StyleSheet.create({});
FirebaseProject/src/screens/SignupScreen.js
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import React, { useContext, useEffect } from "react";
import AuthForm from "../components/AuthForm";
import { Context } from "../context/DataContext";
import { SafeAreaView } from "react-native-safe-area-context";
const SignupScreen = ({ navigation }) => {
const { state, signup, clearErrorMessage } = useContext(Context);
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
clearErrorMessage();
});
return unsubscribe;
}, [navigation]);
return (
<SafeAreaView>
<View>
<AuthForm
headerText="Sign up to Combat Coach"
buttonText="Signup"
onSubmit={signup}
errorMessage={state.errorMessage}
/>
<TouchableOpacity onPress={() => navigation.navigate("Signin")}>
<Text style={styles.navLink}>Already have an account? Sign in</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
export default SignupScreen;
const styles = StyleSheet.create({
navLink: {
color: "#0000EE",
textAlign: "center",
},
});
FirebaseProject/src/navigationService.js
import { CommonActions } from "@react-navigation/native";
let navigator;
export const setNavigator = (nav) => {
navigator = nav;
}; | {
"domain": "codereview.stackexchange",
"id": 43051,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, authentication, promise, firebase, react-native",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.