body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I am creating a .io style game through Unity and it's coming along nicely. This is my first time working with Unity, and my first time using C#; I have been a Java coder. Could you good people tell me what you think, and tell me if you see any major issues? I am hoping to improve the EnemyCode AI script, and if anyone has suggestions there please let me know.</p>
<p>How the game works - You drop towers that shoot everything that is not on your team, that are within a certain distance. You can also shoot other towers, and you can shoot enemy ships. When you get a kill, or drop a tower, your score goes up. There is a score board that I will make a script for eventually. Enemy ships place towers themselves and will have scores.</p>
<p>EnemyCode.cs</p>
<p>This is the code that the enemy ships run off of. When the enemy is created it randomly picks a color that is not already being used by other players in the game. This is done in the getRandomColor() method. They currently locate the closest tower, and move to it. When in range, the enemy shoots a bullet.cs. They check for a new closer tower every update of the physics engine. I would like to add features where enemy ships target other enemy ships, and the player (Controler.cs) as well. Every 10 seconds wherever the enemy ship is located it places a tower of its own color. I would like to change this up where the enemy code could have a better strategy when placing the towers. When the enemy dies, all towers of the same color die with it. </p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCode : MonoBehaviour
{
public GameObject tower;
public GameObject shot;
public float turnSpeed = 2;
public float shootCooldown = 3;
private float cooldownLeft = 0;
public float shootRange = 10;
public float toCloseRange = 2;
public float speed;
public string color;
public float shotOffset;
public int hp = 10;
public float towerPlaceCooldown = 10;
float towerCooldown = 0;
Color32 c;
TowerCode[] myTeam;
void Start()
{
setColor();
}
void setColor()
{
SpriteRenderer sr = GetComponent<SpriteRenderer>();
c = getRandomColor();
sr.color = c;
color = c.ToString();
}
Color32 getRandomColor()
{
Color32 temp = new Color32();
int randNum = (Random.Range(0, 255)/50)*50;
switch (Random.Range(1, 6))
{
case 1: temp.r = (byte)randNum; temp.b = 0xFF; temp.g = 0x0; temp.a = 0xFF; break;
case 2: temp.r = 0x0; temp.b = (byte)randNum; temp.g = 0xFF; temp.a = 0xFF; break;
case 3: temp.r = 0xFF; temp.b = 0x0; temp.g = (byte)randNum; temp.a = 0xFF; break;
case 4: temp.r = (byte)randNum; temp.b = 0x0; temp.g = 0xFF; temp.a = 0xFF; break;
case 5: temp.r = 0xFF; temp.b = (byte)randNum; temp.g = 0x0; temp.a = 0xFF; break;
case 6: temp.r = 0x0; temp.b = 0xFF; temp.g = (byte)randNum; temp.a = 0xFF; break;
}
Object[] g = FindObjectsOfType(typeof(EnemyCode));
Object[] g2 = FindObjectsOfType(typeof(Controler));
for (int c = 0; c < g.Length; c++)
{
EnemyCode e = (EnemyCode)g[c];
if (temp.ToString().Equals(e.color))
{
return getRandomColor();
}
}
for (int c = 0; c < g2.Length; c++)
{
Controler e = (Controler)g2[c];
if (temp.ToString().Equals(e.color))
{
return getRandomColor();
}
}
return temp;
}
TowerCode[] GetTowerCode()
{
Object[] g = FindObjectsOfType(typeof(TowerCode));
TowerCode[] t = new TowerCode[g.Length];
for (int h = 0; h < g.Length; h++)
{
TowerCode temp = (TowerCode)g[h];
if (!temp.color.Equals(this.color))
{
t[h] = temp;
}
else
{
t[h] = null;
}
}
return t;
}
TowerCode getNextTarget()
{
TowerCode[] t = GetTowerCode();
TowerCode nextTarget = null;
float dist = Mathf.Infinity;
for (int h = 0; h < t.Length; h++)
{
if (t[h] != null)
{
float d = Vector3.Distance(this.transform.position, t[h].transform.position);
if (nextTarget == null || d < dist)
{
nextTarget = t[h];
dist = d;
}
}
}
return nextTarget;
}
void MoveTo(TowerCode nextTarget)
{
Vector2 v = nextTarget.transform.position - this.transform.position;
float angle = Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg;
Quaternion rot = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, turnSpeed * Time.deltaTime);
if (Vector2.Distance(transform.position, nextTarget.transform.position) < toCloseRange)
{
transform.position = Vector2.MoveTowards(transform.position, nextTarget.transform.position, -speed * Time.deltaTime);
}
else if (Vector2.Distance(transform.position, nextTarget.transform.position) > shootRange)
{
transform.position = Vector2.MoveTowards(transform.position, nextTarget.transform.position, speed * Time.deltaTime);
}
else
{
transform.position = this.transform.position;
}
}
void shoot()
{
if (cooldownLeft <= 0)
{
Vector3 vec = transform.rotation * new Vector3(0, shotOffset, 0);
Bullet b = shot.GetComponent<Bullet>();
b.color = color;
Instantiate(shot, transform.position + vec, transform.rotation);
cooldownLeft = shootCooldown;
}
else
{
cooldownLeft -= Time.deltaTime;
}
}
void buildTower()
{
if (towerCooldown <= 0)
{
Transform tra = GetComponent<Transform>();
float x = transform.position.x;
float y = transform.position.y;
tra.transform.position.Set(x, y, 0);
TowerCode tc = tower.GetComponent<TowerCode>();
tc.color = color;
tc.col = c;
tc.setColor();
Instantiate(tower, this.transform.position, this.transform.rotation);
towerCooldown = towerPlaceCooldown;
}
else
{
towerCooldown -= Time.deltaTime;
}
}
void checkForDeath()
{
if (hp <= 0)
{
killTeam();
Destroy(gameObject);
}
}
void killTeam()
{
Object[] g = FindObjectsOfType(typeof(TowerCode));
for (int h = 0; h < g.Length; h++)
{
TowerCode temp = (TowerCode)g[h];
temp.teamDie(c);
}
}
void FixedUpdate()
{
TowerCode nextTarget = getNextTarget();
if (!(nextTarget == null))
{
MoveTo(nextTarget);
shoot();
}
buildTower();
checkForDeath();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!(collision.gameObject.GetComponent<Bullet>().color == color))
{
hp--;
}
}
}
</code></pre>
<p>StartUpCode.cs</p>
<p>This code randomly spawns 27 EnemyCode.cs at the start of the game in the range of the variables. Every graphics update it makes sure there are still 27. If there aren't, it spawns more.</p>
<pre><code>public class StartUpCode : MonoBehaviour
{
public GameObject enemyPlayer;
public float xMaxRange;
public float xMinRange;
public float yMaxRange;
public float yMinRange;
void Start()
{
// max enemy count that current color system can handle is 27
for (int v = 0; v < 27; v++)
{
summonEnemy();
}
}
void Update()
{
if (GetEnemyNum() < 27)
{
summonEnemy();
}
}
void summonEnemy()
{
Vector2 pos = new Vector2(Random.Range(xMinRange, xMaxRange), Random.Range(yMinRange, yMaxRange));
Instantiate(enemyPlayer, pos, Quaternion.identity);
}
int GetEnemyNum()
{
Object[] g = FindObjectsOfType(typeof(EnemyCode));
return g.Length;
}
}
</code></pre>
<p>TowerCode.cs</p>
<p>Very similar to EnemyCode.cs, other than it doesn't move or place towers. I would like to add functionality where the TowerCode.cs can target other towers and the Controler.cs, but I keep running into problems and going back to this stable version. </p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TowerCode : MonoBehaviour
{
public GameObject shot;
public int hp = 5;
public float turnSpeed = 5f;
public float shootRange = 20;
public float shootCooldown = 0.5f;
float cooldownLeft = 0;
public string color;
public float shotOffset;
public Color col;
public void teamDie(Color deadTeamCol)
{
if (this.col == deadTeamCol)
{
Destroy(gameObject);
}
}
public void setColor()
{
SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.color = col;
}
EnemyCode[] GetEnemyCode()
{
Object[] g = FindObjectsOfType(typeof(EnemyCode));
EnemyCode[] t = new EnemyCode[g.Length];
for (int h = 0; h < g.Length; h++)
{
EnemyCode temp = (EnemyCode)g[h];
if (!temp.color.Equals(this.color))
{
t[h] = temp;
}
else
{
t[h] = null;
}
}
return t;
}
EnemyCode getNextTarget()
{
EnemyCode[] t = GetEnemyCode();
EnemyCode nextTarget = null;
float dist = Mathf.Infinity;
for (int h = 0; h < t.Length; h++)
{
if (t[h] != null)
{
float d = Vector3.Distance(this.transform.position, t[h].transform.position);
if (nextTarget == null || d < dist)
{
nextTarget = t[h];
dist = d;
}
}
}
return nextTarget;
}
void pointTo(EnemyCode nextTarget)
{
Vector2 v = nextTarget.transform.position - this.transform.position;
float angle = Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg;
Quaternion rot = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, turnSpeed * Time.deltaTime);
}
void shoot()
{
if (cooldownLeft <= 0)
{
Vector3 vec = transform.rotation * new Vector3(0, shotOffset, 0);
Bullet b = shot.GetComponent<Bullet>();
b.color = color;
Instantiate(shot, transform.position + vec, transform.rotation);
cooldownLeft = shootCooldown;
}
else
{
cooldownLeft -= Time.deltaTime;
}
}
void checkForDeath()
{
if (hp <= 0)
{
Destroy(gameObject);
}
}
void FixedUpdate()
{
EnemyCode nextTarget = getNextTarget();
if (nextTarget != null)
{
pointTo(nextTarget);
shoot();
}
checkForDeath();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!(collision.gameObject.GetComponent<Bullet>().color == color))
{
hp--;
}
}
}
</code></pre>
<p>Controler.cs</p>
<p>This is my player script. It works exactly as I want other than for two things. The towers should spawn behind the player instead of disrupting them when moving. I'm not sure how to implement that.</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controler : MonoBehaviour
{
public float speed = 3f;
float buildCoolDown = 0f;
public float BuildCoolDown = 10;
float shootCooldown = 0;
public float ShootCooldown = 0.5f;
public float turnSensitivity = -2f;
public GameObject tower;
public GameObject shot;
public int hp = 10;
public float shotOffset;
public string color;
Color32 c;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
getColor();
}
void getColor()
{
SpriteRenderer sr = GetComponent<SpriteRenderer>();
c = new Color32();
int randNum = (Random.Range(0, 255) / 50) * 50;
switch (Random.Range(1, 6))
{
case 1: c.r = (byte)randNum; c.b = 0xFF; c.g = 0x0; c.a = 0xFF; break;
case 2: c.r = 0x0; c.b = (byte)randNum; c.g = 0xFF; c.a = 0xFF; break;
case 3: c.r = 0xFF; c.b = 0x0; c.g = (byte)randNum; c.a = 0xFF; break;
case 4: c.r = (byte)randNum; c.b = 0x0; c.g = 0xFF; c.a = 0xFF; break;
case 5: c.r = 0xFF; c.b = (byte)randNum; c.g = 0x0; c.a = 0xFF; break;
case 6: c.r = 0x0; c.b = 0xFF; c.g = (byte)randNum; c.a = 0xFF; break;
}
sr.color = c;
color = c.ToString();
}
void move()
{
if (Input.GetButton("Vertical"))
{
rb.AddForce(transform.up * speed * Input.GetAxis("Vertical"));
}
rb.AddTorque(Input.GetAxis("Horizontal") * turnSensitivity);
}
void shoot()
{
if (Input.GetButton("Fire1") && shootCooldown <= 0)
{
Vector3 vec = transform.rotation * new Vector3(0, shotOffset, 0);
Bullet b = shot.GetComponent<Bullet>();
b.color = color;
Instantiate(shot, transform.position + vec, transform.rotation);
shootCooldown = ShootCooldown;
}
else
{
shootCooldown -= Time.deltaTime;
}
}
void placeTower()
{
if (Input.GetButton("Fire3") && buildCoolDown <= 0)
{
Transform t = GetComponent<Transform>();
float x = rb.transform.position.x;
float y = rb.transform.position.y;
t.transform.position.Set(x, y, 0);
TowerCode tc = tower.GetComponent<TowerCode>();
tc.color = color;
tc.col = c;
tc.setColor();
Instantiate(tower, this.transform.position, this.transform.rotation);
buildCoolDown = BuildCoolDown;
}
else
{
buildCoolDown -= Time.deltaTime;
}
}
void FixedUpdate()
{
move();
shoot();
placeTower();
if (hp <= 0)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!(collision.gameObject.GetComponent<Bullet>().color == color))
{
hp--;
}
}
}
</code></pre>
<p>Bullet.cs</p>
<p>The only problem I have here is that my bullets start out with a speed of almost nothing, and it speeds up as it goes. This causes the problem of the bullets appearing behind moving players/enemy's instead of in front of them. Also there is a weird glitch that causes console errors that don't effect game play. In java I would solve this with a throws exception, but that isn't in C# so I used try catch blocks. Kind of bad code, but it works.</p>
<pre><code>public class Bullet : MonoBehaviour
{
public float bulletSpeed = 10;
public float damage = 1f;
float bulletLife = 3;
public string color;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb.AddForce(transform.up * bulletSpeed);
bulletLifeTracker();
}
void bulletLifeTracker()
{
if (bulletLife <= 0)
{
Destroy(gameObject);
}
bulletLife -= Time.deltaTime;
}
private void OnTriggerEnter2D(Collider2D collision)
{
try
{
if (!(collision.gameObject.GetComponent<Bullet>().color == color))
{
Destroy(gameObject);
}
}
catch (Exception e) { }
try
{
if (!(collision.gameObject.GetComponent<TowerCode>().color == color))
{
Destroy(gameObject);
}
}
catch (Exception e) { }
try
{
if (!(collision.gameObject.GetComponent<EnemyCode>().color == color))
{
Destroy(gameObject);
}
}
catch (Exception e) { }
try
{
if (!(collision.gameObject.GetComponent<Controler>().color == color))
{
Destroy(gameObject);
}
}
catch (Exception e) { }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T20:15:46.460",
"Id": "400433",
"Score": "2",
"body": "Could you expand the description above the code to include more details about the game? Perhaps an explanation of the game flow would be useful to reviewers"
},
{
"Conten... | [
{
"body": "<p>This isn't a complete review: I'm going to start by focusing on just one function. And I may come across as pretty critical, so let me also say that this all looks pretty cool. What follows are my (pretty strong) opinions but bear in mind that I haven't coded any games lately. <em>You have,</em> s... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T00:30:42.880",
"Id": "207401",
"Score": "4",
"Tags": [
"c#",
"game",
"ai",
"unity3d"
],
"Title": "Offline .io style game built in Unity"
} | 207401 |
<p>I just finished implementing a HashMap in Java, with methods:</p>
<ul>
<li><code>add(String key, Integer value)</code></li>
<li><code>get(String key)</code></li>
<li><code>remove(String key)</code></li>
<li><code>printHashMap()</code></li>
</ul>
<p>Is this the correct way to implement a <code>HashMap</code>? I am implementing a load factor feature that automatically increases the size of the <code>HashMap</code> until the load factor is satisfied.</p>
<p><strong>Bucket.java</strong></p>
<pre><code>public class Bucket {
// Each Entry contains a key-value pair
String key;
Integer value;
Bucket next; // Used for chaining
public Bucket(String key, Integer value) {
this.key = key;
this.value = value;
}
}
</code></pre>
<p><strong>HashMap.java</strong></p>
<pre><code>/*
* Author: Henry Zhu
* Building a HashMap that resizes based on load factor
*/
import java.util.ArrayList;
public class HashMap {
private ArrayList<Bucket> data;
private double loadFactor = 0.75;
private int initialCapacity = 16;
private int numBuckets = 0;
public HashMap() {
this.data = new ArrayList<Bucket>();
// Fill the list up to the initial capacity
for (int i = 0; i < initialCapacity; i++) {
this.data.add(null);
}
}
public void remove(String key) {
/*
* get hash code of key
* index is hash code % list's size
* let head be the bucket @ the index
* let previous be null
* while the head is not null:
* if the head's key = key of bucket we want to delete:
* Case 1 (B1 -> B2 (to delete) -> B3):
* previous = B1, so set B1.next = B3
* end result: B1 -> B3
* Case 2 (B1 -> B2 (to delete) -> null):
* previous = B1, so set B1.next = null
* Case 3 (B1 (to delete) -> B2):
* previous = null, set list[index] = B2
* Case 4 (B1 (to delete) -> null):
* set list[index] = null;
*
* return
* else:
* previous becomes head
* head becomes head.next
*/
int hashCode = Math.abs(key.hashCode());
int index = hashCode % this.data.size();
Bucket head = this.data.get(index);
Bucket previous = null;
while (head != null) {
if (head.key.equals(key)) { // Evaluates Cases 1 and 2
if (previous != null) {
if (head.next != null) { // Case 1
previous.next = head.next;
} else { // Case 2
previous.next = null;
}
} else { // Evaluates Case 3 and 4
if (head.next != null) { // Case 3
this.data.set(index, head.next);
} else { // Case 4
this.data.set(index, null);
}
}
numBuckets--;
return;
} else {
previous = head;
head = head.next;
}
}
}
public Integer get(String key) {
/*
* get the hash code of the key
* index is the hash code % list's size
* begin the search:
* let head = the bucket at the index
* while the head i snot null:
* if the head's key = the key we're looking for:
* return head.value
* if not?
* head becomes head.next
* return -1
*/
int hashCode = Math.abs(key.hashCode());
int index = hashCode % this.data.size();
Bucket head = this.data.get(index);
while (head != null) {
if (head.key.equals(key)) {
return head.value;
} else {
head = head.next;
}
}
return -1;
}
public void add(String key, Integer value) {
/*
* get hash code of the key
* index is hash code % list's size
* check if key already exists
* if key exists: update the bucket
* if key doesn't exist:
* if index is already occupied: use chaining
* if index isn't already occupied, place the bucket at the index
*/
int hashCode = Math.abs(key.hashCode());
int index = hashCode % this.data.size();
Bucket bucket = this.data.get(index);
boolean alreadyExists = false;
// See if the key already exists in the HashMap
for (int i = 0; i < this.data.size(); i++) {
if (this.data.get(i) != null && this.data.get(i).key.equals(key)) {
this.data.set(i, new Bucket(key, value));
alreadyExists = true;
}
}
if (!alreadyExists) {
// If the spot is occupied, implement the chaining algorithm (uses a LinkedList)
if (this.data.get(index) != null) {
Bucket head = this.data.get(index);
Bucket previous = head;
while (head != null) {
previous = head;
head = head.next;
}
previous.next = new Bucket(key, value);
}
else {
bucket = new Bucket(key, value);
this.data.set(index, bucket);
}
}
// Check to see if the capacity of the list needs to be increased.
numBuckets++;
if (new Double((1.0 * numBuckets) / this.data.size()).compareTo(loadFactor) >= 0) {
while (new Double((1.0 * numBuckets) / this.data.size()).compareTo(loadFactor) >= 0) {
// Increase the size of the list until the load factor is satisfied
this.data.add(null);
}
}
}
public void printMap() {
/*
* Go through every element in the list
* if element is null:
* print null
* if element is a bucket:
* set head to equal the element
* while the head is not null:
* print the head's value
* if head.next is not null
* print "-> "
* set head = head.next
*/
for (int i = 0; i < this.data.size(); i++) {
if (this.data.get(i) == null) {
System.out.println("[" + i + "] = null");
} else {
Bucket head = this.data.get(i);
String text = "[" + i + "] = ";
while (head != null) {
text += ("(" + head.key + ", " + head.value + ")");
if (head.next != null) {
text += " -> ";
}
head = head.next;
}
System.out.println(text);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Is this the correct way to implement a HashMap?</p>\n</blockquote>\n\n<p>There are multiple ways to write them. Did you look any up?</p>\n\n<p>Your cardinal sin is not writing tests to verify that the code works. And it looks like there's a serious issue here - any reasonably tho... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T02:48:31.787",
"Id": "207405",
"Score": "0",
"Tags": [
"java",
"hash-map",
"hashcode"
],
"Title": "HashMap Implemention in Java"
} | 207405 |
<p>I am learning Go and wrote a small application that queries the Skyscanner API as my first attempt at learning. I was hoping someone more expert than me in the language could look over it at broad strokes and let me know if I'm on the right track. I really appreciate any feedback I can get!</p>
<p>Also, I know this is a fair amount to read over. Feedback on even one or two of the files is appreciated.</p>
<p><a href="https://github.com/sdstolworthy/go-fly" rel="noreferrer">GitHub repository</a></p>
<p><strong>main.go</strong></p>
<pre><code>package main
import (
"fmt"
"log"
"os"
"text/tabwriter"
"github.com/sdstolworthy/go-fly/skyscanner"
)
func main() {
fmt.Println()
params := skyscanner.Parameters{
Adults: 1,
Country: "US",
Currency: "USD",
Locale: "en-US",
OriginPlace: "SLC-sky",
DestinationPlace: "BNA-sky",
OutbandDate: "anytime",
InboundDate: "anytime",
}
for _, v := range DestinationAirports {
params.DestinationPlace = v
fmt.Println(v)
SkyscannerQuotes := skyscanner.BrowseQuotes(params)
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
quote, err := SkyscannerQuotes.LowestPrice()
if err != nil {
log.Printf("%v\n\n", err)
continue
}
fmt.Fprintf(w, "Price:\t$%v\nDeparture:\t%v\nReturn:\t%v\t\n\n", quote.Price, quote.DepartureDate, quote.InboundDate)
}
}
</code></pre>
<p><strong>destinations.go</strong></p>
<pre><code>package main
// DestinationAirports is an array of all airports that should be queried
var DestinationAirports = [...]string{
"CDG-sky",
"BNA-sky",
"LHR-sky",
"ZAG-sky",
"SAN-sky",
"MEX-sky",
}
</code></pre>
<p><strong>skyscanner/config.go</strong></p>
<pre><code>package skyscanner
import (
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
)
// Config contains application secrets
type Config struct {
MashapeKey string `yaml:"mashape_key"`
MashapeHost string `yaml:"mashape_host"`
BaseURL string `yaml:"base_url"`
}
func (c *Config) getConfig() *Config {
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
</code></pre>
<p><strong>skyscanner/network.go</strong></p>
<pre><code>package skyscanner
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
func prettyPrint(apiResponse Response) {
fmt.Printf("%+v\n", apiResponse.Quotes)
}
func parseResponse(response *http.Response) Response {
body, readErr := ioutil.ReadAll(response.Body)
if readErr != nil {
log.Fatal(readErr)
}
apiResponse := Response{}
jsonErr := json.Unmarshal(body, &apiResponse)
if jsonErr != nil {
log.Fatal(jsonErr)
}
return apiResponse
}
func getRequest(url string) *http.Request {
req, err := http.NewRequest(http.MethodGet, url, nil)
var config Config
config.getConfig()
req.Header.Set("X-Mashape-Key", config.MashapeKey)
req.Header.Set("X-Mashape-Host", config.MashapeHost)
if err != nil {
log.Fatal(err)
}
return req
}
func getClient() *http.Client {
return &http.Client{
Timeout: time.Second * 2,
}
}
func formatURL(path string) string {
var c Config
c.getConfig()
baseURL := c.getConfig().BaseURL
return fmt.Sprintf("%v%v", baseURL, path)
}
func get(url string) *http.Response {
res, getErr := getClient().Do(getRequest(url))
if getErr != nil {
log.Fatal(getErr)
}
return res
}
/*
BrowseQuotes stub
*/
func BrowseQuotes(parameters Parameters) Response {
browseQuotes := formatURL(fmt.Sprintf("browsequotes/v1.0/%v/%v/%v/%v/%v/%v/%v",
parameters.Country,
parameters.Currency,
parameters.Locale,
parameters.OriginPlace,
parameters.DestinationPlace,
parameters.OutbandDate,
parameters.InboundDate,
))
res := get(browseQuotes)
return parseResponse(res)
}
</code></pre>
<p><strong>skyscanner/parameters.go</strong></p>
<pre><code>package skyscanner
// Parameters generic request type for skyscanner api
type Parameters struct {
Country string `json:"country"`
Currency string `json:"currency"`
Locale string `json:"locale"`
OriginPlace string `json:"originPlace"`
DestinationPlace string `json:"destinationPlace"`
OutbandDate string `json:"outboundDate"`
Adults int `json:"adults"`
InboundDate string `json:"inboundDate"`
}
</code></pre>
<p><strong>skyscanner/response.go</strong></p>
<pre><code>package skyscanner
import "errors"
// Response generic response from skyscanner api
type Response struct {
Quotes []struct {
QuoteID int `json:"QuoteId"`
MinPrice float64 `json:"MinPrice"`
Direct bool `json:"Direct"`
OutboundLeg struct {
CarrierIds []int `json:"CarrierIds"`
OriginID int `json:"OriginId"`
DestinationID int `json:"DestinationId"`
DepartureDate string `json:"DepartureDate"`
} `json:"OutboundLeg"`
InboundLeg struct {
CarrierIds []int `json:"CarrierIds"`
OriginID int `json:"OriginId"`
DestinationID int `json:"DestinationId"`
DepartureDate string `json:"DepartureDate"`
} `json:"InboundLeg"`
QuoteDateTime string `json:"QuoteDateTime"`
} `json:"Quotes"`
Places []struct {
PlaceID int `json:"PlaceId"`
IataCode string `json:"IataCode"`
Name string `json:"Name"`
Type string `json:"Type"`
SkyscannerCode string `json:"SkyscannerCode"`
CityName string `json:"CityName"`
CityID string `json:"CityId"`
CountryName string `json:"CountryName"`
} `json:"Places"`
Carriers []struct {
CarrierID int `json:"CarrierId"`
Name string `json:"Name"`
} `json:"Carriers"`
Currencies []struct {
Code string `json:"Code"`
Symbol string `json:"Symbol"`
ThousandsSeparator string `json:"ThousandsSeparator"`
DecimalSeparator string `json:"DecimalSeparator"`
SymbolOnLeft bool `json:"SymbolOnLeft"`
SpaceBetweenAmountAndSymbol bool `json:"SpaceBetweenAmountAndSymbol"`
RoundingCoefficient int `json:"RoundingCoefficient"`
DecimalDigits int `json:"DecimalDigits"`
} `json:"Currencies"`
}
// Prices returns an array of the lowest prices for a route and date
func (r *Response) Prices() []float64 {
priceList := make([]float64, len(r.Quotes))
for i, v := range r.Quotes {
priceList[i] = v.MinPrice
}
return priceList
}
// A QuoteSummary is a summary of a outbound trip with its price and date
type QuoteSummary struct {
Price float64
DepartureDate string
InboundDate string
}
// LowestPrice prints a list of the lowest prices and their accompanying dates
func (r *Response) LowestPrice() (*QuoteSummary, error) {
quote := QuoteSummary{
99999999,
"",
"",
}
for _, v := range r.Quotes {
if v.MinPrice < quote.Price {
quote.Price = v.MinPrice
quote.DepartureDate = v.OutboundLeg.DepartureDate
quote.InboundDate = v.InboundLeg.DepartureDate
}
}
if quote.Price == 99999999 {
return nil, errors.New("No quote found")
}
return &quote, nil
}
</code></pre>
| [] | [
{
"body": "<p>(I only looked at the GitHub repository ...)</p>\n\n<p>Ah you've got <code>go vet</code> already on, that's why it's not finding anything,\ngreat!</p>\n\n<p><code>Dockerfile</code> looks good too. You might want to specify an exact Go\nversion just in case.</p>\n\n<p><code>main.go</code> looks fi... | {
"AcceptedAnswerId": "219459",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T06:07:14.427",
"Id": "207407",
"Score": "9",
"Tags": [
"parsing",
"api",
"go",
"http",
"yaml"
],
"Title": "Flight API querier"
} | 207407 |
<p>I converted my .net MVC, Entity Framework and SQL server website into .Net with Storage Table as the cheapest database option in Azure. </p>
<p>I followed a repository pattern same as Entity Framework, Created Base Repository for common CRUD operation and other repositories as per table (entity).</p>
<p>This is my first implementation of StorageTable, I would like to get feedback and best practices so I can improve my code.</p>
<p><strong>BaseRepository</strong></p>
<pre><code>public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : TableEntity, new()
{
private readonly CloudTable table;
protected BaseRepository(CloudTableClient tableClient)
{
table = tableClient.GetTableReference(typeof(TEntity).Name);
table.CreateIfNotExistsAsync().GetAwaiter().GetResult();
}
public CloudTable Table
{
get
{
return this.table;
}
}
public void AddEntity(TEntity entity)
{
TableOperation insertOperation = TableOperation.Insert(entity);
table.ExecuteAsync(insertOperation).GetAwaiter().GetResult();
}
public void AddRange(IEnumerable<TEntity> entities)
{
/// Define a batch operation.
TableBatchOperation batchOperation = new TableBatchOperation();
foreach (var entity in entities)
{
batchOperation.Insert(entity);
}
table.ExecuteBatchAsync(batchOperation).GetAwaiter().GetResult();
}
public TEntity Delete(TEntity entity)
{
TableOperation insertOperation = TableOperation.Delete(entity);
table.ExecuteAsync(insertOperation).GetAwaiter().GetResult();
return entity;
}
public void Edit(TEntity entity)
{
TableOperation insertOperation = TableOperation.InsertOrMerge(entity);
table.ExecuteAsync(insertOperation).GetAwaiter().GetResult();
}
public IEnumerable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public IEnumerable<TEntity> GetAll()
{
TableQuery<TEntity> tableQuery = new TableQuery<TEntity>();
List<TEntity> list = new List<TEntity>();
// Initialize the continuation token to null to start from the beginning of the table.
TableContinuationToken continuationToken = null;
do
{
// Retrieve a segment (up to 1,000 entities).
TableQuerySegment<TEntity> tableQueryResult =
table.ExecuteQuerySegmentedAsync(tableQuery, continuationToken).GetAwaiter().GetResult();
// Assign the new continuation token to tell the service where to
// continue on the next iteration (or null if it has reached the end).
continuationToken = tableQueryResult.ContinuationToken;
list.AddRange(tableQueryResult.Results);
// Loop until a null continuation token is received, indicating the end of the table.
} while (continuationToken != null);
return list;
}
}
</code></pre>
<p><strong>AccountRepository</strong> </p>
<pre><code>public class AccountRepository : BaseRepository<Account>, IAccountRepository
{
public AccountRepository(AnimalHubContext context)
: base(context.TableClient)
{
}
public int GetNoOfOTPInLast1Hrs(string phoneNumber)
{
List<Account> list = new List<Account>();
// Initialize the continuation token to null to start from the beginning of the table.
TableContinuationToken continuationToken = null;
var filter1 = TableQuery.GenerateFilterCondition("PhoneNumber", QueryComparisons.Equal, phoneNumber);
var filter2 = TableQuery.GenerateFilterConditionForDate("CreatedDate", QueryComparisons.GreaterThanOrEqual, DateTime.Now.AddHours(-1));
var filters = TableQuery.CombineFilters(filter1, TableOperators.And, filter2);
TableQuery<Account> query = new TableQuery<Account>().Where(filters)
.Select(new List<string> { "PartitionKey", "RowKey", "Timestamp" });
do
{
// Retrieve a segment (up to 1,000 entities).
TableQuerySegment<Account> tableQueryResult =
base.Table.ExecuteQuerySegmentedAsync(query, continuationToken).GetAwaiter().GetResult();
// Assign the new continuation token to tell the service where to
// continue on the next iteration (or null if it has reached the end).
continuationToken = tableQueryResult.ContinuationToken;
list.AddRange(tableQueryResult.Results);
// Loop until a null continuation token is received, indicating the end of the table.
} while (continuationToken != null);
return list.Count;
}
public bool ValidateOTP(string phoneNumber, int OTP)
{
List<Account> list = new List<Account>();
// Initialize the continuation token to null to start from the beginning of the table.
TableContinuationToken continuationToken = null;
var filter1 = TableQuery.GenerateFilterCondition("PhoneNumber", QueryComparisons.Equal, phoneNumber);
var filter2 = TableQuery.GenerateFilterConditionForInt("OTP", QueryComparisons.Equal, OTP);
var filters = TableQuery.CombineFilters(filter1, TableOperators.And, filter2);
TableQuery<Account> query = new TableQuery<Account>().Where(filters);
do
{
// Retrieve a segment (up to 1,000 entities).
TableQuerySegment<Account> tableQueryResult =
base.Table.ExecuteQuerySegmentedAsync(query, continuationToken).GetAwaiter().GetResult();
// Assign the new continuation token to tell the service where to
// continue on the next iteration (or null if it has reached the end).
continuationToken = tableQueryResult.ContinuationToken;
list.AddRange(tableQueryResult.Results);
// Loop until a null continuation token is received, indicating the end of the table.
} while (continuationToken != null);
Account phoneNumberOTP = list.OrderByDescending(x => x.CreatedDate).FirstOrDefault();
if (phoneNumberOTP != null && phoneNumberOTP.PhoneNumber.Equals(phoneNumber, StringComparison.OrdinalIgnoreCase)
&& phoneNumberOTP.OTP == OTP)
{
return true;
}
return false;
}
}
</code></pre>
<p><strong>Singleton TableContext</strong></p>
<pre><code>public class AnimalHubContext
{
private readonly CloudTableClient tableClient;
public AnimalHubContext(IOptions<ApplicationConfigurations> applicationConfigurations)
{
var cloudStorageAccountName = applicationConfigurations.Value.CloudStorageAccountName;
var cloudStorageKey = applicationConfigurations.Value.CloudStoragekey;
// Retrieve storage account information from connection string.
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(cloudStorageAccountName, cloudStorageKey), true);
// Create a table client for interacting with the table service
this.tableClient = storageAccount.CreateCloudTableClient();
}
public CloudTableClient TableClient
{
get
{
return this.tableClient;
}
}
}
</code></pre>
<p><strong>Entity</strong></p>
<pre><code>public class Account : BaseModel
{
public string PhoneNumber { get; set; }
public int OTP { get; set; }
}
public abstract class BaseModel : TableEntity
{
public BaseModel()
{
PartitionKey = "IN";
RowKey = Guid.NewGuid().ToString();
}
public DateTime CreatedDate { get; set; }
public Status Status { get; set; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T11:20:50.880",
"Id": "400378",
"Score": "0",
"body": "Any particular reason you did not keep the async API?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T11:34:07.333",
"Id": "400379",
"Scor... | [
{
"body": "<p>I would suggest keeping the async API intact and also inject the table as it is the actual dependency, not the context. (Explicit Dependency Principle)</p>\n\n<p>As this is meant to be used by derived classes, its members should be <code>virtual</code> to allow derived classes to <code>override</c... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T09:06:50.253",
"Id": "207413",
"Score": "0",
"Tags": [
"c#",
"azure",
"azure-cosmosdb"
],
"Title": "Azure Storage Table using Repository Pattern"
} | 207413 |
<p>i am trying to write csv parser so if i have the same name in the name column i will delete the second name's line. For example:</p>
<pre><code>['CSE_MAIN\\LC-CSEWS61', 'DEREGISTERED', '2018-04-18-192446'],
['CSE_MAIN\\IT-Laptop12', 'DEREGISTERED', '2018-03-28-144236'],
['CSE_MAIN\\LC-CSEWS61', 'DEREGISTERED', '2018-03-28-144236']]
</code></pre>
<p>I need that the last line will be deleted because it has the same name as the first one.</p>
<p>What i wrote is:</p>
<pre><code>file2 = str(sys.argv[2])
print ("The first file is:" + file2)
reader2 = csv.reader (open(file2))
with open("result2.csv",'wb') as result2:
wtr2= csv.writer( result2 )
for r in reader2:
wtr2.writerow( (r[0], r[6], r[9] ))
newreader2 = csv.reader (open("result2.csv"))
sortedlist2 = sorted(newreader2, key=lambda col: col[2] , reverse = True)
for i in range(len(sortedlist2)):
for j in range(len(sortedlist2)-1):
if (sortedlist2[i][0] == sortedlist2[j+1][0] and sortedlist2[i][1]!=sortedlist2[j+1][1]):
if(sortedlist2[i][1]>sortedlist2[j+1][1]):
del sortedlist2[i][0-2]
else:
del sortedlist2[j+1][0-2]
</code></pre>
<p>Thanks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T09:34:50.060",
"Id": "400369",
"Score": "0",
"body": "Two possible solutions are **1)** store the column in a `dictionary/Java set` and do a lookup before you write a row **2)** sort the data on the column and only write the row if ... | [
{
"body": "<p>You do not need to iterate multiple times over the file. You just need to keep a record of all names seen so far and skip lines with already seen names. This takes <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> additional memory, but only <span class=\"math-container\">\\$\\mathcal{O}... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T09:23:15.303",
"Id": "207414",
"Score": "-1",
"Tags": [
"python",
"parsing",
"csv"
],
"Title": "Remove lines from csv if duplicate value in column"
} | 207414 |
<p>This script replaces the red hair in image to black color (replace one color to another)</p>
<hr>
<h3>Three major parts in this script</h3>
<ul>
<li><p>Not just replace color red to black, I hope the output image looks natural, so I will replace the color <strong>close to</strong> red to black. This "close" is measured by Euclidean distance.</p></li>
<li><p>And not just replace by black color, user can modify the red color's <code>r, g, b</code> value separately, like add more green. </p></li>
<li><p>Choose the area to be changed, rather than change the whole picture</p></li>
</ul>
<hr>
<h3>Suggestions I am looking for:</h3>
<ul>
<li>I did some NumPy practice before, so any suggestions about NumPy are welcome.</li>
<li><p>I think the code to replace target area is not so elegant, I am not quite sure about this part:</p>
<pre><code>(c1, r1), (c2, r2) = area
for i in range(r1, r2+1):
l, r = i*h+c1, i*h+c2+1
data[l:r,:k][D[l:r]] = modification(data[l:r,:k][D[l:r]])
</code></pre></li>
</ul>
<hr>
<h3>Full code:</h3>
<pre><code>import numpy as np
from PIL import Image
from scipy.spatial.distance import cdist
def replace_corlor(image, original_corlor, modification, area=None, distance=1000, output="new_test.jpg"):
print("[*] START Replace Color")
img = Image.open(image)
data = np.asarray(img, dtype="int32")
w,h,k = data.shape
data = np.reshape(data, (w*h,k))
distMatrix = cdist(data, np.array([original_corlor]))
D = distMatrix<=distance
D = np.reshape(D,w*h)
if area is None:
data[:,:k][D] = modification(data[:,:k][D])
else:
(c1, r1), (c2, r2) = area
for i in range(r1, r2+1):
l, r = i*h+c1, i*h+c2+1
data[l:r,:k][D[l:r]] = modification(data[l:r,:k][D[l:r]])
data = np.reshape(data, (w,h,k))
img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype="uint8"), "RGB")
img.save(output)
print("[*] DONE Replace Color")
if __name__ == "__main__":
def modification(color):
return color * [2,0,0]
# return [255,0,0]
replace_corlor("test.jpg",(36,35,30),modification, ((0,0),(400,100)))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T05:42:02.527",
"Id": "400744",
"Score": "1",
"body": "I have no comments on your code, your Python is better than mine. :) But for color modification you could use the distance to the `original_color` value. The larger this distance... | [
{
"body": "<p>Nice code.\nLet's look at the function signatures.\nAs gbartonowen noted, two typos on <code>corlor</code> for <code>color</code>.\nThe keyword defaults are lovely,\nthank you for appropriately dealing with a <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noref... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T10:27:00.247",
"Id": "207415",
"Score": "12",
"Tags": [
"python",
"python-3.x",
"image",
"numpy"
],
"Title": "Replace color in image measured by Euclidean distance"
} | 207415 |
<p>I have been practicing recursion lately and I came up with this code to solve the <a href="https://en.wikipedia.org/wiki/Water_pouring_puzzle" rel="nofollow noreferrer">water jug problem</a>, given two jugs of volume <code>jug1</code> and <code>jug2</code>, where <code>jug1 < jug2</code>, obtain a volume <code>t</code>, where <code>t < jug2</code>.</p>
<p>The algorithm below basically always pours from the smaller jug into the bigger jug, how would you improve the solution ?</p>
<p>I think I get the minimum number of steps this way... am I correct ?</p>
<pre><code>jug1 = 5
jug2 = 7
t = 4
def jugSolver(amt1, amt2):
print(amt1, amt2)
if (amt1 == t and amt2 == 0) or (amt1 == 0 and amt2 == t):
return
elif amt2 == jug2:
jugSolver(amt1, 0)
elif amt1 != 0:
if amt1 <= jug2-amt2:
jugSolver(0, amt1+amt2)
elif amt1 > jug2-amt2:
jugSolver(amt1-(jug2-amt2),amt2+(jug2-amt2))
else:
jugSolver(jug1, amt2)
jugSolver(0,0)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T20:08:55.977",
"Id": "400688",
"Score": "0",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code ... | [
{
"body": "<p>Your code is not a “good” practice at recursion. Every “recursive” call to <code>jugSolver</code> is the last statement that is executed in the current call, thus the whole function can easily be replaced by a simple loop:</p>\n\n<pre><code>print(amt1, amt2)\nwhile amt1 != t and amt2 != t:\n ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T10:51:08.723",
"Id": "207416",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"recursion"
],
"Title": "Pouring water between two jugs to get a certain amount in one of the jugs (2)"
} | 207416 |
<p>I wrote the following code to merge two sorted lists. Is there a way I can improve it?</p>
<p>Possible ideas (not sure how to implement them):</p>
<ul>
<li>Remove code duplication (setting the returning list node and moving to the next)</li>
<li>Avoid the use of the infinite <code>loop</code></li>
<li>Avoid the use of <code>panic!</code></li>
</ul>
<p>This is the data structure:</p>
<pre><code>type Link = Option<Box<Node>>;
pub struct Node {
elem: i32,
next: Link,
}
impl Node {
fn new(elem: i32) -> Node {
Node { elem, next: None }
}
}
</code></pre>
<p>And this is the method:</p>
<pre><code>fn merge_sorted_lists(list1: &Link, list2: &Link) -> Link {
if list1.is_none() || list2.is_none() {
return None;
}
let mut res = None;
{
let mut node3 = &mut res;
let mut node1 = list1;
let mut node2 = list2;
loop {
if let (Some(link1), Some(link2)) = (node1, node2) {
if link1.elem > link2.elem {
*node3 = Some(Box::new(Node::new(link2.elem)));
node2 = &link2.next;
} else {
*node3 = Some(Box::new(Node::new(link1.elem)));
node1 = &link1.next;
}
if let Some(link) = {node3} {
node3 = &mut link.next;
} else {
panic!();
}
} else if let Some(link1) = node1 {
*node3 = Some(Box::new(Node::new(link1.elem)));
node1 = &link1.next;
if let Some(link) = {node3} {
node3 = &mut link.next;
} else {
panic!();
}
} else if let Some(link2) = node2 {
*node3 = Some(Box::new(Node::new(link2.elem)));
node1 = &link2.next;
if let Some(link) = {node3} {
node3 = &mut link.next;
} else {
panic!();
}
} else {
break;
}
}
}
res
}
</code></pre>
| [] | [
{
"body": "<p>One problem in your current code is that you allocate the merged list, that could be what the user want but that not very flexible, a better way would be to consume the list, and let the user do a copy before if needed.</p>\n\n<p>One other problem is that you have <a href=\"https://en.wikipedia.or... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T11:41:24.700",
"Id": "207418",
"Score": "4",
"Tags": [
"linked-list",
"rust"
],
"Title": "Merge two sorted lists in Rust"
} | 207418 |
<p>I have created the following view extending the JPanel class, the objective of this view is to allow the user to perform 3 CRUD operations create,delete and modify on the entity <strong>"Attribute"</strong>, this entity belong to an entity <strong>User</strong> or <strong>Client</strong>, so when the user wants to perform CRUD operations it has to specify if the operations will be performed on the <strong>User Attributes</strong> or <strong>Client Attributes</strong></p>
<p>The view is divided in 2 parts: </p>
<ul>
<li><p>The 1st one is for displaying <strong>Fixed Attributes</strong> from the User and
Client entities, there's not need to perform CRUD operations on
those.</p></li>
<li><p>The 2nd one is for performing the CRUD operations on the <strong>"Additional
Attributes"</strong>.</p></li>
</ul>
<p>How can I improve my class? is there some way to create less JComboBoxes?
How can I improve the look of the JScrollPane?</p>
<pre><code> package view.attributePanes;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class PaneAttributeManagement extends JPanel {
/************ Strings[] **************/
private static String[] types = { "String", "Int", "Date", "Boolean" };
private static String[] entities = { "Users", "Clients" };
/************ JComboBoxes **************/
@SuppressWarnings({ "unchecked", "rawtypes" })
private JComboBox boxAttributeTypes = new JComboBox(types);
@SuppressWarnings({ "unchecked", "rawtypes" })
private JComboBox boxAttributeTypes1 = new JComboBox(types);
@SuppressWarnings({ "unchecked", "rawtypes" })
private JComboBox boxEntities = new JComboBox(entities);
@SuppressWarnings({ "unchecked", "rawtypes" })
private JComboBox boxEntities1 = new JComboBox(entities);
@SuppressWarnings({ "unchecked", "rawtypes" })
private JComboBox boxEntities2 = new JComboBox(entities);
@SuppressWarnings({ "rawtypes" })
private JComboBox boxDeleteAttributesName = new JComboBox();
@SuppressWarnings({ "rawtypes" })
private JComboBox boxModifyAttributesName = new JComboBox();
/************ JTextFields **************/
JTextField addAttributeNameTxt = new JTextField(15);
JTextField addAttributeValueTxt = new JTextField(15);
JTextField modifyAttributeNameTxt = new JTextField(15);
JTextField modifyAttributeValueTxt = new JTextField(15);
/************ JButtons **************/
private JButton addNewAttributeBtn = new JButton("Add");
private JButton deleteAttributeBtn = new JButton("Delete");
private JButton modifyAttributeBtn = new JButton("Update");
/************ Main panes **************/
private JPanel mainPane;
private JScrollPane mainScrollPane;
public PaneAttributeManagement() {
mainPane = new JPanel();
mainPane.setLayout(new MigLayout("wrap 2", "[] 16 []"));
initComponents();
}
protected void initComponents() {
MigLayout layout = new MigLayout("wrap 2", "[grow][grow]", "[grow][grow][grow]");
setLayout(layout);
add(getMainScrollPane(), "cell 0 0");
mainPane.add(getFixedAttributesPanel(), "cell 0 0,grow");
mainPane.add(getAdditionalAttributePanel(), "cell 0 1 2 1,grow");
}
private JScrollPane getMainScrollPane() {
mainScrollPane = new JScrollPane(mainPane);
mainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mainScrollPane.setPreferredSize(new Dimension(470, 400));
return mainScrollPane;
}
private JPanel getFixedAttributesPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Fixed Attributes"));
panel.setLayout(new MigLayout("wrap 2", "[] 16 []"));
panel.add(getFixedUserAttributesPanel());
panel.add(getFixedClientAttributesPanel());
return panel;
}
private JPanel getFixedUserAttributesPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("User"));
panel.setLayout(new MigLayout("wrap 2", "[] 16 []"));
panel.add(new JLabel("1."), "right");
panel.add(new JLabel("User ID"));
panel.add(new JLabel("2."), "right");
panel.add(new JLabel("Name"));
panel.add(new JLabel("3."), "right");
panel.add(new JLabel("Surname"));
panel.add(new JLabel("4."), "right");
panel.add(new JLabel("Password"));
panel.add(new JLabel("5."), "right");
panel.add(new JLabel("Clients owned"));
return panel;
}
private JPanel getFixedClientAttributesPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Client"));
panel.setLayout(new MigLayout("wrap 2", "[] 16 []"));
panel.add(new JLabel("1."), "right");
panel.add(new JLabel("Client ID"));
panel.add(new JLabel("2."), "right");
panel.add(new JLabel("Name"));
return panel;
}
private JPanel getAdditionalAttributePanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Additional Attributes"));
panel.setLayout(new MigLayout("wrap 1", "[] 16 []"));
panel.add(getAddAttributePanel());
panel.add(getModifyAttributePanel());
panel.add(getDeleteAttributePanel());
return panel;
}
private JPanel getAddAttributePanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Add Attribute"));
panel.setLayout(new MigLayout("wrap 2", "[]16[]", "[][][][][][]"));
panel.add(new JLabel("For:"));
panel.add(boxEntities);
panel.add(new JLabel("Name:"));
panel.add(addAttributeNameTxt);
panel.add(new JLabel("Type:"));
panel.add(boxAttributeTypes);
panel.add(new JLabel("Value:"));
panel.add(addAttributeValueTxt);
panel.add(addNewAttributeBtn, "cell 1 4, right");
return panel;
}
private JPanel getDeleteAttributePanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Delete Attributes"));
panel.setLayout(new MigLayout("wrap 2", "[]16[]", "[][][][][][]"));
panel.add(new JLabel("From:"));
panel.add(boxEntities1);
panel.add(new JLabel("Name:"));
panel.add(boxDeleteAttributesName);
panel.add(deleteAttributeBtn, "cell 2 3,right");
return panel;
}
private JPanel getModifyAttributePanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Modify Attributes"));
panel.setLayout(new MigLayout("wrap 2", "[]16[]", "[][][][][][]"));
panel.add(new JLabel("From:"));
panel.add(boxEntities2);
panel.add(new JLabel("Name:"));
panel.add(boxModifyAttributesName);
panel.add(new JLabel("New name:"));
panel.add(modifyAttributeNameTxt);
panel.add(new JLabel("New type:"));
panel.add(boxAttributeTypes1);
panel.add(new JLabel("New value:"));
panel.add(modifyAttributeValueTxt);
panel.add(modifyAttributeBtn, "cell 1 5, right");
return panel;
}
public String getAddAttributeNameTxt() {
return addAttributeNameTxt.getText();
}
public String getAddAttributeValueTxt() {
return addAttributeValueTxt.getText();
}
public String getModifyAttributeNameTxt() {
return modifyAttributeNameTxt.getText();
}
public String getModifyAttributeValueTxt() {
return modifyAttributeValueTxt.getText();
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/tIrvX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tIrvX.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/5UmPJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5UmPJ.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<h3>Quickfire opinions:</h3>\n\n<ul>\n<li>Swing is deprecated. If you have the choice: <strong>do not use swing!</strong></li>\n<li>Empty lines are a useful thing. \nIt's pretty conventional to use empty lines between members and around the import section of code.\nIt helps delineate logically connec... | {
"AcceptedAnswerId": "207423",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T12:02:35.807",
"Id": "207419",
"Score": "4",
"Tags": [
"java",
"swing",
"user-interface",
"crud"
],
"Title": "Simple view for CRUD with miglayout"
} | 207419 |
<p>I wrote a code which prints the following pattern :</p>
<pre><code>5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
</code></pre>
<p>The code is as follows : </p>
<pre><code>#include <stdio.h>
void main(){
int n,i,k,b,a;
printf("ENTER OUTER NUMBER:");
scanf("%d",&n);
for(i=0;i<2*n-1;i++){
printf("%d",n);
}
printf("\n");
int p=n;
for(i=0;i<n-1;i++){
int a=0;
for(k=0;k<=i;k++){
printf("%d",n-a);
a++;
}
for(b=0;b>i;b++){
printf(" ");
}
for(k=1;k<=2*p-3;k++){
printf("%d",n-i-1);
}
p--;
for(k=i;k>=0;k--){
printf("%d",n-k);
}
printf("\n");
}
int q=1;
for(i=0;i<n-2;i++){
for(k=n;k>i+1;k--){
printf("%d",k);
}
for(k=1;k<=2*q-1;k++){
printf("%d",q+1);
}
q++;
for(k=2+i;k<=n;k++){
printf("%d",k);
}
printf("\n");
}
for(i=0;i<2*n-1;i++){
printf("%d",n);
}
getchar();
}
</code></pre>
<p>I printed the first and last line independently.Then,I divided the pattern into two halves and considered some common triangular patterns as follows:</p>
<pre><code>5 5 2 3 4 5
5 4 4 5 3 4 5
5 4 3 3 4 5 4 5
5 4 3 2 2 3 4 5 5
</code></pre>
<p>The code ran well in the <strong>CODE BLOCKS</strong> IDE.But, I think it's too long and I complicated the coding.My query is:</p>
<ol>
<li><p>Can I shorten the code with the similar logic of breaking the pattern into parts or mine is ok ?</p></li>
<li><p>Is there any alternative to this ?</p></li>
</ol>
| [] | [
{
"body": "<p>The same pattern can be produced by a single instance of nested for loops, where outer loop variable is line and inner one - horizontal position.</p>\n\n<p>I do not want to spoil your fun in finding the function at the heart of the loop (at least yet), which given two coordinates produces the valu... | {
"AcceptedAnswerId": "207434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T12:46:30.193",
"Id": "207421",
"Score": "5",
"Tags": [
"c",
"ascii-art"
],
"Title": "Printing concentric squares of numbers"
} | 207421 |
<p>I have written a function which counts how many unique words are included in a given text.</p>
<p>The source-code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const computeCountUniqueWords = (strToExamine) => {
let parts = strToExamine.split(" ");
let validWords = parts.filter((word) => {
return /^\w/.test(word);
});
let uniqueWords = new Set(validWords);
return uniqueWords.size;
}
let text1 = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor.";
let text2 = "Etiam ultricies nisi vel augue. Curabitur ullamcorper";
console.log(`Text 1 has ${computeCountUniqueWords(text1)} words`);
console.log(`Text 2 has ${computeCountUniqueWords(text2)} words.`);</code></pre>
</div>
</div>
</p>
<p>I think it has become quite neat and short. </p>
<p>Nevertheless: <strong>Is there a better way to solve the described task?</strong> </p>
<p>Moveover: <strong>Is my checking with the regular expression sufficient? Or should it be enhanced?</strong></p>
<p>Looking forward to reading your answers.</p>
| [] | [
{
"body": "<h2>Two problems</h2>\n\n<p>Your code has two problems. </p>\n\n<ol>\n<li>It does not remove punctuation from the words resulting in the same words not matching. Eg <code>text1</code> has 12 unique words not 13. You count <code>dolor</code> and <code>dolor.</code> as different words.</li>\n<li>You ar... | {
"AcceptedAnswerId": "207437",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T14:23:51.780",
"Id": "207429",
"Score": "7",
"Tags": [
"javascript",
"regex",
"ecmascript-6"
],
"Title": "Compute count of unique words using ES6 sets"
} | 207429 |
<p>I am trying to find a good, basic way to make selection and insertion sorts so that I can manipulate them for other sorting techniques. How do these look? Is there a simpler way to write them?</p>
<pre><code>package javaapplication59;
public class JavaApplication59 {
public static void main(String[] args) {
selectionSort ss = new selectionSort();
insertionSort is = new insertionSort();
int[] arr = {2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345};
arr = is.sort(arr);
System.out.print("{");
for (int el : arr) {
System.out.print(el + ",");
}
System.out.println("\b}");
}
}
class insertionSort {
public int[] sort(int[] a) {
int insrt, j;
boolean keepGoing;
for (int i = 1; i < a.length; i++) {
insrt = a[i];
j = i - 1;
keepGoing = true;
while ((j >= 0) && keepGoing) {
if(insrt<a[j]){
a[j+1] = a[j];
j--;
if(j==-1)
a[0] = insrt;
}
else{
keepGoing = false;
a[j+1] = insrt;
}
}
}
return a;
}
}
class selectionSort {
public int[] sort(int[] arr) {
int min, minIndex;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
arr[minIndex] = arr[i];
arr[i] = min;
}
return arr;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T22:32:33.193",
"Id": "400440",
"Score": "3",
"body": "Consider using [`java.util.Arrays.toString(int[])`](https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html#toString(int%5B%5D)) for printing your array. Ie: `System.ou... | [
{
"body": "<p>Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.\nIf you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.</p... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T15:39:42.133",
"Id": "207433",
"Score": "3",
"Tags": [
"java",
"algorithm",
"sorting",
"insertion-sort"
],
"Title": "Selection and Insertion sorts from scratch in Java"
} | 207433 |
<p>While I'm training to get better at C, I tried my hand at making a doubly linked list implementation. </p>
<h3><code>linkedlist.h</code></h3>
<pre><code>#ifndef LINKED_LIST_H_
#define LINKED_LIST_H_
#include <stdlib.h>
typedef struct node {
void* data;
struct node *next;
struct node *prev;
} node;
typedef node* pnode;
typedef struct List {
pnode head, tail;
} *List;
List init_list();
void push_back(List, void*);
void* pop_back(List);
void push_front(List, void*);
void* pop_front(List);
void foreach(List, void (*func)(void*));
void free_list(List);
void clear(List);
int size(List);
#endif /* LINKED_LIST_H_ */
</code></pre>
<h3><code>linkedlist.c</code></h3>
<pre><code>#include "linkedlist.h"
List init_list() {
List list = (List)malloc(sizeof(struct List));
list->head = NULL;
list->tail = NULL;
return list;
}
void push_back(List list, void* data) {
pnode temp = (pnode)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
temp->prev = NULL;
if(!(list->head)) {
list->head = temp;
list->tail = temp;
} else {
list->tail->next = temp;
temp->prev = list->tail;
list->tail = list->tail->next;
}
}
void push_front(List list, void* data) {
pnode temp = (pnode)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
temp->prev = NULL;
if(!(list->tail)) {
list->head = temp;
list->tail = temp;
} else {
list->head->prev = temp;
temp->next = list->head;
list->head = list->head->prev;
}
}
void* pop_front(List list) {
if(!(list->tail)) return NULL;
pnode temp = list->head;
if(list->head == list->tail) {
list->head = list->tail = NULL;
} else {
list->head = list->head->next;
list->head->prev = NULL;
}
void* data = temp->data;
free(temp);
return data;
}
void* pop_back(List list) {
if(!(list->head)) return NULL;
pnode temp = list->tail;
if(list->tail == list->head) {
list->tail = list->head = NULL;
} else {
list->tail = list->tail->prev;
list->tail->next = NULL;
}
void* data = temp->data;
free(temp);
return data;
}
void free_list(List list) {
while(list->head) {
pop_back(list);
}
free(list);
}
void clear(List list) {
while(list->head) {
pop_back(list);
}
}
void foreach(List list, void(*func)(void*)) {
pnode temp = list->head;
if(temp) {
while(temp) {
(*func)(temp->data);
temp = temp->next;
}
}
}
int size(List list) {
int i = 0;
pnode temp = list->head;
while(temp) {
i++;
temp = temp->next;
}
return i;
}
</code></pre>
<p>Can you please point out any flaws, errors, stupid mistakes, general improvements, which can make this code better and "C'ish"?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T17:40:50.500",
"Id": "400422",
"Score": "1",
"body": "Why are you defining struct type aliases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T17:48:12.527",
"Id": "400423",
"Score": "0",
... | [
{
"body": "<p>The method <code>free_list(list)</code> should internally use <code>clear(list)</code>, instead of duplicating the code for clearing the list.</p>\n\n<p>The method <code>clear(list)</code> should not use <code>pop_back(list)</code>, which does a lot of checks and pointer assignments, which are dis... | {
"AcceptedAnswerId": "207456",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T16:31:56.237",
"Id": "207435",
"Score": "2",
"Tags": [
"c",
"linked-list"
],
"Title": "Doubly linked list in C"
} | 207435 |
<p>I'm new to handling errors and am not sure how to do it, basically, in a speicific request <code>err.code === 11000</code> is not actually an error, but expected behaviour. I want to output it but not like another error and I want the code to continue running. I don't think it looks nice.</p>
<pre><code>(async () =>{
let client;
try {
client = await MongoClient;
let sales = await call(),
collection = client.db("scraper").collection("sold");
try {
stored = await collection.insertMany(sales.sold, {ordered: false});
console.log({completed: stored.result.n})
}catch(err){
if(err.code === 11000){log({completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length})}
else{log( {err} )}
}
//console.log(sales)
} catch(err) {
log(err)
}
client.close();
})()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T07:17:06.190",
"Id": "400460",
"Score": "2",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what th... | [
{
"body": "<p>In the case that the error code is not 11000 I would re-throw the error in the inner try. That way you do not repeat, possibly complex error logic or possibly execute code that you do not want to. i.e. instead of </p>\n\n<pre><code>try {\n try {\n // code\n } catch(err) {\n if (err.code ==... | {
"AcceptedAnswerId": "207487",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T22:45:34.447",
"Id": "207447",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"ecmascript-6"
],
"Title": "Is this a good way to use Try catch?"
} | 207447 |
<blockquote>
<h3><a href="https://leetcode.com/problems/most-profit-assigning-work" rel="nofollow noreferrer">Problem Statement</a>:</h3>
<p><em>We have jobs: <code>difficulty[i]</code> is the difficulty of the i<sup>th</sup> job, and <code>profit[i]</code> is the profit of the i<sup>th</sup> job.</em></p>
<p><em>Now we have some workers. <code>worker[i]</code> is the ability of the i<sup>th</sup> worker, which means that this worker can only complete a job with difficulty at most <code>worker[i]</code>.</em></p>
<p><em>Every worker can be assigned at most one job, but one job can be completed multiple times.</em></p>
<p><em>For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.</em></p>
<p><em>What is the most profit we can make?</em></p>
<h3>Example 1:</h3>
<ul>
<li><strong>Input</strong>:
<ul>
<li><code>difficulty = [2,4,6,8,10]</code></li>
<li><code>profit = [10,20,30,40,50]</code></li>
<li><code>worker = [4,5,6,7]</code> </li>
</ul></li>
<li><strong>Output</strong>:
<ul>
<li><code>100</code></li>
</ul></li>
</ul>
<p>Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.</p>
<h3>Notes:</h3>
<ul>
<li><code>1 <= difficulty.length = profit.length <= 10000</code> </li>
<li><code>1 <= worker.length <= 10000</code> </li>
<li><code>difficulty[i]</code>, <code>profit[i]</code>, <code>worker[i]</code> are in range [1, 10^5]</li>
</ul>
</blockquote>
<h3>Solution:</h3>
<ul>
<li><strong>Time Complexity</strong>: <code>O(n log n + w log n)</code>.</li>
<li><strong>Space Complexity</strong>: <code>O(n)</code>.</li>
</ul>
<p> </p>
<pre><code>class Solution {
private static class Job implements Comparable<Job> {
private int difficulty;
private int profit;
public Job(int difficulty, int profit) {
this.difficulty = difficulty;
this.profit = profit;
}
public int getDifficulty() {
return difficulty;
}
public int getProfit() {
return profit;
}
//Jobs are ordered based on their difficulties
@Override
public int compareTo(Job otherJob) {
int difference = this.getDifficulty() - otherJob.getDifficulty();
//If both the jobs have the same difficulty, we want the more profitable job to be ordered first so that we get correct maxProfits
difference = (difference == 0) ? (otherJob.getProfit() - this.getProfit()) : difference;
return difference;
}
}
private void updateDifficultyAndMaxProfits(Job[] jobs, int[] difficulties, int[] maxProfits) {
for (int i = 0; i < jobs.length; i++) {
Job job = jobs[i];
difficulties[i] = job.getDifficulty();
if (i == 0) {
maxProfits[i] = job.getProfit();
} else {
maxProfits[i] = Math.max(job.getProfit(), maxProfits[i - 1]);
}
}
}
public int maxProfitAssignment(int[] difficulties, int[] profits, int[] workers) {
Job[] jobs = new Job[difficulties.length];
for (int i = 0; i < difficulties.length; i++) {
jobs[i] = new Job(difficulties[i], profits[i]);
}
Arrays.sort(jobs);
int[] maxProfits = new int[difficulties.length];
updateDifficultyAndMaxProfits(jobs, difficulties, maxProfits);
int totalMaxProfit = 0;
for (int worker : workers) {
int workerMaxProfitIndex = Arrays.binarySearch(difficulties, worker);
//If there isn't an exact match we need to retrieve the index from the insertion point
if (workerMaxProfitIndex < 0) {
workerMaxProfitIndex = -(workerMaxProfitIndex + 2);
}
//Update totalMaxProfit only if there's at least one task that the worker can accomplish
if(workerMaxProfitIndex >= 0){
totalMaxProfit += maxProfits[workerMaxProfitIndex];
}
}
return totalMaxProfit;
}
}
</code></pre>
<p>Please review my code and let me know if there's room for improvement.</p>
| [] | [
{
"body": "<h3>Algorithm</h3>\n\n<p>The algorithm is correct, but an optimization is possible.\nWhen the input contains multiple jobs with the same difficulty,\nthen you can reduce the search space,\nbecause at any difficulty level,\nyou're only interested in the most profitable job.\nThe time complexity would ... | {
"AcceptedAnswerId": "207863",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T00:10:17.267",
"Id": "207452",
"Score": "2",
"Tags": [
"java",
"programming-challenge",
"interview-questions",
"binary-search"
],
"Title": "Leetcode #826. Most Profit Assigning Work solution in Java (Sort + Binary Search)"
} | 207452 |
<p>I just finished making a flappy bird type game and would like some feedback on my game loop and state machine. The game loop was based on <a href="https://www.koonsolo.com/news/dewitters-gameloop/" rel="nofollow noreferrer">deWiTTER's</a> article, and the state machine was based off of an <a href="https://codereview.stackexchange.com/questions/200150/sdl-c-high-low-guessing-game">answer</a> by Indi on my first game. The code was condensed and re-arranged in order to just have a minimum viable project to show the basic idea. If needed, <a href="https://github.com/Nickswoboda/FlippyWhale" rel="nofollow noreferrer">this</a> is the githhub for the full game including the <code>SDL</code> and <code>LTexture</code> files.</p>
<p>One main question: I've read both deWiTTER's and Gaffer's articles on timesteps. I think I understand the gist of both, deWiTTER's a little more so. Is one solution better than the other? Or does it just depend on the game?</p>
<p>Also, is there an ideal amount of updates per second for physics? deWiTTER's argues that 25 is more than enough, but Gaffer's example uses 100 updates per second.</p>
<p>Beside that, any feedback on either the game loop or my state machine will be really helpful.</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <stack>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include "SDLInit.h"
#include "Texture.h"
#include "StateMachine.h"
#include "Game.h"
int main(int argc, char* args[])
{
sdl sdlinit;
AssetManager assets;
Game game;
//used for retro-ish look
SDL_RenderSetLogicalSize(assets.renderer_.get(), VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
std::stack<std::unique_ptr<state>> stateStack;
stateStack.push(std::unique_ptr<state>(new TitleState{&assets, &game}));
int nextGameTick = SDL_GetTicks();
int loops;
while (!stateStack.empty())
{
loops = 0;
state::update_result_t result;
stateStack.top()->input();
//update only 25fps but render as fast as possible
while (SDL_GetTicks() > nextGameTick && loops < MAX_FRAMESKIP)
{
game.nowTime_ = SDL_GetTicks() / 1000.f;
game.deltaTime_ = game.nowTime_ - game.thenTime_;
game.thenTime_ = game.nowTime_;
result = stateStack.top()->update();
nextGameTick += SKIP_TICKS;
loops++;
}
//used for smoother movement
assets.interpolation_ = float(SDL_GetTicks() + SKIP_TICKS - nextGameTick)
/ float(SKIP_TICKS);
if (result.type == state::update_result_type::continue_state)
{
stateStack.top()->render();
}
else if (result.type == state::update_result_type::replace_state)
{
stateStack.top().swap(result.next);
}
else if (result.type == state::update_result_type::push_state)
{
stateStack.push(std::move(result.next));
}
else if (result.type == state::update_result_type::end_state)
{
stateStack.pop();
}
else if (result.type == state::update_result_type::quit_state)
{
while (!stateStack.empty())
stateStack.pop();
}
}
return 0;
}
</code></pre>
<p><strong>Globals.h</strong></p>
<pre><code>#pragma once
const int TICKS_PER_SECOND = 25;
const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
const int MAX_FRAMESKIP = 5;
constexpr int SCREEN_WIDTH = 1024;
constexpr int SCREEN_HEIGHT = 576;
constexpr int VIRTUAL_WIDTH = 512;
constexpr int VIRTUAL_HEIGHT = 288;
constexpr int BIRD_HEIGHT = 24;
constexpr int BIRD_WIDTH = 38;
constexpr int PIPE_WIDTH = 70;
constexpr int PIPE_HEIGHT = 288;
constexpr float PIPE_SPEED = 4.0f;
constexpr int BACKGROUND_LOOPING_POINT = 576;
constexpr float BACKGROUND_SCROLL_SPEED = 2.0f;
</code></pre>
<p><strong>StateMachine.h</strong></p>
<pre><code>#pragma once
#include "Game.h"
#include <algorithm>
#include <vector>
class state
{
public:
enum class update_result_type
{
continue_state,
end_state,
replace_state,
push_state,
quit_state,
};
struct update_result_t
{
update_result_type type = update_result_type::continue_state;
std::unique_ptr<state> next = nullptr;
};
state() = default;
virtual ~state() = default;
virtual void input() = 0;
virtual update_result_t update() = 0;
virtual void render() = 0;
state(state const&) = delete;
auto operator=(state const&) = delete;
};
class PlayState : public state
{
public:
PlayState(AssetManager* assets, Game* game);
void input() override;
update_result_t update() override;
void render() override;
private:
enum class UserChoice
{
none,
pause,
start,
quit,
};
UserChoice choice_ = UserChoice::none;
AssetManager* assets_ = nullptr;
Game* game_ = nullptr;
std::vector<PipePair> pipePair_;
float timer_ = 0;
int lastYPos_ = -190;
int score_ = 0;
};
class CountdownState : public state
{
public:
CountdownState(AssetManager* assets, Game* game);
void input() override;
update_result_t update() override;
void render() override;
private:
enum class UserChoice
{
none,
start,
quit,
};
UserChoice choice_ = UserChoice::none;
AssetManager* assets_ = nullptr;
Game* game_ = nullptr;
float timer_ = 0.f;
float countdownTime_ = 1.f;
int count_ = 3;
};
class TitleState : public state
{
public:
TitleState(AssetManager* assets, Game* game);
void input() override;
update_result_t update() override;
void render() override;
private:
enum class UserChoice
{
none,
start,
quit,
};
UserChoice choice_ = UserChoice::none;
AssetManager* assets_ = nullptr;
Game* game_ = nullptr;
};
</code></pre>
<p><strong>StateMachine.cpp</strong></p>
<pre><code>#include "StateMachine.h"
#include "Globals.h"
#include <iostream>
PlayState::PlayState(AssetManager* assets, Game* game) : assets_(assets), game_(game)
{}
void PlayState::input()
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
choice_ = UserChoice::quit;
}
else if (e.type == SDL_KEYDOWN)
{
if (e.key.keysym.sym == SDLK_RETURN)
{
choice_ = UserChoice::pause;
}
}
}
}
state::update_result_t PlayState::update()
{
assets_->updateBackground();
static int pipeSpawnTime = 0;
timer_ += game_->deltaTime_;
if (timer_ >= pipeSpawnTime)
{
timer_ -= pipeSpawnTime;
pipeSpawnTime = getRandomNumber(1, 2);
pipePair_.push_back(PipePair{ lastYPos_ });
lastYPos_ = getRandomNumber(-220, -160);
}
for (int i = 0; i < pipePair_.size(); i++)
{
pipePair_[i].update(assets_);
}
for (int i = 0; i < pipePair_.size(); i++)
{
if (pipePair_[i].remove_)
{
pipePair_.erase(pipePair_.begin());
}
}
if (choice_ == UserChoice::quit)
return { state::update_result_type::quit_state };
else if (choice_ == UserChoice::pause)
{
assets_->scrolling_ = false;
return { state::update_result_type::replace_state, std::unique_ptr<state>{new TitleState{assets_, game_ }} };
}
return {};
}
void PlayState::render()
{
SDL_RenderClear(assets_->renderer_.get());
assets_->renderBackground();
for (int i = 0; i < pipePair_.size(); i++)
{
pipePair_[i].render(assets_);
}
SDL_RenderPresent(assets_->renderer_.get());
}
CountdownState::CountdownState(AssetManager* assets, Game* game) : assets_(assets), game_(game)
{}
void CountdownState::input()
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
choice_ = UserChoice::quit;
}
}
}
state::update_result_t CountdownState::update()
{
timer_ += game_->deltaTime_;
if (timer_ > countdownTime_)
{
timer_ -= countdownTime_;
count_--;
}
if (count_ == 0)
{
assets_->scrolling_ = true;
return { state::update_result_type::replace_state, std::unique_ptr<state>{new PlayState{assets_, game_}} };
}
if ( choice_ == UserChoice::quit)
return { state::update_result_type::quit_state };
}
void CountdownState::render()
{
SDL_RenderClear(assets_->renderer_.get());
assets_->renderBackground();
LTexture timerText = { from_text, assets_->hugeFont_.get(), assets_->renderer_.get(), std::to_string(count_), assets_->whiteFont_, assets_->fontWrapWidth_ };
timerText.render(assets_->renderer_.get(), VIRTUAL_WIDTH / 2 - timerText.width_ / 2, 120);
SDL_RenderPresent(assets_->renderer_.get());
}
TitleState::TitleState(AssetManager* assets, Game* game) : assets_(assets), game_(game)
{}
void TitleState::input()
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
choice_ = UserChoice::quit;
}
else if (e.type == SDL_KEYDOWN)
{
if (e.key.keysym.sym == SDLK_RETURN)
{
choice_ = UserChoice::start;
}
}
}
}
state::update_result_t TitleState::update()
{
switch (choice_)
{
case UserChoice::quit:
return { state::update_result_type::quit_state };
case UserChoice::start:
return { state::update_result_type::replace_state, std::unique_ptr<state>{new CountdownState{assets_, game_}} };
default:
return {};
}
}
void TitleState::render()
{
SDL_RenderClear(assets_->renderer_.get());
assets_->renderBackground();
SDL_RenderPresent(assets_->renderer_.get());
}
</code></pre>
<p><strong>Game.h</strong></p>
<pre><code>#pragma once
#include <vector>
#include <random>
#include <SDL.h>
#include <SDL_ttf.h>
#include "Texture.h"
#include "Globals.h"
#include "SDLInit.h"
std::mt19937& random_engine();
int getRandomNumber(int x, int y);
struct Game
{
float thenTime_ = 0.0f;
float nowTime_ = 0.0f;
float deltaTime_ = 0.0f;
};
struct AssetManager
{
AssetManager();
void updateBackground();
void renderBackground();
void renderAward(int score);
std::unique_ptr<SDL_Window, sdl_deleter> window_{ SDL_CreateWindow("Flippy", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN) };
std::unique_ptr<SDL_Renderer, sdl_deleter> renderer_{ SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) };
std::unique_ptr<TTF_Font, sdl_deleter> smallFont_{ TTF_OpenFont("resources/font.ttf", 8) };
std::unique_ptr<TTF_Font, sdl_deleter> mediumFont_{ TTF_OpenFont("resources/font.ttf", 14) };
std::unique_ptr<TTF_Font, sdl_deleter> flappyFont_{ TTF_OpenFont("resources/flappy.ttf", 28) };
std::unique_ptr<TTF_Font, sdl_deleter> hugeFont_{ TTF_OpenFont("resources/font.ttf", 56) };
SDL_Color whiteFont_ = { 0xff, 0xff, 0xff };
int fontWrapWidth_ = SCREEN_WIDTH;
LTexture backgroundTexture_ = { from_surface, renderer_.get(), "resources/background.png" };
LTexture groundTexture_ = { from_surface, renderer_.get(), "resources/ground.png" };
LTexture flippyTexture_ = { from_surface, renderer_.get(), "resources/flippy.png" };
LTexture flippyWhaleText_ = { from_text, flappyFont_.get(), renderer_.get(), "Flippy Whale", whiteFont_, fontWrapWidth_ };
LTexture pressEnterText = { from_text, smallFont_.get(), renderer_.get(), "Press Enter", whiteFont_, fontWrapWidth_ };
LTexture youLostText_ = { from_text, mediumFont_.get(), renderer_.get(), "Oof! You Lost!", whiteFont_, fontWrapWidth_ };
LTexture restartText_ = { from_text, mediumFont_.get(), renderer_.get(), "Press Enter to Play Again!", whiteFont_, fontWrapWidth_ };
bool scrolling_ = false;
float backgroundScroll_ = 0;
float groundScroll_ = 0;
float interpolation_ = 0.0f;
std::vector<LTexture> corals;
};
struct Pipe
{
enum class Orientation
{
TOP,
BOTTOM,
};
Pipe(Orientation side, int yPos) : orientation_(side), yPos_(yPos)
{}
void render(AssetManager* assets, int color);
float xPos_ = VIRTUAL_WIDTH + 64;
int yPos_ = 0;
int width_ = PIPE_WIDTH;
int height_ = PIPE_HEIGHT;
Orientation orientation_ = Orientation::TOP;
};
struct PipePair
{
PipePair(int yPos) : yPos_(yPos)
{}
void update(AssetManager* assets);
void render(AssetManager* assets);
int gapHeight_ = getRandomNumber(70, 90);
bool scored_ = false;
float xPos_ = VIRTUAL_WIDTH + 32;
int yPos_ = 0;
bool remove_ = false;
int color_ = getRandomNumber(0, 2);
Pipe pipes_[2] = { Pipe(Pipe::Orientation::TOP, yPos_), Pipe(Pipe::Orientation::BOTTOM, yPos_ + PIPE_HEIGHT + gapHeight_) };
};
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>#include "Game.h"
std::mt19937& random_engine()
{
static std::mt19937 mersenne(std::random_device{}());
return mersenne;
}
int getRandomNumber(int x, int y)
{
std::uniform_int_distribution<> dist{ x,y };
return dist(random_engine());
}
AssetManager::AssetManager()
{
corals.push_back(LTexture{ from_surface, renderer_.get(), "resources/purplecoral.png" });
corals.push_back(LTexture{ from_surface, renderer_.get(), "resources/pinkcoral.png" });
corals.push_back(LTexture{ from_surface, renderer_.get(), "resources/yellowcoral.png" });
}
void AssetManager::updateBackground()
{
if (scrolling_ == true)
{
backgroundScroll_ += BACKGROUND_SCROLL_SPEED;
if (backgroundScroll_ > BACKGROUND_LOOPING_POINT)
{
backgroundScroll_ = 0;
}
}
}
void AssetManager::renderBackground()
{
if (scrolling_ == true)
backgroundTexture_.render(renderer_.get(), std::max(static_cast<int>(-backgroundScroll_ - (BACKGROUND_SCROLL_SPEED * interpolation_)), -BACKGROUND_LOOPING_POINT), 0);
else
backgroundTexture_.render(renderer_.get(), -backgroundScroll_, 0);
}
void PipePair::update(AssetManager* assets)
{
if (xPos_ > -PIPE_WIDTH * 2)
{
xPos_ -= PIPE_SPEED;
for (int i = 0; i < 2; i++)
{
pipes_[i].xPos_ -= PIPE_SPEED;
}
}
else
{
remove_ = true;
}
}
void PipePair::render(AssetManager* assets)
{
for (int i = 0; i < 2; i++)
{
pipes_[i].render(assets, color_);
}
}
void Pipe::render(AssetManager* assets, int color)
{
if (orientation_ == Pipe::Orientation::TOP)
{
assets->corals[color].render(assets->renderer_.get(), xPos_ - (PIPE_SPEED * assets->interpolation_), yPos_, nullptr, 0.0, nullptr, SDL_FLIP_VERTICAL);
}
else
{
assets->corals[color].render(assets->renderer_.get(), xPos_ - (PIPE_SPEED * assets->interpolation_), yPos_);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T07:24:38.070",
"Id": "400462",
"Score": "0",
"body": "\"Also, is there an ideal amount of updates per second for physics? deWiTTER's argues that 25 is more than enough, but Gaffer's example uses 100 updates per second.\" I think tha... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T06:41:54.237",
"Id": "207460",
"Score": "3",
"Tags": [
"c++",
"sdl"
],
"Title": "Game loop and State Machine C++/SDL2"
} | 207460 |
<p>I am extracting 10 lat/long points from Google Maps and placing these into a text file. The program should be able to read in the text file, calculate the <a href="https://pypi.org/project/haversine/" rel="nofollow noreferrer">haversine</a> distance between each point, and store in an adjacency matrix. The adjacency matrix will eventually be fed to a 2-opt algorithm, which is outside the scope of the code I am about to present.</p>
<p>The following code is functional, but extremely inefficient. If I had 1000 points instead of 10, the adjacency matrix would need 1000 x 1000 iterations to be filled. Can this be optimized?</p>
<pre><code>import csv
from haversine import haversine
import matplotlib.pyplot as plt
import numpy as np
def read_two_column_file(file_name):
with open(file_name, 'r') as f_input:
csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True, )
long = []
lat = []
for col in csv_input:
x = float(col[0]) # converting to float
y = float(col[1])
long.append(x)
lat.append(y)
return long, lat
def display_points(long, lat):
plt.figure()
plt.ylabel('longitude')
plt.xlabel('latitude')
plt.title('longitude vs latitude')
plt.scatter(long, lat)
plt.show()
def main():
long, lat = read_two_column_file('latlong.txt')
points = []
for i in range(len(lat)):
coords = tuple([lat[i], long[i]]) # converting to tuple to be able to perform haverine calc.
points.append(coords)
hav = []
for i in range(len(lat)):
for j in range(len(long)):
hav.append(haversine(points[i], points[j]))
np.asarray(hav)
adj_matrix = np.reshape(hav, (10, 10)) # reshaping to 10 x 10 matrix
print(adj_matrix)
display_points(long, lat)
main()
</code></pre>
<p>Sample Input:</p>
<pre><code>35.905333, 14.471970
35.896389, 14.477780
35.901281, 14.518173
35.860491, 14.572245
35.807607, 14.535320
35.832267, 14.455894
35.882414, 14.373217
35.983794, 14.336096
35.974463, 14.351006
35.930951, 14.401137
</code></pre>
<p>Sample Output:</p>
<pre><code>[[ 0. 1.15959635 5.15603243 12.15003864 12.66090817 8.06760374
11.25481465 17.31108648 15.37358741 8.34541481]
[ 1.15959635 0. 4.52227294 11.19223786 11.50131214 7.32033758
11.72388583 18.35259685 16.41378987 9.29953014]
[ 5.15603243 4.52227294 0. 7.44480948 10.26177912 10.15688933
16.24592213 22.1101544 20.18967731 13.40020548]
[12.15003864 11.19223786 7.44480948 0. 7.01813758 13.28961044
22.25645098 29.42422794 27.49154954 20.48281039]
[12.66090817 11.50131214 10.26177912 7.01813758 0. 9.22215871
19.74293886 29.16680205 27.25540014 19.97465594]
[ 8.06760374 7.32033758 10.15688933 13.28961044 9.22215871 0.
10.66219491 21.06632671 19.24994647 12.24773666]
[11.25481465 11.72388583 16.24592213 22.25645098 19.74293886 10.66219491
0. 11.67502344 10.21846781 6.08016463]
[17.31108648 18.35259685 22.1101544 29.42422794 29.16680205 21.06632671
11.67502344 0. 1.93885474 9.20353461]
[15.37358741 16.41378987 20.18967731 27.49154954 27.25540014 19.24994647
10.21846781 1.93885474 0. 7.28280909]
[ 8.34541481 9.29953014 13.40020548 20.48281039 19.97465594 12.24773666
6.08016463 9.20353461 7.28280909 0. ]]
</code></pre>
<p>Plot:</p>
<p><a href="https://i.stack.imgur.com/O1m4O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O1m4O.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T09:10:49.367",
"Id": "400468",
"Score": "1",
"body": "Welcome to Code Review and congratulations on writing a decent question on your first try."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T14:54:5... | [
{
"body": "<p>More than half of your code is being used to convert from one data format to another (from two lat and long list to tuples and then from a list of lists to an array).</p>\n\n<p>The easiest to understand version would be to use <a href=\"https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/n... | {
"AcceptedAnswerId": "207493",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T07:25:02.903",
"Id": "207461",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"coordinate-system"
],
"Title": "Extracting an adjaceny matrix containing haversine distance from points on map"
} | 207461 |
<p>I have the following code:</p>
<pre><code>function TSliverHelper.SlowNorth: TSlice;
var
i: integer;
begin
// Add pixels 0,1,2
// This means expanding every bit into a byte
// Or rather every byte into an int64;
for i:= 0 to 7 do begin
Result.Data8[i]:= TSuperSlice.Lookup012[Self.bytes[i]];
end;
end;
</code></pre>
<p>This uses a straight forward lookup table, but obviously LUT's are slow and clobber the cache. This takes about 2860 millisecs for 100.000.000 items.</p>
<p>The following approach is a bit faster (1797 MS, or 37% faster):</p>
<pre><code>function TSliverHelper.North: TSlice;
const
SliverToSliceMask: array[0..7] of byte = ($01,$02,$04,$08,$10,$20,$40,$80);
asm
//RCX = @Self (a pointer to an Int64)
//RDX = @Result (a pointer to an array[0..63] of byte)
movq xmm0,[rcx] //Get the sliver
mov r9,$8040201008040201
movq xmm15,r9 //[rip+SliverToSliceMask] //Get the mask
movlhps xmm15,xmm15 //extend it
mov r8,$0101010101010101 //Shuffle mask
movq xmm14,r8 //00 00 00 00 00 00 00 00 01 01 01 01 01 01 01 01
pslldq xmm14,8 //01 01 01 01 01 01 01 01 00 00 00 00 00 00 00 00
movdqa xmm1,xmm0 //make a copy of the sliver
//bytes 0,1
pshufb xmm1,xmm14 //copy the first two bytes across
pand xmm1,xmm15 //Mask off the relevant bits
pcmpeqb xmm1,xmm15 //Expand a bit into a byte
movdqu [rdx],xmm1
//bytes 2,3
psrldq xmm0,2 //shift in the next two bytes
movdqa xmm2,xmm0
pshufb xmm2,xmm14 //copy the next two bytes across
pand xmm2,xmm15 //Mask off the relevant bits
pcmpeqb xmm2,xmm15 //Expand a bit into a byte
movdqu [rdx+16],xmm2
//bytes 4,5
psrldq xmm0,2 //shift in the next two bytes
movdqa xmm3,xmm0
pshufb xmm3,xmm14 //copy the next two bytes across
pand xmm3,xmm15 //Mask off the relevant bits
pcmpeqb xmm3,xmm15 //Expand a bit into a byte
movdqu [rdx+32],xmm3
//bytes 6,7
psrldq xmm0,2 //shift in the next two bytes
movdqa xmm4,xmm0
pshufb xmm4,xmm14 //copy the final two bytes across
pand xmm4,xmm15 //Mask off the relevant bits
pcmpeqb xmm4,xmm15 //Expand a bit into a byte
//Store the data
movdqu [rdx+48],xmm4
end;
</code></pre>
<p>However, that is a lot of code. I'm hoping there's a way to do with less processing that's going to work faster.
The way the code works (in prose) is simple.<br>
First we clone the input byte 8 times. Next the bit is masked off using the 01,02,04... mask and an AND operation. Finally this randomish bit is expanded into a byte using the compare-equal-to-mask (pcmpeqb). </p>
<p>The opposite operation is a simple <code>PMSKMOVB</code>. </p>
<p>I can use AVX1 code, but not AVX2.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T09:30:27.007",
"Id": "400469",
"Score": "0",
"body": "Don't you have any other options than Pascal (if I'm right)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T09:37:45.387",
"Id": "400470",
... | [
{
"body": "<p>Use a multiplication to perform several shifts in a single instruction.</p>\n\n<ol>\n<li><p>Trim the input to seven bits to avoid overlap in the second step.</p></li>\n<li><p>Shift by 0, 7, 14, 21, 28, 35, 42 bits and aggregate the results in a 64-bit integer.</p></li>\n<li><p>Keep only bits 0, 8,... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T09:02:15.293",
"Id": "207462",
"Score": "4",
"Tags": [
"performance",
"assembly",
"native-code",
"pascal",
"x86"
],
"Title": "Expand every bit into a byte"
} | 207462 |
<p>I created a simple game of life and I used console prints to debug and visualize it at first. However, when I tried to introduce GUI (using Python <code>tkinter</code>), the game slowed down to a crawl. Everything is working fine, as far as I'm concerned, but I would like to know how to improve performance.</p>
<p>Notes:</p>
<ol>
<li>I asked something similar on Stackoverflow, but that was a specific question about a bug I think I had. Hope that's OK</li>
<li>I have a design bug, where when a shape gets to the outskirts of the grid, it starts to behave badly. Known, and not the primary issue currnetly</li>
</ol>
<p>Thanks in advance, really appriciate any input (<em>include styling, abuse-of-methods / Python built-ins, alogrithmic and anything that comes up to mind in order to improve</em>).</p>
<pre><code># Game of life
from random import randint
import numpy as np
from copy import deepcopy
from enum import Enum
import tkinter as tk
class State(Enum):
Dead = 0
Alive = 1
def __str__(self):
return str(self.value)
class Cell:
def __init__(self, m, n, state):
self.m = np.uint(m)
self.n = np.uint(n)
self.state = state
def kill(self):
self.state = State.Dead
def birth(self):
self.state = State.Alive
def __str__(self):
return '({},{}) {}'.format(self.m, self.n, self.state)
def __repr__(self):
return '({},{}) {}'.format(self.m, self.n, self.state)
class Game:
def __init__(self, m, n, alive_cells = None):
self.m = m
self.n = n
self.grid = np.ndarray((m,n), dtype = np.uint8)
if alive_cells:
self.cells = [Cell(i // n,i % n, State.Alive if (i // n,i % n) in alive_cells else State.Dead) for i in range(m*n)]
else:
self.cells = [Cell(i / n,i % n,randint(0,1)) for i in range(m*n)]
# GUI #
self.top = tk.Tk()
self.cell_size = 10000 // 400 #(self.m * self.n)
self.canvas = tk.Canvas(self.top, bg="gray", height=self.m *self. cell_size, width=self.n * self.cell_size)
self.rectangulars = []
def populate_grid(self):
for cell in self.cells:
self.grid[cell.m,cell.n] = cell.state.value
def show(self, show_GUI = True, print_2_console = False):
self.populate_grid()
if print_2_console:
print('#'*self.m*3)
print(self.grid)
if show_GUI:
self.draw_canvas()
def iterate(self):
'''
Rules:
(1) If cell has less than 2 neighbours, it dies
(2) If cell has more than 3 neighbours, it dies
(3) If cell has 2-3 neighbours, it survives
(4) If cell has 3 neighbours, it rebirths
'''
new_cells = []
for cell in self.cells:
alive_neighbours = 0
for i in range(cell.m - 1, cell.m + 2):
for j in range(cell.n - 1, cell.n + 2):
if i == cell.m and j == cell.n:
continue
else:
try:
alive_neighbours += self.grid[i,j]
except IndexError:
pass
tmp = deepcopy(cell)
if alive_neighbours < 2 or alive_neighbours > 3:
tmp.kill()
elif alive_neighbours == 3:
tmp.birth()
else: # == 2
pass
new_cells.append(tmp)
self.cells = new_cells
self.show()
def draw_canvas(self):
# delete old rectangulars
for rect in self.rectangulars:
self.canvas.delete(rect)
for cell in self.cells:
if cell.state == State.Alive:
color = 'blue'
else:
color = 'red'
self.rectangulars.append(self.canvas.create_rectangle(cell.n*self.cell_size, cell.m*self.cell_size, (1+cell.n)*self.cell_size, (1+cell.m)*self.cell_size, fill=color))
self.canvas.pack()
self.update_canvas()
self.top.mainloop()
def update_canvas(self): # iterate -> show -> draw_canvas
self.top.after(100, self.iterate)
if __name__ == "__main__":
glider = (40, 40, ((1,3), (2,3), (2,1), (3,2), (3,3)))
small_exploder = (30, 30, ((10,10), (11,9), (11,10), (11,11), (12,9), (12,11), (13,10)))
M, N, STARTING_LIVE_CELLS, ITERATIONS = *small_exploder, 0
g = Game(M, N, STARTING_LIVE_CELLS)
g.show()
</code></pre>
| [] | [
{
"body": "<p>The main problem is that you're attempting to create about 9000 canvas objects a second. While the canvas is fairly flexible and powerful, it starts to have performance issues once you create a few tens of thousands of objects, even when you delete them later. Since you are creating 9000 objects p... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T09:59:37.070",
"Id": "207464",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"tkinter",
"game-of-life"
],
"Title": "Adding GUI to game of life hinders performance"
} | 207464 |
<p>My code takes numbers from a large text file, then splits it to organise the spacing and to place it into a 2-dimensional array. The code is used to get data for a job scheduler that I'm building.</p>
<pre><code>#reading in workload data
def getworkload():
work = []
strings = []
with open("workload.txt") as f:
read_data = f.read()
jobs = read_data.split("\n")
for j in jobs:
strings.append(" ".join(j.split()))
for i in strings:
work.append([float(s) for s in i.split(" ")])
return work
print(getworkload())
</code></pre>
<p>The <a href="https://www.writeurl.com/publish/0nyoo3ntnueidy248o1s" rel="nofollow noreferrer">text file</a> is over 2000 lines long, and looks like this:</p>
<pre><code> 1 0 1835117 330855 640 5886 945 -1 -1 -1 5 2 1 4 9 -1 -1 -1
2 0 2265800 251924 640 3124 945 -1 -1 -1 5 2 1 4 9 -1 -1 -1
3 1 3114175 -1 640 -1 945 -1 -1 -1 5 2 1 4 9 -1 -1 -1
4 1813487 7481 -1 128 -1 20250 -1 -1 -1 5 3 1 5 8 -1 -1 -1
5 1814044 0 122 512 1.13 1181 -1 -1 -1 1 1 1 1 9 -1 -1 -1
6 1814374 1 51 512 -1 1181 -1 -1 -1 1 1 1 2 9 -1 -1 -1
7 1814511 0 55 512 -1 1181 -1 -1 -1 1 1 1 2 9 -1 -1 -1
8 1814695 1 51 512 -1 1181 -1 -1 -1 1 1 1 2 9 -1 -1 -1
9 1815198 0 75 512 2.14 1181 -1 -1 -1 1 1 1 2 9 -1 -1 -1
10 1815617 0 115 512 1.87 1181 -1 -1 -1 1 1 1 1 9 -1 -1 -1
…
</code></pre>
<p>It takes 2 and a half minutes to run but I can print the returned data. How can it be optimised?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T11:07:25.133",
"Id": "400482",
"Score": "1",
"body": "Welcome on Code Review. I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. If you're having trouble getting s... | [
{
"body": "<p>You are doing a lot of unnecessary work. Why split each row only to join it with single spaces and then split it again by those single spaces?</p>\n\n<p>Instead, here is a list comprehension that should do the same thing:</p>\n\n<pre><code>def get_workload(file_name=\"workload.txt\"):\n with op... | {
"AcceptedAnswerId": "207484",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T10:59:08.413",
"Id": "207469",
"Score": "0",
"Tags": [
"python",
"performance",
"csv",
"formatting"
],
"Title": "Taking text from a file and formatting it"
} | 207469 |
<h2>Intro</h2>
<p>I'm going through the K&R book (2nd edition, ANSI C ver.) and want to get the most from it: learn (outdated) C and practice problem-solving at the same time. I believe that the author's intention was to give the reader a good exercise, to make him think hard about what he can do with the tools introduced, so I'm sticking to program features introduced so far and using "future" features and standards only if they don't change the program logic.</p>
<p>Compiling with <code>gcc -Wall -Wextra -Wconversion -pedantic -std=c99</code>.</p>
<h2>K&R Exercise 1-22</h2>
<p>Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.</p>
<h2>Solution</h2>
<p>The solution attempts to reuse functions coded in the previous exercises (<code>getline</code> & <code>copy</code>) and make the solution reusable as well. In that spirit, a new function <code>size_t foldline(char * restrict ins, char * restrict outs, size_t fcol, size_t tw);</code> is coded to solve the problem. However, it requires a full buffer to be able to determine the break-point, so I coded <code>size_t fillbuf(char s[], size_t sz);</code> to top-up the buffer.</p>
<p>I wanted to make the folding non-destructive and possibly reversible, so the program doesn't delete anything, and adds a <code>\</code> when we break individual "words". The output can be reversed by deleting <code>(?<=\ )\n|(?<=\t)\n|\\\n</code> pattern matches (obviously if original had some matches, they'll get deleted too). Would you say this design approach is good?</p>
<p>In the spirit of writing reusable code, should I move appending the '\n' and '\' to the <code>main</code> routine and make the function just split the string at breakpoint? Or even, make one to find the breakpoint, and other to split the string?</p>
<pre><code>## Code
/* Exercise 1-22. Write a program to "fold" long input lines into two or more
* shorter lines after the last non-blank character that occurs before the n-th
* column of input. Make sure your program does something intelligent with very
* long lines, and if there are no blanks or tabs before the specified column.
*/
#include <stdio.h>
#include <stdbool.h>
#define MAXTW 16 // max. tab width
#define MAXFC 100 // max. fold column, must be >=MAXTW
#define LINEBUF MAXFC+2 // line buffer size, must be >MAXFC+1
size_t getline(char line[], size_t sz);
void copy(char * restrict to, char const * restrict from);
size_t foldline(char * restrict ins, char * restrict outs, size_t fcol,
size_t tw); // style Q, how to indent this best?
size_t fillbuf(char s[], size_t sz);
int main(void)
{
char line[LINEBUF]; // input buffer
size_t len; // input buffer string length
size_t fcol = 10; // column to fold at
size_t tw = 4; // tab width
if (fcol > MAXFC) {
return -1;
}
if (tw > MAXTW) {
return -2;
}
len = getline(line, LINEBUF);
while (len > 0) {
char xline[LINEBUF]; // folded part
size_t xlen; // folded part string length
// fold the line (or part of one)
xlen = foldline(line, xline, fcol, tw);
printf("%s", line);
// did we fold?
if (xlen > 0) {
// we printed only the first part, and must run the 2nd part through
// the loop as well
copy(line, xline);
if (line[xlen-1] == '\n') {
len = xlen;
}
else {
// if there's no '\n' at the end, there's more of the line and
// we must fill the buffer to be able to process it properly
len = fillbuf(line, LINEBUF);
}
}
else {
len = getline(line, LINEBUF);
}
}
return 0;
}
/* Folds a line at the given column. The input string gets truncated to have
* `fcol` chars + '\n', and the excess goes into output string.
* Non-destructive (doesn't delete whitespace) and adds a '\' char before the
* '\n' if it has to break a word. Can be reversed by deleting
* "(?<=\ )\n|(?<=\t)\n|\\\n" regex pattern matches unless the original file had
* matches as well.
*/
size_t foldline(char * restrict ins, char * restrict outs, size_t fcol,
size_t tw)
{
/* Find i & col such that they will mark either the position of termination
* (\0 or \n) or whatever the char in the overflow column.
* Find lnbi such that it will mark the last non-blank char before the
* folding column.
*/
size_t i;
size_t lnbi;
size_t col;
char lc = ' ';
for (col = 0, i = 0, lnbi = 0; ins[i] != '\0' && ins[i] != '\n' &&
col < fcol; ++i) {
if (ins[i] == ' ') {
++col;
if (lc != ' ' && lc != '\t') {
lnbi = i-1;
}
}
else if (ins[i] == '\t') {
col = (col + tw) / tw * tw;
if (lc != ' ' && lc != '\t') {
lnbi = i-1;
}
}
else {
++col;
}
lc = ins[i];
}
// Determine where to fold at
size_t foldat;
if (col < fcol) {
// don't fold, terminated before the fold column
outs[0] = '\0';
return 0;
}
else if (col == fcol) {
// maybe fold, we have something in the overflow
if (ins[i] == '\n' || ins[i] == '\0') {
// don't fold, termination can stay in the overflow
outs[0] = '\0';
return 0;
}
else if (lnbi > 0 || (ins[0] != ' ' && ins[0] != '\t' && (ins[1] == ' '
|| ins[1] == '\t'))) {
// fold after the whitespace following the last non-blank char
foldat = lnbi+2;
}
else {
// fold at overflow
foldat = i;
}
}
else {
// col > fcol only possible if ins[i-1] == '\t' so we fold and place the
// tab on the next line
foldat = i-1;
}
// Fold
size_t j = 0, k;
// add a marker if we're folding after a non-blank char
if (ins[foldat-1] != ' ' && ins[foldat-1] != '\t') {
outs[j++] = ins[foldat-1];
ins[foldat-1] = '\\';
}
for (k = foldat; ins[k] != '\0'; ++j, ++k) {
outs[j] = ins[k];
}
outs[j] = '\0';
ins[foldat++] = '\n';
ins[foldat] = '\0';
return j;
}
/* continue reading a line into `s`, return total string length;
* the buffer must have free space for at least 1 more char
*/
size_t fillbuf(char s[], size_t sz)
{
// find end of string
size_t i;
for (i = 0; s[i] != '\0'; ++i) {
}
// not introduced in the book, but we could achieve the same by c&p
// getline code here
return i + getline(&s[i], sz-i);
}
/* getline: read a line into `s`, return string length;
* `sz` must be >1 to accomodate at least one character and string
* termination '\0'
*/
size_t getline(char s[], size_t sz)
{
int c;
size_t i = 0;
bool el = false;
while (i + 1 < sz && !el) {
c = getchar();
if (c == EOF) {
el = true; // note: `break` not introduced yet
}
else {
s[i] = (char) c;
++i;
if (c == '\n') {
el = true;
}
}
}
if (i < sz) {
if (c == EOF && !feof(stdin)) { // EOF due to read error
i = 0;
}
s[i] = '\0';
}
return i;
}
/* copy: copy a '\0' terminated string `from` into `to`;
* assume `to` is big enough;
*/
void copy(char * restrict to, char const * restrict from)
{
size_t i;
for (i = 0; from[i] != '\0'; ++i) {
to[i] = from[i];
}
to[i] = '\0';
}
</code></pre>
<h2>Testing</h2>
<h3>Output</h3>
<p><code>$ ./ch1-ex-1-22-02 <ch1-ex-1-22-02.c >out.txt</code></p>
<pre><code>/*
Exercise
1-22.
Write a
program
to "fold"
long
input
lines
into two
or more
*
shorter
lines
after the
last
non-blank
character
that
occurs
before
the n-th
* column
of input.
Make sure
your
program
does
something
intellige\
nt with
very
* long
lines,
and if
there are
no blanks
or tabs
before
the
specified
column.
*/
#include
<stdio.h>
#include
<stdbool.\
h>
#define
MAXTW
16
//
max. tab
width
#define
MAXFC
100
//
max. fold
column,
</code></pre>
<p>...</p>
<h3>Reversibility</h3>
<pre><code>$ ./ch1-ex-1-22-02 <ch1-ex-1-22-02.c | perl -p -e 's/(?<=\ )\n|(?<=\t)\n|\\\n//g' | diff - ch1-ex-1-22-02.c
</code></pre>
<p>returns nothing :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T11:44:36.570",
"Id": "400792",
"Score": "0",
"body": "`getline()` [UB in the pathological case sz == 1 as it tests uninitialized c with c == EOF](https://codereview.stackexchange.com/a/207498/29485)."
},
{
"ContentLicense":... | [
{
"body": "<p>Only a small review.</p>\n\n<blockquote>\n <p>Would you say this design approach is good?</p>\n</blockquote>\n\n<p>Yes. I did have trouble following the code though. I was not able to find a test that failed the coding goal.</p>\n\n<blockquote>\n <p>In the spirit of writing reusable code, shoul... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T12:59:11.343",
"Id": "207474",
"Score": "1",
"Tags": [
"beginner",
"c",
"strings",
"formatting",
"io"
],
"Title": "K&R Exercise 1-22. Fold (break) lines at specified column"
} | 207474 |
<p>I'm a newbie Python programmer and I just made my first script which allows autoclicking into various positions of the screen (3 for now) an X number of times with an Y interval.</p>
<p>I'd like to know what do you think about my code, specifically if there is a more efficient way to do the same task.</p>
<p>No need to extend functionalities and such. I'm just curious to hear what more experienced developers think.</p>
<pre><code>#import libraries
import pyautogui
from tkinter import *
import time
import subprocess
#settings
pyautogui.PAUSE = 1
pyautogui.FAILSAFE = True
pyautogui.size()
width, height = pyautogui.size()
initialStr = "Screen Size: " + str(width) +" - " +str(height)
print(initialStr)
x,y = pyautogui.position()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionStr)
# displays screen size
def function():
print(initialStr)
#saves mouse position 1
def position():
time.sleep(2)
global xmouse, ymouse
xmouse, ymouse = pyautogui.position()
print(str(xmouse)+","+str(ymouse))
w2 = Label(ro, text="Position 1 set: "+str(xmouse)+","+str(ymouse)).grid(row=2,columnspan=2)
#saves mouse position 2
def position2():
time.sleep(2)
global xmouse2, ymouse2
xmouse2, ymouse2 = pyautogui.position()
print(str(xmouse2)+","+str(ymouse2))
w3 = Label(ro, text="Position 2 set: "+str(xmouse2)+","+str(ymouse2)).grid(row=4,columnspan=2)
#saves mouse position 3
def position3():
time.sleep(2)
global xmouse3, ymouse3
xmouse3, ymouse3 = pyautogui.position()
print(str(xmouse3)+","+str(ymouse3))
w4 = Label(ro, text="Position 3 set: "+str(xmouse3)+","+str(ymouse3)).grid(row=6,columnspan=2)
#saves number of cycles
def sel():
selection = "Value = " + str(iterations.get())
label = Label(ro, text="Number of cycles: "+str(iterations.get())).grid(row=11,columnspan=2)
#saves execution interval
def sel2():
selection = "Value = " + str(parametro_timer.get())
label2 = Label(ro, text="Execution interval set at: "+str(parametro_timer.get())+" seconds").grid(row=14,columnspan=2)
#starts autoclicking
def gogo():
#checks for unset variables, if one or more are unset it returns an error
try:
xmouse,xmouse2,xmouse3
except NameError:
label_error = Label(ro, foreground="red", text="ERROR: Some parameters are not set").grid(row=16,columnspan=2)
#if all settings have been set then the program can start autoclicking
else:
time.sleep(2)
timer=int(parametro_timer.get())
parametro_range=int(iterations.get())
for i in range(0,parametro_range):
pyautogui.click(xmouse, ymouse)
time.sleep(timer)
pyautogui.click(xmouse2, ymouse2)
time.sleep(timer)
pyautogui.click(xmouse3, ymouse3)
time.sleep(timer)
#GUI
ro = Tk()
ro.wm_title("AutoClicker1.0")
#scale variables
iterations = DoubleVar()
parametro_timer = DoubleVar()
w1 = Label(ro, text=initialStr).grid(row=0,columnspan=2, pady=15)
w2 = Label(ro, text="Position 1 is unset").grid(row=2,columnspan=2)
w3 = Label(ro, text="Position 2 is unset").grid(row=4,columnspan=2)
w4 = Label(ro, text="Position 3 is unset").grid(row=6,columnspan=2)
button = Button(ro, text="Set Position 1 [2 seconds to hover into position]", command=position).grid(row=1,columnspan=2)
button = Button(ro, text="Set Position 2 [2 seconds to hover into position]", command=position2).grid(row=3,columnspan=2)
button = Button(ro, text="Set Position 3 [2 seconds to hover into position]", command=position3).grid(row=5,columnspan=2)
scale = Scale( ro, variable = iterations, orient=HORIZONTAL, from_=5, to=100 ).grid(row=9,columnspan=2)
button = Button(ro, text="Set number of cycles", command=sel).grid(row=10,columnspan=2)
label = Label(ro, text="Cycles are unset (Default=5)").grid(row=11,columnspan=2)
scale1 = Scale( ro, variable = parametro_timer, orient=HORIZONTAL, from_=2, to=15 ).grid(row=12,columnspan=2)
button = Button(ro, text="Set execution interval", command=sel2).grid(row=13,columnspan=2)
label2 = Label(ro, text="Execution interval is unset (Default=2)").grid(row=14,columnspan=2)
button = Button(ro, text="Start", command=gogo).grid(row=15,columnspan=2,padx=110,pady=5)
label_error = Label(ro, text="").grid(row=16,columnspan=2)
ro.mainloop()
</code></pre>
| [] | [
{
"body": "<h1>Review</h1>\n\n<h2>PEP 8</h2>\n\n<p>There are rules in Python, how you should format your code. If you want to write proper code, you should follow it: <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a></p>\n\n<h2>Use an... | {
"AcceptedAnswerId": "207762",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T14:47:12.027",
"Id": "207477",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"tkinter"
],
"Title": "Custom autoclick Python script"
} | 207477 |
<p>I made a program that converts between Celsius and Fahrenheit. Is there any way that I could make this code more efficient and cleaner?</p>
<pre><code>use std::io;
// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)
/**********Converts between Fahrenheit and Celsius*********/
fn main() -> () {
println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
let mut convert_type = String::new();
io::stdin().read_line(&mut convert_type)
.expect("Failed to conversion type.");
let t = String::from(convert_type);
println!("You want to convert to: {}", t);
println!("What temperature would you like to convert?");
let mut temp = String::new();
io::stdin().read_line(&mut temp)
.expect("Failed to read temperature.");
let temp: i32 = match temp.trim().parse() {
Ok(temp) => temp,
Err(_e) => {
-1
}
};
match t.as_str() {
"C\n" => println!("{}", ftoc(temp)),
"F\n" => println!("{}", ctof(temp)),
_ => println!("t = {:?}", t),
}
}
// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
(c * (9 / 5)) + 32
}
//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
(f-32) * (5 / 9)
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code> cargo run
Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
Finished dev [unoptimized + debuginfo] target(s) in 2.64s
Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
F
You want to convert to: F
What temperature would you like to convert?
0
32
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T15:53:38.333",
"Id": "400527",
"Score": "3",
"body": "Please use `rustfmt` the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code."
}
] | [
{
"body": "<p>The first thing I always do is running <code>clippy</code>.</p>\n\n<p>You will catch some things that are not neccessary, e.g. </p>\n\n<ul>\n<li><code>fn main() -> ()</code> can be reduced to <code>fn main()</code></li>\n<li><code>let t = String::from(convert_type);</code> is simply <code>let t... | {
"AcceptedAnswerId": "207483",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T15:38:08.007",
"Id": "207481",
"Score": "7",
"Tags": [
"rust",
"unit-conversion"
],
"Title": "Fahrenheit and Celsius converter in Rust"
} | 207481 |
<p>Is authentication implemented correctly? </p>
<p>At the entry point to the app, which is <code>App.js</code>, query the Django server, which responds whether the current user is authenticated after checking <code>request.user.isAuthenticated</code></p>
<p>I am not using <code>redux</code>, just storing authentication state in a local object (this can't be tampered with I assume?). This is reset on signout and I guess it is also lost and re-queried whenever the app is reloaded.</p>
<p>All app routes except the login route are behind <code>PrivateRoute</code>, which will redirect to login unless <code>myAuth.isAuthenticated === true</code>.</p>
<p>Any additional comments welcome.</p>
<p>App.js</p>
<pre><code>import React, {Component} from "react";
import ReactDOM from "react-dom";
import MainContainer from "../containers/MainContainer";
import {Provider} from "react-redux";
import store from "../store";
import BrowserRouter from "react-router-dom/es/BrowserRouter";
import {Redirect, Route, Switch} from "react-router-dom";
import LoginPage from "./LoginPage";
import myAuth from "../myAuth";
import {APP_LOGIN_PATH} from "../constants/paths";
class App extends Component {
state = {
loaded: false,
};
componentDidMount() {
myAuth.authenticate(() => this.setState({
loaded: true,
}))
}
render() {
const { loaded } = this.state;
return (
loaded ? (
<BrowserRouter>
<Switch>
<Route path={ APP_LOGIN_PATH } component={ LoginPage } />
<PrivateRoute path="/app" component={ MainContainer } />
</Switch>
</BrowserRouter>
) : (
<div>Loading...</div>
)
)
}
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
myAuth.isAuthenticated === true
? <Component {...props} />
: <Redirect to={{ pathname: APP_LOGIN_PATH, state: { from: props.location }}} />
)} />
);
const wrapper = document.getElementById("app");
wrapper ? ReactDOM.render(
<Provider store={ store }>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
, wrapper) : null;
</code></pre>
<p>myAuth.js</p>
<pre><code>const myAuth = {
isAuthenticated: false,
isStaff: false,
isSuperuser: false,
authenticate(cb) {
console.log("authenticate");
fetch("/session_user/")
.then(response => {
if (response.status !== 200) {
console.log("Something went wrong during authentication");
}
return response.json();
})
.then(data => {
this.isAuthenticated = data.isAuthenticated;
this.isStaff = data.isStaff;
this.isSuperuser = data.isSuperuser;
})
.then(cb)
},
signout(cb) {
fetch("/logout/")
.then(response => {
if (response.status !== 200) {
console.log("Something went wrong while logging out");
}
})
.then(data => {
this.isAuthenticated = false;
this.isStaff = false;
this.isSuperuser = false;
})
}
};
export default myAuth;
</code></pre>
| [] | [
{
"body": "<p>The client-side data can definitely be tampered with so you should not rely on that for security.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-25T16:43:23.017",
"Id": "531422",
"Score": "0",
"body": "Can you be... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T16:00:11.183",
"Id": "207485",
"Score": "1",
"Tags": [
"authentication",
"react.js",
"django",
"jsx"
],
"Title": "React + Django (session) authentication"
} | 207485 |
<p>I feel like the title is a bit wordy. What I have defined here is a function that takes two parameters: </p>
<ul>
<li>a list that contains valued sorted from smallest to biggest</li>
<li>a number to insert at the right index so that the returned list print its values from smallest to biggest</li>
</ul>
<p><strong>NOTE:</strong> Recursion is mandatory</p>
<pre><code>def insert(lst, to_insert):
"""
parameters : lst of type list, that contains values sorted from smallest to largest;
to_insert : represents a value
returns : same list with the to_insert value positioned at the right index
in order for the list to remain sorted from smallest to largest;
"""
if len(lst) == 1:
return []
if lst[0] < to_insert and to_insert < lst[1]:
lst[3] = to_insert
return [lst[0]] + [lst[3]] + insert(lst[1:], to_insert)
else:
return [lst[0]] + insert(lst[1:], to_insert)
print(insert([1,2,3,4,5,7,8,9], 6))
</code></pre>
<p>The list outputs the following : </p>
<pre><code>[1,2,3,4,5,6,7,8] #not sure where 9 got left
</code></pre>
<p>How do I optimize this function, using only simple functions.</p>
| [] | [
{
"body": "<p>Recursion is usually a poor choice in Python. Non-tail recursion is usually a poor choice in any language (and this is non-tail because we apply <code>+</code> to the result before returning it).</p>\n\n<p>It's better to use the standard <code>bisect</code> module to find (once) the correct index... | {
"AcceptedAnswerId": "207492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T16:49:12.253",
"Id": "207488",
"Score": "3",
"Tags": [
"python",
"sorting",
"recursion"
],
"Title": "Insert a number in a sorted list and return the list with the number at the correct index"
} | 207488 |
<p>I have to create a custom table (like a pivot table), where users can find immediately the total of items, and when clicking on data, get the <code>db</code> page correctly filtered.</p>
<p>My code works fine, but continuous improvement pushes me to look for more efficient code.</p>
<p>Thanks for every contributes.</p>
<pre><code>Sub AddTab1(ByVal c As Integer, str As String)
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim dbSh As Worksheet, tabSh As Worksheet
Dim ini As Date, fin As Date, tmp As Date, s As Range
Set dbSh = Sheets("db_Out")
Set tabSh = Sheets("Tab")
Dim arrTab(), rng As Range, i As Integer, cl As Range
Dim colIndex As Long, lrw As Integer, lcl As Integer
Dim firstCell As Range
Dim lastCell As Range
ini = Now()
If dbSh.Cells(2, c) = vbNullString Then MsgBox "Non ci sono dati valorizzati da estrapolare", vbInformation, "Cf_utility.info": Exit Sub
tabSh.Select
With tabSh
Set s = Range(str)
s.Select
If s.Offset(1) = vbNullString Then GoTo continue
s.Select
lrw = Columns(s.Column).Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row 'Selection.End(xlDown).row
lcl = Selection.End(xlToRight).Column
s.Offset(1).Select
.Range(Selection, Cells(lrw, lcl)).ClearContents
s.Offset(2).Select
.Range(Selection, Cells(lrw, lcl)).Select
Selection.Delete Shift:=xlUp
s.Offset(1).Select
End With
continue:
With dbSh
.AutoFilterMode = False
.Cells.EntireColumn.Hidden = False
Set firstCell = .Cells(2, c)
Set lastCell = .Cells(.Rows.Count, c).End(xlUp)
Set rng = .Range(firstCell, lastCell)
rng.Copy
End With
tabSh.Select
s.Offset(1).Select
ActiveSheet.Paste
Application.CutCopyMode = False
tabSh.Sort.SortFields.Clear
tabSh.Sort.SortFields.Add key:=s, _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With tabSh.Sort
.SetRange Range(s.Offset(1), Cells(Columns(s.Column).Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row, s.Column))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
s.Select
s.Offset(1).Select
Set rng = Range(Selection, Cells(Columns(s.Column).Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row, s.Column))
rng.RemoveDuplicates Columns:=1, Header:=xlNo
'KPI2-1 (Prelievo)
s.Select
lrw = Selection.End(xlDown).row
lcl = Selection.End(xlToRight).Column
ReDim arrTab(4 To lrw, 1 To lcl - 1)
s.Offset(1).Select
Set rng = Range(Selection, Selection.End(xlDown))
'c = D_KPI2_1 'Kpi KPI2_1
For Each cl In rng.Cells
arrTab(cl.row, 2) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "STD", dbSh.Columns(V_KPI2_1), 0.9) + WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "STD", dbSh.Columns(V_KPI2_1), 1)
If Not arrTab(cl.row, 2) > 0 Then arrTab(cl.row, 2) = Empty
arrTab(cl.row, 3) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "STD", dbSh.Columns(V_KPI2_1), "Out of KPI")
If Not arrTab(cl.row, 3) > 0 Then arrTab(cl.row, 3) = Empty
arrTab(cl.row, 4) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "STD", dbSh.Columns(V_KPI2_1), "Backlog")
If Not arrTab(cl.row, 4) > 0 Then arrTab(cl.row, 4) = Empty
arrTab(cl.row, 5) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "PRIORITY", dbSh.Columns(V_KPI2_1), 0.95) + WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "PRIORITY", dbSh.Columns(V_KPI2_1), 1)
If Not arrTab(cl.row, 5) > 0 Then arrTab(cl.row, 5) = Empty
arrTab(cl.row, 6) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "PRIORITY", dbSh.Columns(V_KPI2_1), "Out of KPI")
If Not arrTab(cl.row, 6) > 0 Then arrTab(cl.row, 6) = Empty
arrTab(cl.row, 7) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "PRIORITY", dbSh.Columns(V_KPI2_1), "Backlog")
If Not arrTab(cl.row, 7) > 0 Then arrTab(cl.row, 7) = Empty
arrTab(cl.row, 8) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "AOG", dbSh.Columns(V_KPI2_1), 1)
If Not arrTab(cl.row, 8) > 0 Then arrTab(cl.row, 8) = Empty
arrTab(cl.row, 9) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "AOG", dbSh.Columns(V_KPI2_1), "Out of KPI")
If Not arrTab(cl.row, 9) > 0 Then arrTab(cl.row, 9) = Empty
arrTab(cl.row, 10) = WorksheetFunction.CountIfs(dbSh.Columns(c), cl.Value, dbSh.Columns(TypeTra), "AOG", dbSh.Columns(V_KPI2_1), "Backlog")
If Not arrTab(cl.row, 10) > 0 Then arrTab(cl.row, 10) = Empty
For i = 2 To 10
arrTab(cl.row, 1) = arrTab(cl.row, 1) + arrTab(cl.row, i)
Next
If arrTab(cl.row, 1) < 1 Then arrTab(cl.row, 1) = Empty
Next
Range(s.Offset(1, 1), Cells(lrw, s.Offset(, 10).Column)) = arrTab()
s.Select
StartCl
lcl = Selection.End(xlToRight).Column
lrw = Selection.End(xlDown).row
Range(Selection.Offset(1), Selection.Offset(1, 11)).Select
Selection.Copy
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
s.Select
CleanTab
s.Select
InsLink
fin = Now()
tmp = fin - ini
Debug.Print tmp
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
</code></pre>
<p>My english is maybe not perfectly understandable, so here is a image</p>
<p>fabrizio</p>
<p><a href="https://i.stack.imgur.com/JNm8g.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JNm8g.jpg" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T17:54:30.287",
"Id": "400544",
"Score": "1",
"body": "I'm afraid to tell you that [this subject doesn't have much success](https://codereview.stackexchange.com/questions/tagged/vba#) on Stack Exchange. Hope you'll get a solution."
... | [
{
"body": "<p>A couple quick house-keeping issues first:</p>\n\n<ul>\n<li>Get rid of your old commented out code - it's simply adding noise.</li>\n<li><p>Your indentation is inconsistent. I had to <a href=\"http://rubberduckvba.com/Indentation\" rel=\"noreferrer\">run this through an indenter</a> before I could... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T16:52:23.333",
"Id": "207489",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Retrieve data from table with criteria"
} | 207489 |
<p>I have used Enum objects before in PHP as shown <a href="https://stackoverflow.com/questions/254514/php-and-enums">here</a>.</p>
<p>However, I often find it's a requirement to have further attributes or metadata available on the instances.</p>
<p>I came up with the example solution below:</p>
<pre><code><?php
class Month {
const January = 1;
const February = 2;
const March = 3;
const April = 4;
const May = 5;
const June = 6;
const July = 7;
const August = 8;
const September = 9;
const October = 10;
const November = 11;
const December = 12;
protected $value;
protected static $metadata = [
1 => ['days_in_month' => 31],
2 => ['days_in_month' => 28],
3 => ['days_in_month' => 31],
4 => ['days_in_month' => 30],
5 => ['days_in_month' => 31],
6 => ['days_in_month' => 30],
7 => ['days_in_month' => 31],
8 => ['days_in_month' => 31],
9 => ['days_in_month' => 30],
10 => ['days_in_month' => 31],
11 => ['days_in_month' => 30],
12 => ['days_in_month' => 31]
];
public function __construct($value)
{
$this->value = $value;
}
public function __get($name)
{
if (array_key_exists($name, static::$metadata[$this->value])) {
return static::$metadata[$this->value][$name];
}
}
}
$month = new Month(Month::February); // Returns Month instance
$month->days_in_month; // Returns 28 (for February)
</code></pre>
<p>Obviously the metadata array can be expanded to include further attributes that should be available for each enumerable option. And of course this need to throw exceptions / handle problems.</p>
<p>Feedback appreciated. Is there a better way to have an Enumerable-type approach which can include additional attributes?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T17:32:38.683",
"Id": "400538",
"Score": "0",
"body": "What are you using this for, where April to December aren't needed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T17:44:58.443",
"Id": "4005... | [
{
"body": "<p>February doesn't necessarily have 28 days. In some years, it has 29 days. This code produces the wrong answer for around ¼ of Februaries.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-21T11:33:35.6... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T16:54:55.320",
"Id": "207490",
"Score": "-1",
"Tags": [
"php",
"enum"
],
"Title": "Adding additional attributes to an Enum object"
} | 207490 |
<h1>Assumptions</h1>
<p>Basically, a Connection class has a "Disconnect" event. Subscribing to this event isn't thread-safe, because the disconnection may fire from another thread right before I subscribe. So checking before the subscription doesn't help.</p>
<p>Checking for the disconnect after subscription doesn't help either because the event may have fired in the meanwhile (2 threads might execute the same "observer" twice).</p>
<h1>(My) Solution:</h1>
<p>An event always fired once (and only once), even if the event itself already happened before Source is on <a href="https://github.com/CaptainOachkatzl/XSLibrary/blob/master/XSThreadSafety/Events/OneShotEvent.cs" rel="nofollow noreferrer">GitHub</a> as well.</p>
<h1>Questions:</h1>
<p>Are there other simpler solutions addressing this? (by <em>simpler</em> I mean from an outside or usage perspective)</p>
<p>Do you see any race conditions or things that could go wrong?</p>
<p>Maybe you have optimizations or simplifications to add?</p>
<p>Input is highly appreciated!</p>
<pre><code>/// <summary>
/// Triggers if the event is invoked or was invoked before subscribing to it.
/// <para> Can be accessed safely by multiple threads.</para>
/// </summary>
public class AutoInvokeEvent<Sender, Args>
{
public delegate void EventHandle(Sender sender, Args arguments);
/// <summary>
/// Handle will be invoked if the event was triggered in the past.
/// <para>Unsubscribing happens automatically after the invocation and is redundant if done from the event handle.</para>
/// </summary>
public event EventHandle Event
{
add
{
if (!Subscribe(value))
value(m_sender, m_eventArgs);
}
remove { InternalEvent -= value; }
}
private event EventHandle InternalEvent;
// this is my personal lock implementation. in this case it is used like any other lock(object) so just ignore it
private SafeExecutor m_lock = new SingleThreadExecutor();
private volatile bool m_invoked = false;
Sender m_sender;
Args m_eventArgs;
/// <summary>
/// Invokes all subscribed handles with the given parameters.
/// <para>All calls after the first are ignored.</para>
/// </summary>
public void Invoke(Sender sender, Args args)
{
GetEventHandle(sender, args)?.Invoke(m_sender, m_eventArgs);
}
private EventHandle GetEventHandle(Sender sender, Args args)
{
return m_lock.Execute(() =>
{
if (m_invoked)
return null;
m_sender = sender;
m_eventArgs = args;
m_invoked = true;
EventHandle handle = InternalEvent;
InternalEvent = null;
return handle;
});
}
/// <returns>Returns true if subscription was successful and false if handle needs to be invoked immediately.</returns>
private bool Subscribe(EventHandle handle)
{
return m_lock.Execute(() =>
{
if (!m_invoked)
InternalEvent += handle;
return !m_invoked;
});
}
}
</code></pre>
<h2>How the class could be used :</h2>
<pre><code>class Connection
{
public AutoInvokeEvent<object, EndPoint> OnDisconnect = new AutoInvokeEvent<object, EndPoint>();
public Disconnect()
{
OnDisconnect.Invoke(this, endpoint);
}
}
void main()
{
Connection connection = new Connection();
connection.OnDisconnect.Event += DoStuffOnDisconnect;
}
void DoStuffOnDisconnect(object sender, EndPoint endpoint) { }
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T20:34:16.017",
"Id": "400572",
"Score": "0",
"body": "What do you need this actually for? I cannot come up with any use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T21:06:48.737",
"Id": "... | [
{
"body": "<h1>Thread safety</h1>\n\n<p>Both <code>Subscribe</code> and <code>GetEventHandle</code> use lock and <a href=\"https://stackoverflow.com/questions/22534462/c-sharp-is-it-thread-safe-to-subscribe-same-event-handler-for-all-objects\">and+remove on field event are thread-safe too</a>. You can even remo... | {
"AcceptedAnswerId": "208131",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T17:43:06.223",
"Id": "207494",
"Score": "7",
"Tags": [
"c#",
"multithreading",
"thread-safety",
"event-handling",
"observer-pattern"
],
"Title": "Threadsafe oneshot-event which fires on subscription if the event was fired in the past"
} | 207494 |
<h2>Story:</h2>
<p>I build a kind of labyrinth. This labyrinth is divided in seven steps. You start with the first, then second, and so on to the seventh. You cannot go back to a previous step. Each step contains 3 to 5 rooms. Every room of a step is connected to at least one room of the next step. As well, every room of a step is connected to at least one room of the previous one. No <em>hallway</em> (connection between rooms) can cross another <em>hallway</em>. No room can have more than 3 source-rooms, neither more than 3 destination-rooms.</p>
<h2>Implementation:</h2>
<p>My point is to create a <em>matrix</em> (two-dim array) which depict the connection of a step to its successor. Rows represent the rooms of the <em>source</em> step, and columns the <em>destination</em> step. As I want to practice it, F# is required.</p>
<h2>Decisions:</h2>
<p>The <em>matrix</em> will only contains 3 values:<br>
- <code>M[i,j] = 1</code> means that source-room #<code>i</code> is connected to destination-room #<code>j</code><br>
- <code>M[i,j] = 0</code> means that source-room can not be connected to destination-room<br>
- <code>M[i,j] = -1</code> means that source-room can be connected (but is not) to destination-room</p>
<h2>Constraints:</h2>
<ol>
<li>Because <em>hallways</em> cannot be crossed, first source-room is imperatively connected to the first destination-room ; same for last rooms. </li>
<li>Because rooms can not have more than three destination-room, the first source-room can only be connected to the three first destination-rooms, and the last destination-room can only be connected to the three last source-rooms.</li>
</ol>
<h2>Code:</h2>
<pre><code>module MapConnections =
let IsUncertain array row col =
Array2D.get array row col = -1
let IsDisconnected array row col =
Array2D.get array row col = 0
let IsConnected array row col =
Array2D.get array row col = 1
let ListUncertain array =
let mutable list : (int*int) list = list.Empty
for i in 0 .. Array2D.length1 array - 1 do
for j in 0 .. Array2D.length2 array - 1 do
if IsUncertain array i j then
list <- list @ [(i,j)]
list
let ListDisconnected array =
let mutable list : (int*int) list = list.Empty
for i in 0 .. Array2D.length1 array - 1 do
for j in 0 .. Array2D.length2 array - 1 do
if IsDisconnected array i j then
list <- list @ [(i,j)]
list
let ListConnected array =
let mutable list : (int*int) list = list.Empty
for i in 0 .. Array2D.length1 array - 1 do
for j in 0 .. Array2D.length2 array - 1 do
if IsConnected array i j then
list <- list @ [(i,j)]
list
let CountUncertain array =
ListUncertain array |> Seq.length<int*int>
let CountDisconnection array =
ListDisconnected array |> Seq.length<int*int>
let CountConnection array =
ListConnected array |> Seq.length<int*int>
let Disconnect array row col =
if IsUncertain array row col then
Array2D.set array row col 0
IsDisconnected array row col
// Check no-cross rule
let Connect array row col =
if IsUncertain array row col then
Array2D.set array row col 1
// Disconnect all 'top-right' connections
for i in 0 .. row - 1 do
for j in col + 1 .. Array2D.length2 array - 1 do
Disconnect array i j |> ignore
// Disconnect all 'bottom-left' connections
for i in row + 1 .. Array2D.length1 array - 1 do
for j in 0 .. col - 1 do
Disconnect array i j |> ignore
IsConnected array row col
// Check no-more-than-three rule
let Create rows cols =
let matrix = Array2D.create rows cols -1
Connect matrix 0 0 |> ignore
Connect matrix (rows - 1) (cols - 1) |> ignore
for i in 3 .. rows - 1 do
Disconnect matrix i 0 |> ignore
for i in 0 .. rows - 4 do
Disconnect matrix i (cols - 1) |> ignore
for j in 3 .. cols - 1 do
Disconnect matrix 0 j |> ignore
for j in 0 .. cols - 4 do
Disconnect matrix (rows - 1) j |> ignore
matrix
</code></pre>
<h2>What I want to be sure:</h2>
<p>I want to follow the F# conventions. For example, if lists are non-mutable, I presume that a <code>mutable list</code> is something to avoid?</p>
| [] | [
{
"body": "<p>I'm not sure, I understand what the purpose of your code is, so here are some general thoughts:</p>\n\n<hr>\n\n<p>You have 3 identical functions except for a predicate:</p>\n\n<blockquote>\n<pre><code>let ListUncertain array =\n let mutable list : (int*int) list = list.Empty\n for i in 0 ..... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T17:52:45.893",
"Id": "207497",
"Score": "2",
"Tags": [
"beginner",
"f#"
],
"Title": "Connect elements of a list to elements of an other list using a two-dim array"
} | 207497 |
<p>In my <a href="https://codereview.stackexchange.com/questions/204827/generate-multi-dimensional-maze-with-borders-and-fixed-degree-on-each-node-type">previous post</a> I made rather dull (and, as it turns out, bluntly wrong) attempt at solving the <strong>problem:</strong></p>
<hr />
<blockquote>
<p>Generate a maze with <span class="math-container">\$N\$</span> nodes, <span class="math-container">\$K<N\$</span> of which are border nodes. Each border must have degree of <span class="math-container">\$m\$</span>, and each non-border node must have degree of <span class="math-container">\$p>m\$</span>. The generated maze must be a minimally connected graph. Duplicating edges is not allowed (each pair of nodes can have only zero or one edge).</p>
</blockquote>
<hr />
<h2>Algorithm:</h2>
<p>My algorithm generates disconnected nodes first, sorted by their indices. Memory for neighbor indices is managed semi-manually, because <em>I believe</em> that on smaller neighbor count standard memory allocator becomes less efficient (to be checked). Satisfied nodes are the ones which have required number of edges in place.</p>
<p>-1. head <- first of nodes</p>
<p>-2. while head is not at end of nodes:</p>
<p>---2.1. neighbor <- last element of nodes</p>
<p>---2.2. while *head is not satisfied</p>
<p>-----2.2.1. connect *head and *neighbor</p>
<p>-----2.2.2. advance neighbor towards head (decrement)</p>
<p>---2.3. if *head is not satisfied, return empty maze</p>
<p>---2.4. Advance head towards end</p>
<p>---2.5. Sort range [head, end of nodes) (comparison function below)</p>
<p>-3. Return built maze</p>
<p>When comparing, it is important to put <em>the most constraining</em> nodes first. It will allow to exit early if the maze is impossible to generate. The most constraining node is a node which has more fill percentage (<span class="math-container">\$\frac{Current}{Required}\$</span>).</p>
<p>Note that instead of doing division, I do multiplication:</p>
<p><span class="math-container">\$\frac{Current1}{Required1}<\frac{Current2}{Required2}\$</span></p>
<p>is the same as</p>
<p><span class="math-container">\$Current1*Required2<Current2*Required1\$</span></p>
<hr />
<h2>What is different compared to previous solution?</h2>
<p>Well, <em>everything</em>. I believe I included all suggestions by <a href="https://codereview.stackexchange.com/users/39848/edward">@Edward</a>, but there might be some incompatibilities, due to the fact that algorithm is very different.</p>
<p>This solution won't break a sweat on 100'000 edges, but performance heavily depends on the node count, as the sorting step is the most time-consuming. It also doesn't duplicate edges, and doesn't crash due to stackoverflow, and is better in many other ways from end user's perspective. But the code is ... well, it is in the concerns section.</p>
<hr />
<h2>Code</h2>
<pre><code>#ifndef MAZE_GENERATOR_MAZE_HPP
#define MAZE_GENERATOR_MAZE_HPP
#include <algorithm>
#include <cstddef>
#include <vector>
#include <memory>
#include <optional>
class maze {
public:
struct node {
std::size_t index = 0;
std::size_t* neighbor_indices = nullptr;
std::size_t filled_count = 0;
};
private:
std::vector<node> nodes;
std::unique_ptr<std::size_t[]> neighbors_storage;
maze() = default;
maze(std::vector<node>&& nodes, std::unique_ptr<std::size_t[]>&& neighbors_storage):
nodes(std::move(nodes)),
neighbors_storage(std::move(neighbors_storage)) {}
public:
class maze_builder {
std::size_t _node_count;
std::size_t _border_count;
std::size_t _border_edge_count;
std::size_t _nonborder_edge_count;
public:
maze_builder& of_size(std::size_t node_count) {
_node_count = node_count;
return *this;
}
maze_builder& with_borders(std::size_t border_count, std::size_t border_edge_count) {
_border_count = border_count;
_border_edge_count = border_edge_count;
return *this;
}
maze_builder& with_typical_nodes(std::size_t nonborder_edge_count) {
_nonborder_edge_count = nonborder_edge_count;
return *this;
}
std::optional<maze> try_build() {
return maze::try_build(_node_count, _border_count, _border_edge_count, _nonborder_edge_count);
}
};
const std::vector<node>& get_nodes() const {
return nodes;
}
static std::optional<maze> try_build(std::size_t node_count, std::size_t border_count,
std::size_t border_edge_count, std::size_t nonborder_edge_count) {
auto is_border_index = [border_count](std::size_t index) {return index < border_count;};
auto is_satisfied = [border_edge_count, nonborder_edge_count, is_border_index](node& n) {
if (is_border_index(n.index)) {
return n.filled_count == border_edge_count;
} else {
return n.filled_count == nonborder_edge_count;
}
};
auto is_over_satisfied = [border_edge_count, nonborder_edge_count, is_border_index](node& n) {
if (is_border_index(n.index)) {
return n.filled_count > border_edge_count;
} else {
return n.filled_count > nonborder_edge_count;
}
};
auto node_cmp = [is_border_index, border_edge_count, nonborder_edge_count](const node& lhs, const node& rhs) {
bool is_lhs_border = is_border_index(lhs.index);
bool is_rhs_border = is_border_index(rhs.index);
auto required_lhs = is_lhs_border ? border_edge_count : nonborder_edge_count;
auto required_rhs = is_rhs_border ? border_edge_count : nonborder_edge_count;
return lhs.filled_count * required_rhs > rhs.filled_count * required_lhs;
};
std::vector<node> nodes(node_count);
const std::size_t nonborder_count = nodes.size() - border_count;
const std::size_t total_neighbor_count =
nonborder_count * nonborder_edge_count + border_count * border_edge_count;
auto neighbors_storage = std::make_unique<std::size_t[]>(total_neighbor_count);
std::size_t* storage = neighbors_storage.get();
for (std::size_t i = 0; i < nodes.size(); ++i) {
nodes[i].index = i;
nodes[i].neighbor_indices = storage;
storage += (is_border_index(i)) ?
border_edge_count :
nonborder_edge_count;
}
auto head = nodes.begin();
while (head != nodes.end()) {
auto neighbor = std::prev(nodes.end());
while (neighbor != head && !is_satisfied(*head)) {
if (is_over_satisfied(*neighbor)) {
throw std::logic_error("oversatisfied node found");
}
add_edge(*head, *neighbor);
--neighbor;
}
if (!is_satisfied(*head)) {
return {};
}
++head;
std::sort(head, nodes.end(), node_cmp);
}
std::sort(nodes.begin(), nodes.end(), [](const node& lhs, const node& rhs) {
return lhs.index < rhs.index;
});
std::optional<maze> result;
result = maze(std::move(nodes), std::move(neighbors_storage));
return result;
}
maze_builder builder() {
return {};
}
private:
static void add_edge(node& from, node& to) {
from.neighbor_indices[from.filled_count++] = to.index;
to.neighbor_indices[to.filled_count++] = from.index;
}
};
#endif //MAZE_GENERATOR_MAZE_HPP
</code></pre>
<pre><code>#include <unordered_set>
#include <chrono>
#include <iostream>
#include <queue>
void add_all_neighbors(std::queue<std::size_t>& to_visit, const maze::node& node) {
for (std::size_t i = 0; i < node.filled_count; ++i) {
to_visit.push(node.neighbor_indices[i]);
}
}
bool is_minimally_connected(const maze& m) {
const auto& nodes = m.get_nodes();
std::vector<char> visited(nodes.size());
visited[0] = true;
std::queue<std::size_t> to_visit;
add_all_neighbors(to_visit, nodes[0]);
while (!to_visit.empty()) {
auto visit_target = to_visit.front();
to_visit.pop();
if (visited[visit_target]) {
continue;
}
visited[visit_target] = true;
add_all_neighbors(to_visit, nodes[visit_target]);
}
return std::all_of(visited.begin(), visited.end(), [](char flag){return flag;});
}
bool repeats_connections(const maze& m) {
const auto& nodes = m.get_nodes();
for (const auto& node: nodes) {
std::unordered_set<std::size_t> unique_indices;
for (std::size_t i = 0; i < node.filled_count; ++i) {
unique_indices.insert(node.neighbor_indices[i]);
}
if (unique_indices.size() != node.filled_count) {
return true;
}
}
return false;
}
int main(int argc, char* argv[]) {
if (argc != 5) {
std::cerr << "usage: program node_count border_count border_edge_count non_border_edge_count "
<< '\n';
return -1;
}
std::size_t node_count = std::stoul(argv[1]);
std::size_t border_count = std::stoul(argv[2]);
std::size_t border_edge_count = std::stoul(argv[3]);
std::size_t non_border_edge_count = std::stoul(argv[4]); //sometimes also referred as just node edge count
namespace ch = std::chrono;
auto start_time = ch::system_clock::now();
auto solution = maze::try_build(node_count, border_count, border_edge_count, non_border_edge_count);
auto end_time = ch::system_clock::now();
if (solution.has_value()) {
std::cout << "found!\n";
if (!is_minimally_connected(solution.value())) {
std::cout << "false positive, maze is not minimally connected\n";
}
if (repeats_connections(solution.value())) {
std::cout << "false positive, some nodes duplicate connections\n";
}
} else {
std::cout << "not found!\n";
}
std::cout << "completed in "
<< ch::duration_cast<ch::milliseconds>(end_time - start_time).count() << " milliseconds\n";
}
</code></pre>
<hr />
<h2>Concerns</h2>
<ul>
<li><p>Too many lambdas hanging around</p>
<p>They can't be static functions, as they require current arguments. I thought about using javascript style function that returns a lambda which stores current state, but it looked weird.</p>
</li>
<li><p>Unusable interface</p>
<p>I tried to change it in some places, but in the end I end up either not being able to have necessary control (create, access all nodes), or unable to test the code. At the moment testing the code is very hard and requires intrusion.</p>
</li>
</ul>
<p>Any other comments are welcome!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T19:59:30.523",
"Id": "400568",
"Score": "0",
"body": "If you find the algorithm or any other part of the post ambiguous, please let me know. Feel free to make any suggestions about improving the post."
},
{
"ContentLicense":... | [
{
"body": "<pre><code>std::size_t node_count = std::stoul(argv[1]);\n</code></pre>\n\n<p>I agree with the commenter who said (more or less) \"don't write <code>std::size_t</code> when <code>size_t</code> will do.\" And I'll go further, and point out that most of your uses of <code>size_t</code> are unnecessary.... | {
"AcceptedAnswerId": "208810",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T19:19:00.153",
"Id": "207501",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"graph",
"c++17"
],
"Title": "Generating maze for complicated Hunt the Wumpus game"
} | 207501 |
<p>In carryless multiplication the partial products are XORed (ie addition without carry) together rather than added normally. The partial products themselves are still the product of a power of two (namely a bit extracted from one operand) and the other operand. For a multiplication by a power of two there is no difference between carryless multiplication and regular multiplication, so this step can be done with a normal multiplication. But then in JavaScript the question arises, which multiplication? It could be written like this:</p>
<pre><code>function clmul_u32(a, b) {
var prod = 0;
while (a != 0) {
prod ^= Math.imul(b, a & -a);
a &= a - 1;
}
return prod;
}
</code></pre>
<p>Using <code>Math.imul</code> is correct by definition, so no problems there.</p>
<p>Or it could be written like this:</p>
<pre><code>function clmul_u32(a, b) {
var prod = 0;
while (a != 0) {
prod ^= b * (a & -a);
a &= a - 1;
}
return prod;
}
</code></pre>
<p>This version avoids <code>Math.imul</code>, which I am often told to "avoid or polyfill", but it is less clear why this version should work. Multiplication by a power of two is actually safe, it cannot mangle the integer part of significand unlike multiplication by values that have simultaneously a low number of leading zeroes and a low number of trailing zeroes. I feel like if I used this version, I would have to write a long-winded comment justifying its correctness. </p>
<p>So which way should I go? Or perhaps there are better ways entirely?</p>
| [] | [
{
"body": "<h2>Question 1</h2>\n<blockquote>\n<p><em>So which way should I go?</em></p>\n</blockquote>\n<p>That depends on what is the assessment criteria. Three basic criteria are performance, readability and ease of use.</p>\n<h3>Readability</h3>\n<p>That depends on the reader. Knowing that bitwise operators ... | {
"AcceptedAnswerId": "207552",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T20:08:15.460",
"Id": "207504",
"Score": "0",
"Tags": [
"javascript",
"comparative-review",
"bitwise"
],
"Title": "Implementing carryless multiplication using normal multiplication"
} | 207504 |
<p>I have a simple function that reads character by character from stdin, while resizing the buffer whenever needed. The implementation will only allow 256 characters to be read, but that can easily be modified. Are there an obvious problems with this function? ie. it relies on undefined behaviour. And how can performance be improved?</p>
<pre><code>void scan(char **buffer) {
char *newBuffer;
unsigned char i = 0;
unsigned char size = 1;
*buffer = malloc(16);
(*buffer)[0] = 0;
while (1) {
(*buffer)[i] = getchar();
if ((*buffer)[i] == '\n') {
(*buffer)[i] = 0;
return;
}
if (i >= (size * 16)) {
size++;
newBuffer = realloc(*buffer, size * 16);
*buffer = newBuffer;
}
i++;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T08:32:25.470",
"Id": "400622",
"Score": "0",
"body": "It seems that (if your `UCHAR_MAX` is 255) this implementation will support reading of **4080** characters, not 256."
}
] | [
{
"body": "<ul>\n<li><p><strong><code>realloc</code></strong> may fail. In that case, <code>*buffer = newBuffer;</code> without checking would result in a memory leak. Consider</p>\n\n<pre><code> if (newBuffer) {\n *buffer = newBuffer;\n } else {\n handle_error_as_appropriate;\n }\n</code... | {
"AcceptedAnswerId": "207541",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T22:20:32.037",
"Id": "207513",
"Score": "1",
"Tags": [
"beginner",
"c"
],
"Title": "Automatically scan and resize buffer in C"
} | 207513 |
<p>I had this idea not to long ago on creating a secure chat for people who need to be not meddled with when talking (like whistleblowers, hackers, etc) talking to one of my friends about it he said I could use the <a href="https://inventwithpython.com/hacking/chapter22.html" rel="nofollow noreferrer">One Time Pad Cipher</a>, so I decided to write my own in Python. </p>
<p>If you don't know what the one time pad is, in a <em>nutshell</em> it's a cipher that generates a key for you that is as long as the string you pass to it, this key makes it <em>theoretically</em> impossible to crack the cipher without the key itself, due to their being so many possible combinations.</p>
<p>My cipher uses <code>sqlite</code> to store a database into memory to keep the keys unique, once the program is exited, the database is destroyed (theoretically). I would like someone to poke as many holes in this as possible, I would like to see if the string is possible to be cracked and would also like someone to break the database if possible. Basically I want to know how secure this is. Please keep in mind, this is not a finished product but just a fundamental understanding to a larger project. So critique away and have fun with it, thank you!</p>
<p>The code:</p>
<pre><code>import random
import string
import sqlite3
PUNC = string.punctuation
ALPHABET = string.ascii_letters
def initialize():
"""
initialize the database into memory so that it can be wiped upon exit
"""
connection = sqlite3.connect(":memory:", isolation_level=None, check_same_thread=False)
cursor = connection.cursor()
cursor.execute(
"CREATE TABLE used_keys ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"key TEXT"
")"
)
return cursor
def create_key(_string, db_cursor):
"""
create the key from a provided string
"""
retval = ""
set_string = ""
used_keys = db_cursor.execute("SELECT key FROM used_keys")
id_number = len(used_keys.fetchall()) + 1
for c in _string:
if c in PUNC:
c = ""
if c == " " or c.isspace():
c = ""
set_string += c
key_length = len(set_string)
acceptable_key_characters = string.ascii_letters
for _ in range(key_length):
retval += random.choice(acceptable_key_characters)
if retval not in used_keys:
db_cursor.execute("INSERT INTO used_keys(id, key) VALUES (?, ?)", (id_number, retval))
return retval, set_string
else:
create_key(_string, db_cursor)
def encode_cipher(_string, key):
"""
encode the string using a generated unique key
"""
retval = ""
for k, v in zip(_string, key):
c_index = ALPHABET.index(k)
key_index = ALPHABET.index(v)
cipher_index = c_index + key_index
try:
retval += ALPHABET[cipher_index]
except IndexError:
cipher_index -= 26
retval += ALPHABET[cipher_index]
return retval
def decode_cipher(encoded, key):
"""
decode the encoded string using the encoded string and the key used to cipher it
"""
retval = ""
for k, v in zip(encoded, key):
c_index = ALPHABET.index(k)
key_index = ALPHABET.index(v)
decode = c_index - key_index
try:
retval += ALPHABET[decode]
except IndexError:
decode += 26
retval += ALPHABET[decode]
return retval
def main():
"""
main messy function
"""
exited = False
choices = {"1": "show keys", "2": "create new key", "3": "decode a cipher", "4": "exit"}
cursor = initialize()
seperator = "-" * 35
print("database initialized, what would you like to do:")
try:
while not exited:
for item in sorted(choices.keys()):
print("[{}] {}".format(item, choices[item]))
choice = raw_input(">> ")
if choice == "1":
keys = cursor.execute("SELECT key FROM used_keys")
print(seperator)
for key in keys.fetchall():
print(key[0])
print(seperator)
elif choice == "2":
phrase = raw_input("Enter your secret phrase: ")
key, set_string = create_key(phrase, cursor)
encoded = encode_cipher(set_string, key)
print(seperator)
print("encoded message: '{}'".format(encoded))
print(seperator)
elif choice == "3":
encoded_cipher = raw_input("enter and encoded cipher: ")
encode_key = raw_input("enter the cipher key: ")
decoded = decode_cipher(encoded_cipher, encode_key)
print(seperator)
print("decoded message: '{}'".format(decoded))
print(seperator)
elif choice == "4":
print("database destroyed")
exited = True
except KeyboardInterrupt:
print("database has been destroyed")
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<p>The hard problems for one-time pads are </p>\n\n<ol>\n<li>randomly generating the pad, and</li>\n<li>securely sharing the pad between the participants (and nobody else).</li>\n</ol>\n\n<p>The first problem is not solved, because the <code>random</code> package is a <em>pseudo-random</em> generator... | {
"AcceptedAnswerId": "207566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T22:48:59.103",
"Id": "207515",
"Score": "3",
"Tags": [
"python",
"python-2.x",
"security",
"sqlite",
"caesar-cipher"
],
"Title": "Simple one time pad cipher"
} | 207515 |
<p>I would like make this calculator program more Object Oriented but I'm struggling with how to do it. The calculator works perfectly but I would like to have another class that does the calculations and then sends that information back to the main class to be displayed. Any tips? I'm not sure how to call the methods and return the calculations.</p>
<pre><code> public partial class MainWindow : Window
{
//Basic Variables
string input = string.Empty;
string op1 = string.Empty;
string op2 = string.Empty;
char operation;
double result = 0.0;
public MainWindow()
{
InitializeComponent();
}
private void btnOn_Click(object sender, RoutedEventArgs e)
{
displayTextbox.IsEnabled = true;
}
private void btnOff_Click(object sender, RoutedEventArgs e)
{
displayTextbox.IsEnabled = false;
displayTextbox.Text = String.Empty;
displayTextbox.Text = "Off";
}
private void btn0_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 0;
this.displayTextbox.Text += input;
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 1;
this.displayTextbox.Text += input;
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 2;
this.displayTextbox.Text += input;
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 3;
this.displayTextbox.Text += input;
}
private void btn4_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 4;
this.displayTextbox.Text += input;
}
private void btn5_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 5;
this.displayTextbox.Text += input;
}
private void btn6_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 6;
this.displayTextbox.Text += input;
}
private void btn7_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 7;
this.displayTextbox.Text += input;
}
private void btn8_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 8;
this.displayTextbox.Text += input;
}
private void btn9_Click(object sender, RoutedEventArgs e)
{
this.displayTextbox.Text = "";
input += 9;
this.displayTextbox.Text += input;
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
displayTextbox.Text = "";
this.input = string.Empty;
this.op1 = string.Empty;
this.op2 = string.Empty;
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
op1 = input;
operation = '+';
input = string.Empty;
}
private void btnDivision_Click(object sender, RoutedEventArgs e)
{
op1 = input;
operation = '/';
input = string.Empty;
}
private void btnMultiple_Click(object sender, RoutedEventArgs e)
{
op1 = input;
operation = '*';
input = string.Empty;
}
private void btnSubtract_Click(object sender, RoutedEventArgs e)
{
op1 = input;
operation = '-';
input = string.Empty;
}
private void btnEquals_Click(object sender, RoutedEventArgs e)
{
op2 = input;
double num1, num2;
double.TryParse(op1, out num1);
double.TryParse(op2, out num2);
if (operation == '+')
{
result = num1 + num2;
displayTextbox.Text = result.ToString();
}
else if (operation == '-')
{
result = num1 - num2;
displayTextbox.Text = result.ToString();
}
else if (operation == '*')
{
result = num1 * num2;
displayTextbox.Text = result.ToString();
}
else if (operation == '/')
{
result = num1 / num2;
displayTextbox.Text = result.ToString();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T19:45:45.007",
"Id": "400687",
"Score": "0",
"body": "Odd to me that input is string."
}
] | [
{
"body": "<p>Some tips from me:</p>\n\n<p>1) You should separate the UI logic from your main logic. In your case, the logic is the calculation, so you should make a class for it. Don't think about the UI, just code your logic. It must be completely independent of the UI. This way you could test your calculatio... | {
"AcceptedAnswerId": "207521",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T23:02:59.307",
"Id": "207516",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"calculator",
"gui"
],
"Title": "Four-function calculator with buttons for digits and operators"
} | 207516 |
<p>I just finished this big project. Its is called <code>SortedList</code> and it is implemented using a Doubly-Linked List. It data is of type <code>void*</code> and it has 4 default functions: compare, copy, display and free. What they do is in the documented code.</p>
<p>This data structure is my most advanced one and I'd like to have it as a reference to my other data structures, like the way it is documented, the way it is implemented and so on.</p>
<p>Any suggestions, are more than welcome. Feel free to give me a full feedback, even for the smallest details. Please focus on <code>SortedList.h</code> and <code>SortedList.c</code>. If you would like to help me in this project feel free to message me.</p>
<p>The documentation supports <a href="http://www.doxygen.org/" rel="nofollow noreferrer">doxygen</a>.</p>
<p>I'm making a data structures library located <a href="https://github.com/LeoVen/C-DataStructures-Library" rel="nofollow noreferrer">here</a>. My intentions with it is <strong>purely educational</strong>. So code readability and documentations are key to this project. I do not intend for these structures to be fast and industrial-grade. I just hope this will one day be useful for students and enthusiasts.</p>
<p><strong>P.S.</strong> I had to remove a lot of content due to text size limitations like <code>Core.h</code> and <code>CoreSort.h</code>. I also haven't had time to make tests. You can check the latest advancements in the Github repository linked above.</p>
<p><strong>SortedList.h</strong></p>
<pre><code>#ifndef C_DATASTRUCTURES_LIBRARY_SORTEDLIST_H
#define C_DATASTRUCTURES_LIBRARY_SORTEDLIST_H
#include "Core.h"
#include "CoreSort.h"
#ifdef __cplusplus
extern "C" {
#endif
// A sorted doubly-linked list. See the source file for the full documentation.
struct SortedList_s;
/// \brief A type for a sorted doubly-linked list.
///
/// A type for a <code> struct SortedList_s </code> so you don't have to always
/// write the full name of it.
typedef struct SortedList_s SortedList_t;
/// \brief A pointer type for a sorted doubly-linked list.
///
/// Useful for not having to declare every variable as pointer type. This
/// typedef does that for you.
typedef struct SortedList_s *SortedList;
/// \brief Comparator function type.
///
/// A type for a function that compares two elements, returning:
/// - [ > 0] when the first element is greater than the second;
/// - [ < 0] when the first element is less than the second;
/// - 0 when both elements are equal.
typedef int(*sli_compare_f)(void *, void *);
/// \brief A Copy function type.
///
/// A type for a function that takes an input (first parameter) and returns an
/// exact copy of that element.
typedef void *(*sli_copy_f)(void *);
/// \brief Display function type.
///
/// A type for a function that displays an element in the console. Please do
/// not print a newline character.
typedef void(*sli_display_f)(void *);
/// \brief A Free function type.
///
/// A type for a function responsible for completely freeing an element from
/// memory.
typedef void(*sli_free_f)(void *);
///////////////////////////////////// STRUCTURE INITIALIZATION AND DELETION ///
Status sli_init(SortedList *list);
Status sli_create(SortedList *list, SortOrder order, sli_compare_f compare_f,
sli_copy_f copy_f, sli_display_f display_f, sli_free_f free_f);
Status sli_free(SortedList *list);
Status sli_erase(SortedList *list);
/////////////////////////////////////////////////////////////////// SETTERS ///
Status sli_set_func_compare(SortedList list, sli_compare_f function);
Status sli_set_func_copy(SortedList list, sli_copy_f function);
Status sli_set_func_display(SortedList list, sli_display_f function);
Status sli_set_func_free(SortedList list, sli_free_f function);
Status sli_set_limit(SortedList list, index_t limit);
Status sli_set_order(SortedList list, SortOrder order);
// No setter because the user might break the sorted property of the list.
/////////////////////////////////////////////////////////////////// GETTERS ///
index_t sli_length(SortedList list);
index_t sli_limit(SortedList list);
SortOrder sli_order(SortedList list);
Status sli_get(SortedList list, void **result, index_t index);
////////////////////////////////////////////////////////// INPUT AND OUTPUT ///
Status sli_insert(SortedList list, void *element);
Status sli_insert_all(SortedList list, void **elements, index_t count);
Status sli_remove(SortedList list, void **result, index_t position);
Status sli_remove_max(SortedList list, void **result);
Status sli_remove_min(SortedList list, void **result);
/////////////////////////////////////////////////////////// STRUCTURE STATE ///
bool sli_full(SortedList list);
bool sli_empty(SortedList list);
/////////////////////////////////////////////////////////////////// UTILITY ///
void *sli_max(SortedList list);
void *sli_min(SortedList list);
index_t sli_index_first(SortedList list, void *key);
index_t sli_index_last(SortedList list, void *key);
bool sli_contains(SortedList list, void *key);
Status sli_reverse(SortedList list);
Status sli_copy(SortedList list, SortedList *result);
Status sli_to_array(SortedList list, void ***result, index_t *length);
/////////////////////////////////////////////////////////////////// LINKING ///
Status sli_merge(SortedList list1, SortedList list2);
Status sli_unlink(SortedList list, SortedList *result, index_t position);
Status sli_sublist(SortedList list, SortedList *result, index_t start,
index_t end);
/////////////////////////////////////////////////////////////////// DISPLAY ///
Status sli_display(SortedList list);
Status sli_display_array(SortedList list);
Status sli_display_raw(SortedList list);
///////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////// Iterator ///
///////////////////////////////////////////////////////////////////////////////
// A sorted list iterator. See the source file for the full documentation.
struct SortedListIterator_s;
/// \brief A type for a sorted list iterator.
///
/// A type for a <code> struct SortedListIterator_s </code>.
typedef struct SortedListIterator_s SortedListIterator_t;
/// \brief A pointer type for a sorted list iterator.
///
/// A pointer type for a <code> struct SortedListIterator_s </code>.
typedef struct SortedListIterator_s *SortedListIterator;
///////////////////////////////////// STRUCTURE INITIALIZATION AND DELETION ///
Status sli_iter_init(SortedListIterator *iter, SortedList target);
Status sli_iter_retarget(SortedListIterator *iter, SortedList target);
Status sli_iter_free(SortedListIterator *iter);
///////////////////////////////////////////////////////////////// ITERATION ///
Status sli_iter_next(SortedListIterator iter);
Status sli_iter_prev(SortedListIterator iter);
Status sli_iter_to_head(SortedListIterator iter);
Status sli_iter_to_tail(SortedListIterator iter);
/////////////////////////////////////////////////////////// STRUCTURE STATE ///
bool sli_iter_has_next(SortedListIterator iter);
bool sli_iter_has_prev(SortedListIterator iter);
////////////////////////////////////////////////////////// SETTER AND GETTER ///
/// Gets a copy of the element pointed by the cursor.
Status sli_iter_get(SortedListIterator iter, void **result);
// No setter because the user might break the sorted property of the list.
////////////////////////////////////////////////////////// INPUT AND OUTPUT ///
// No insert functions because the user might break the sorted property.
Status sli_iter_remove_next(SortedListIterator iter, void **result);
Status sli_iter_remove_curr(SortedListIterator iter, void **result);
Status sli_iter_remove_prev(SortedListIterator iter, void **result);
/////////////////////////////////////////////////////////////////// UTILITY ///
void *sli_iter_peek_next(SortedListIterator iter);
void *sli_iter_peek(SortedListIterator iter);
void *sli_iter_peek_prev(SortedListIterator iter);
#ifdef __cplusplus
}
#endif
#endif //C_DATASTRUCTURES_LIBRARY_SORTEDLIST_H
</code></pre>
<p><strong>SortedList.c</strong></p>
<p>Sadly the source code is too big so I have omitted all the iterator's functions... You can still check it out <a href="https://github.com/LeoVen/C-DataStructures-Library" rel="nofollow noreferrer">here</a>.</p>
<pre><code>#include "SortedList.h"
/// \brief A generic sorted doubly-linked list.
///
/// This is a generic sorted doubly-linked list. Its elements can be added in
/// ASCENDING or DESCENDING order. This property can be set when creating a new
/// list or using sli_set_order(). You can also limit its length using
/// sli_set_limit(). To remove this limitation simply set the limit to a value
/// less than or equal to 0.
///
/// To initialize a list use sli_init(). This only initializes the structure.
/// If you don't set the proper functions later you won't be able to insert
/// elements, copy the list, display the list or even delete it. If you want to
/// initialize it completely, use instead sli_create(). Here you must pass in
/// default functions (compare, copy, display and free), making a complete
/// list.
///
/// To add an element to the list use sli_insert(). To remove, you have three
/// options: sli_remove() that removes an element at a given position;
/// sli_remove_max() that removes the biggest element; and sli_remove_min()
/// that removes the smallest element.
///
/// To delete a list use sli_free(). This completely frees all elements and
/// sets the list pointer to NULL. Note that if you haven't set a delete
/// function you won't be able to delete the list or its elements. You must set
/// a delete function that will be responsible for freeing from memory all
/// elements.
struct SortedList_s
{
/// \brief List length.
///
/// List current amount of elements linked between the \c head and \c tail
/// pointers.
index_t length;
/// \brief List length limit.
///
/// If it is set to 0 or a negative value then the list has no limit to its
/// length. Otherwise it won't be able to have more elements than the
/// specified value. The list is always initialized with no restrictions to
/// its length, that is, \c limit equals 0. The user won't be able to limit
/// the list length if it already has more elements than the specified
/// limit.
index_t limit;
/// \brief Points to the first Node on the list.
///
/// Points to the first Node on the list or \c NULL if the list is empty.
struct SortedListNode_s *head;
/// \brief Points to the last Node on the list.
///
/// Points to the first Node on the list or \c NULL if the list is empty.
struct SortedListNode_s *tail;
/// \brief Defines the order of elements.
///
/// The order of elements can either be \c ASCENDING or \c DESCENDING.
SortOrder order;
/// \brief Comparator function.
///
/// A function that compares one element with another that returns an int
/// with the following rules:
///
/// - <code>[ > 0 ]</code> if first element is greater than the second;
/// - <code>[ < 0 ]</code> if second element is greater than the first;
/// - <code>[ 0 ]</code> if elements are equal.
sli_compare_f d_compare;
/// \brief Copy function.
///
/// A function that returns an exact copy of an element.
sli_copy_f d_copy;
/// \brief Display function.
///
/// A function that displays an element in the console. Useful for
/// debugging.
sli_display_f d_display;
/// \brief Deallocator function.
///
/// A function that completely frees an element from memory.
sli_free_f d_free;
/// \brief A version id to keep track of modifications.
///
/// This version id is used by the iterator to check if the structure was
/// modified. The iterator can only function if its version_id is the same
/// as the structure's version id, that is, there have been no structural
/// modifications (except for those done by the iterator itself).
index_t version_id;
};
/// \brief A SortedList_s node.
///
/// Implementation detail. This is a doubly-linked node with a pointer to the
/// previous node (or \c NULL if it is the head node) and another pointer to
/// the next node (or \c NULL if it is the tail node).
struct SortedListNode_s
{
/// \brief Data pointer.
///
/// Points to node's data. The data needs to be dynamically allocated.
void *data;
/// \brief Next node on the list.
///
/// Next node on the list or \c NULL if this is the tail node.
struct SortedListNode_s *next;
/// \brief Previous node on the list.
///
/// Previous node on the list or \c NULL if this is the head node.
struct SortedListNode_s *prev;
};
/// \brief A type for a sorted list node.
///
/// Defines a type to a <code> struct SortedListNode_s </code>.
typedef struct SortedListNode_s SortedListNode_t;
/// \brief A pointer type for a sorted list node.
///
/// Define a pointer type to a <code> struct SortedListNode_s </code>.
typedef struct SortedListNode_s *SortedListNode;
///////////////////////////////////////////////////// NOT EXPOSED FUNCTIONS ///
static Status sli_make_node(SortedListNode *node, void *data);
static Status sli_free_node(SortedListNode *node, sli_free_f free_f);
static Status sli_get_node_at(SortedList list, SortedListNode *result,
index_t position);
static Status sli_insert_tail(SortedList list, void *element);
////////////////////////////////////////////// END OF NOT EXPOSED FUNCTIONS ///
/// \brief Initializes the SortedList_s structure.
///
/// This function initializes the SortedList_s structure but does not sets any
/// default functions. If you don't set them latter you won't be able to add
/// elements, copy the list, free the list or display it. It also sets a
/// default order of \c DESCENDING.
///
/// \param[in,out] list SortedList_s to be allocated.
///
/// \return DS_ERR_ALLOC if list allocation failed.
/// \return DS_OK if all operations are successful.
Status sli_init(SortedList *list)
{
*list = malloc(sizeof(SortedList_t));
if (!(*list))
return DS_ERR_ALLOC;
(*list)->length = 0;
(*list)->limit = 0;
(*list)->version_id = 0;
(*list)->order = DESCENDING;
(*list)->head = NULL;
(*list)->tail = NULL;
(*list)->d_compare = NULL;
(*list)->d_copy = NULL;
(*list)->d_display = NULL;
(*list)->d_free = NULL;
return DS_OK;
}
/// \brief Creates a SortedList_s.
///
/// This function completely creates a SortedList_s. This sets the list order
/// of elements and all of its default functions.
///
/// \param[in,out] list SortedList_s to be allocated.
/// \param[in] order The sorting order of the list's elements.
/// \param[in] compare_f A function that compares two elements.
/// \param[in] copy_f A function that makes an exact copy of an element.
/// \param[in] display_f A function that displays in the console an element.
/// \param[in] free_f A function that completely frees from memory an element.
///
/// \return DS_ERR_ALLOC if list allocation failed.
/// \return DS_OK if all operations are successful.
Status sli_create(SortedList *list, SortOrder order, sli_compare_f compare_f,
sli_copy_f copy_f, sli_display_f display_f, sli_free_f free_f)
{
*list = malloc(sizeof(SortedList_t));
if (!(*list))
return DS_ERR_ALLOC;
(*list)->length = 0;
(*list)->limit = 0;
(*list)->version_id = 0;
(*list)->order = order;
(*list)->head = NULL;
(*list)->tail = NULL;
(*list)->d_compare = compare_f;
(*list)->d_copy = copy_f;
(*list)->d_display = display_f;
(*list)->d_free = free_f;
return DS_OK;
}
/// \brief Frees from memory a SortedList_s and all its elements.
///
/// This function frees from memory all the list's elements using its default
/// free function and then frees the list's structure. The variable is then set
/// to \c NULL.
///
/// \param[in,out] list SortedList_s to be freed from memory.
///
/// \return DS_ERR_INCOMPLETE_TYPE if a default free function is not set.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_free(SortedList *list)
{
if (*list == NULL)
return DS_ERR_NULL_POINTER;
if ((*list)->d_free == NULL)
return DS_ERR_INCOMPLETE_TYPE;
SortedListNode prev = (*list)->head;
Status st;
while ((*list)->head != NULL)
{
(*list)->head = (*list)->head->next;
st = sli_free_node(&prev, (*list)->d_free);
if (st != DS_OK)
return st;
prev = (*list)->head;
}
free((*list));
(*list) = NULL;
return DS_OK;
}
/// \brief Erases a SortedList_s.
///
/// This function is equivalent to freeing a list and the creating it again.
/// This will reset the list to its initial state with no elements, but will
/// keep all of its default functions and the order of elements.
///
/// \param[in,out] list SortedList_s to be erased.
///
/// \return DS_ERR_INCOMPLETE_TYPE if a default free function is not set.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_erase(SortedList *list)
{
if (*list == NULL)
return DS_ERR_NULL_POINTER;
SortedList new_list;
Status st = sli_create(&new_list, (*list)->order, (*list)->d_compare,
(*list)->d_copy, (*list)->d_display, (*list)->d_free);
if (st != DS_OK)
return st;
st = sli_free(list);
// Probably didn't set the free function...
if (st != DS_OK)
{
free(new_list);
return st;
}
*list = new_list;
return DS_OK;
}
/// \brief Sets the default compare function.
///
/// Use this function to set a default compare function. It can only be done
/// when the list is empty, otherwise you would have elements sorted with a
/// different logic. The function needs to comply with the sli_compare_f
/// specifications.
///
/// \param[in] list SortedList_s to set the default compare function.
/// \param[in] function An sli_compare_f kind of function.
///
/// \return DS_ERR_INVALID_OPERATION if the list is not empty.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_set_func_compare(SortedList list, sli_compare_f function)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
// Can only set a new compare function if the list is empty, otherwise you
// would be adding new elements in the list with a different logic than the
// elements already in the list.
if (!sli_empty(list))
return DS_ERR_INVALID_OPERATION;
list->d_compare = function;
return DS_OK;
}
/// \brief Sets the default copy function.
///
/// Use this function to set a default compare function. It needs to comply
/// with the sli_copy_f specifications.
///
/// \param[in] list SortedList_s to set the default copy function.
/// \param[in] function An sli_copy_f kind of function.
///
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_set_func_copy(SortedList list, sli_copy_f function)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
list->d_copy = function;
return DS_OK;
}
/// \brief Sets the default display function
///
/// Use this function to set a default display function. It needs to comply
/// with the sli_display_f specifications. Useful for debugging.
///
/// \param[in] list SortedList_s to set the default display function.
/// \param[in] function An sli_display_f kind of function.
///
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_set_func_display(SortedList list, sli_display_f function)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
list->d_display = function;
return DS_OK;
}
/// \brief Sets the default free function
///
/// Use this function to set a default free function. It needs to comply
/// with the sli_free_f specifications.
///
/// \param[in] list SortedList_s to set the default free function.
/// \param[in] function An sli_free_f kind of function.
///
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_set_func_free(SortedList list, sli_free_f function)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
list->d_free = function;
return DS_OK;
}
/// \brief Sets a limit to the specified SortedList_s's length.
///
/// Limit's the SortedList_s's length. You can only set a limit greater or
/// equal to the list's current length and greater than 0. To remove this
/// limitation simply set the limit to 0 or less.
///
/// \param[in] list SortedList_s reference.
/// \param[in] limit Maximum list length.
///
/// \return DS_ERR_INVALID_OPERATION if the limitation is less than the list's
/// current length.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_set_limit(SortedList list, index_t limit)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
// The new limit can't be lower than the list's current length.
if (list->length > limit && limit > 0)
return DS_ERR_INVALID_OPERATION;
list->limit = limit;
return DS_OK;
}
/// \brief Sets the sorting order of elements of the specified SortedList_s.
///
/// Sets the sorting order of elements to either \c ASCENDING or \c DESCENDING.
/// You can only set it when the list is empty.
///
/// \param[in] list SortedList_s reference.
/// \param[in] order Sorting order of elements.
///
/// \return DS_ERR_INVALID_OPERATION if the list is not empty.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_set_order(SortedList list, SortOrder order)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (!sli_empty(list))
return DS_ERR_INVALID_OPERATION;
list->order = order;
return DS_OK;
}
/// \brief Returns the SortedList_s's length.
///
/// Returns the list's current length or -1 if the list references to \c NULL.
///
/// \param[in] list SortedList_s reference.
///
/// \return -1 if the list reference is \c NULL.
/// \return The list's length.
index_t sli_length(SortedList list)
{
if (list == NULL)
return -1;
return list->length;
}
/// \brief Returns the SortedList_s's limit.
///
/// Returns the list limit or -1 if the list references to \c NULL.
///
/// \param[in] list SortedList_s reference.
///
/// \return -1 if the list reference is \c NULL.
/// \return The list's limit.
index_t sli_limit(SortedList list)
{
if (list == NULL)
return -1;
return list->limit;
}
/// \brief Returns the SortedList_s's sorting order.
///
/// Return the list's sorting order, either ASCENDING, DESCENDING or 0 if the
/// list references to \c NULL.
///
/// \param[in] list SortedList_s reference.
///
/// \return 0 if the list references to \c NULL.
/// \return The list order.
SortOrder sli_order(SortedList list)
{
if (list == NULL)
return 0;
return list->order;
}
/// \brief Returns a copy of an element at a given position.
///
/// This function is zero-based and returns a copy of the element located at
/// the specified index.
///
/// \param[in] list SortedList_s reference.
/// \param[out] result Resulting copy of the element.
/// \param[in] index Element position.
///
/// \return DS_ERR_INCOMPLETE_TYPE if a default copy function is not set.
/// \return DS_ERR_INVALID_OPERATION if the list is empty.
/// \return DS_ERR_NEGATIVE_VALUE if index parameter is negative.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_ERR_OUT_OF_RANGE if index parameter is greater than or equal
/// to the list's length.
/// \return DS_OK if all operations are successful.
Status sli_get(SortedList list, void **result, index_t index)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
if (index < 0)
return DS_ERR_NEGATIVE_VALUE;
if (index >= list->length)
return DS_ERR_OUT_OF_RANGE;
if (list->d_copy == NULL)
return DS_ERR_INCOMPLETE_TYPE;
SortedListNode node;
Status st = sli_get_node_at(list, &node, index);
if (st != DS_OK)
return st;
*result = list->d_copy(node->data);
return DS_OK;
}
/// \brief Inserts an element to the specified SortedList_s.
///
/// Inserts an element according to the sort order specified by the list. This
/// function can take up to O(n) to add an element in its correct position.
///
/// \param[in] list SortedList_s reference where the element is to be inserted.
/// \param[in] element Element to be inserted in the list.
///
/// \return DS_ERR_FULL if \c limit is set (different than 0) and the list
/// length reached the specified limit.
/// \return DS_ERR_INCOMPLETE_TYPE if a default compare function is not set.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_insert(SortedList list, void *element)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (list->d_compare == NULL)
return DS_ERR_INCOMPLETE_TYPE;
if (sli_full(list))
return DS_ERR_FULL;
SortedListNode node;
Status st = sli_make_node(&node, element);
if (st != DS_OK)
return st;
// First node.
if (sli_empty(list))
{
list->head = node;
list->tail = node;
}
// Insert node in its position.
else
{
SortedListNode scan = list->head;
SortedListNode before = NULL;
if (list->order == ASCENDING)
{
// Insert 'head'. Change list->head.
if (list->d_compare(node->data, list->head->data) <= 0)
{
// The new element will be the new smallest element.
node->next = list->head;
list->head->prev = node;
list->head = node;
}
else
{
while (scan != NULL &&
list->d_compare(node->data, scan->data) > 0)
{
before = scan;
scan = scan->next;
}
// Insert 'tail'. Change list->tail.
if (scan == NULL)
{
// The new element will be the new biggest element.
node->prev = before;
before->next = node;
list->tail = node;
}
// Insert at the middle of the list.
else
{
before->next = node;
scan->prev = node;
node->next = scan;
node->prev = before;
}
}
}
// Defaults to DESCENDING.
else
{
// Insert 'head'. Change list->head.
if (list->d_compare(node->data, list->head->data) >= 0)
{
// The new element will be the new biggest element.
node->next = list->head;
list->head->prev = node;
list->head = node;
}
else
{
while (scan != NULL &&
list->d_compare(node->data, scan->data) < 0)
{
before = scan;
scan = scan->next;
}
// Insert 'tail'. Change list->tail.
if (scan == NULL)
{
// The new element will be the new smallest element.
node->prev = before;
before->next = node;
list->tail = node;
}
// Insert at the middle of the list.
else
{
before->next = node;
scan->prev = node;
node->next = scan;
node->prev = before;
}
}
}
}
list->length++;
list->version_id++;
return DS_OK;
}
/// \brief Inserts an array of elements to the specified SortedList_s.
///
/// Inserts an array of void pointers into the list, with a size of \c count.
///
/// \param[in] list SortedList_s reference where all elements are to be
/// inserted.
/// \param[in] elements Elements to be inserted in the list.
/// \param[in] count Amount of elements to be inserted.
///
/// \return DS_ERR_NEGATIVE_VALUE if count parameter is negative.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_insert_all(SortedList list, void **elements, index_t count)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (count < 0)
return DS_ERR_NEGATIVE_VALUE;
Status st;
for (index_t i = 0; i < count; i++)
{
st = sli_insert(list, elements[i]);
if (st != DS_OK)
return st;
}
return DS_OK;
}
/// \brief Removes an element at a specified position from a SortedList_s.
///
/// Removes an element at the specified position. The position is 0 based so
/// the first element is at the position 0.
///
/// \param[in] list SortedList_s reference where an element is to be removed.
/// \param[out] result Resulting element removed from the list.
/// \param[in] position Element's position.
///
/// \return DS_ERR_INVALID_OPERATION if list is empty.
/// \return DS_ERR_ITER if during iteration the scanner references to \c NULL.
/// \return DS_ERR_NEGATIVE_VALUE if position parameter is negative.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_ERR_OUT_OF_RANGE if position parameter is greater than or equal
/// to the list's length.
/// \return DS_OK if all operations are successful.
Status sli_remove(SortedList list, void **result, index_t position)
{
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
if (position < 0)
return DS_ERR_NEGATIVE_VALUE;
if (position >= list->length)
return DS_ERR_OUT_OF_RANGE;
SortedListNode node;
// Remove head
if (position == 0)
{
node = list->head;
*result = node->data;
list->head = list->head->next;
if (list->head != NULL)
list->head->prev = NULL;
}
// Remove tail
else if (position == list->length - 1)
{
node = list->tail;
*result = node->data;
list->tail = list->tail->prev;
if (list->tail != NULL)
list->tail->next = NULL;
}
// Remove somewhere in the middle
else
{
Status st = sli_get_node_at(list, &node, position);
if (st != DS_OK)
return st;
// Unlink the current node
// Behold the power of doubly-linked lists!
node->prev->next = node->next;
node->next->prev = node->prev;
*result = node->data;
}
free(node);
list->length--;
list->version_id++;
if (sli_empty(list))
{
list->head = NULL;
list->tail = NULL;
}
return DS_OK;
}
/// \brief Removes the highest value from the specified SortedList_s.
///
/// Removes the highest value from the list. Depending on the sort order of
/// elements this function is equivalent to removing an element from the head
/// of the list or from tail.
///
/// \param[in] list SortedList_s reference where an element is to be removed.
/// \param[out] result Resulting element removed from the list.
///
/// \return DS_ERR_INVALID_OPERATION if list is empty.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_remove_max(SortedList list, void **result)
{
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
SortedListNode node;
// Remove from tail.
if (list->order == ASCENDING)
{
node = list->tail;
*result = node->data;
list->tail = list->tail->prev;
list->tail->next = NULL;
free(node);
}
// Remove from head.
else
{
node = list->head;
*result = node->data;
list->head = list->head->next;
list->head->prev = NULL;
free(node);
}
list->length--;
if (sli_empty(list))
{
list->head = NULL;
list->tail = NULL;
}
list->version_id++;
return DS_OK;
}
/// \brief Removes the smallest value from the specified SortedList_s.
///
/// Removes the smallest value from the list. Depending on the sort order of
/// elements this function is equivalent to removing an element from the head
/// of the list or from tail.
///
/// \param[in] list SortedList_s reference where an element is to be removed.
/// \param[out] result Resulting element removed from the list.
///
/// \return DS_ERR_INVALID_OPERATION if list is empty.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_remove_min(SortedList list, void **result)
{
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
SortedListNode node;
// Remove from head.
if (list->order == ASCENDING)
{
node = list->head;
*result = node->data;
list->head = list->head->next;
list->head->prev = NULL;
free(node);
}
// Remove from tail.
else
{
node = list->tail;
*result = node->data;
list->tail = list->tail->prev;
list->tail->next = NULL;
free(node);
}
list->length--;
if (sli_empty(list))
{
list->head = NULL;
list->tail = NULL;
}
list->version_id++;
return DS_OK;
}
/// \brief Checks if the specified SortedList_s is full.
///
/// Returns true if the list is full or false otherwise. The list can only be
/// full if its limit is set to a value higher than 0 and respecting all rules
/// from sli_set_limit().
///
/// \warning This function does not checks for \c NULL references and is prone
/// to provoke run-time errors if not used correctly.
///
/// \param[in] list SortedList_s reference.
///
/// \return True if the list is full.
/// \return False if the list is not full.
bool sli_full(SortedList list)
{
return list->limit > 0 && list->length >= list->limit;
}
/// \brief Checks if specified SortedList_s list is empty.
///
/// Returns true if the list is empty or false otherwise. The list is empty
/// when its length is 0. If every function works properly there is no need to
/// check if the head or tail pointers are \c NULL or not. The length variable
/// already tracks it.
///
/// \warning This function does not checks for \c NULL references and is prone
/// to provoke run-time errors if not used correctly.
///
/// \param[in] list SortedList_s reference.
///
/// \return True if the list is empty.
/// \return False if the list is not empty.
bool sli_empty(SortedList list)
{
return list->length == 0;
}
/// \brief Returns the highest element from the specified SortedList_s.
///
/// Returns a reference to the highest element in the list or NULL if the list
/// is empty. Use this as a read-only. If you make any changes to this element
/// the internal structure of the list will change and may cause undefined
/// behaviour.
///
/// \param[in] list SortedList_s reference.
///
/// \return NULL if the list references to \c NULL or if the list is empty.
/// \return The highest element in the list.
void *sli_max(SortedList list)
{
if (list == NULL)
return NULL;
if (sli_empty(list))
return NULL;
if (list->order == ASCENDING)
return list->tail->data;
return list->head->data;
}
/// \brief Returns the smallest element from the specified SortedList_s.
///
/// Returns a reference to the smallest element in the list or NULL if the list
/// is empty. Use this as a read-only. If you make any changes to this element
/// the internal structure of the list will change and may cause undefined
/// behaviour.
///
/// \param[in] list SortedList_s reference.
///
/// \return NULL if the list references to \c NULL or if the list is empty.
/// \return The highest element in the list.
void *sli_min(SortedList list)
{
if (list == NULL)
return NULL;
if (sli_empty(list))
return NULL;
if (list->order == ASCENDING)
return list->head->data;
return list->tail->data;
}
/// \brief Returns the index of the first element that matches a key.
///
/// Returns the index of the first element that matches a given key or -1 if it
/// could not be found.
///
/// \param[in] list SortedList_s reference.
/// \param[in] key Key to be searched in the list.
///
/// \return -2 if the list references to \c NULL.
/// \return -1 if the element was not found.
/// \return The index of the matched element.
index_t sli_index_first(SortedList list, void *key)
{
if (list == NULL)
return -2;
SortedListNode scan = list->head;
index_t index = 0;
while (scan != NULL)
{
if (list->d_compare(scan->data, key) == 0)
return index;
index++;
scan = scan->next;
}
return -1;
}
/// \brief Returns the index of the last element that matches a key.
///
/// Returns the index of the first element that matches a given key or -1 if it
/// could not be found.
///
/// \param[in] list SortedList_s reference.
/// \param[in] key Key to be searched in the list.
///
/// \return -2 if the list references to \c NULL.
/// \return -1 if the element was not found.
/// \return The index of the matched element.
index_t sli_index_last(SortedList list, void *key)
{
if (list == NULL)
return -2;
SortedListNode scan = list->tail;
index_t index = 0;
while (scan != NULL)
{
if (list->d_compare(scan->data, key) == 0)
return list->length - 1 - index;
index++;
scan = scan->prev;
}
return -1;
}
/// \brief Checks if a given element is present in the specified SortedList_s.
///
/// Returns true if the element is present in the list, otherwise false.
///
/// \warning This function does not checks for \c NULL references for either
/// the list parameter or if the default compare function is set.
///
/// \param[in] list SortedList_s reference.
/// \param[in] key Key to be matched.
///
/// \return True if the element is present in the list.
/// \return False if the element is not present in the list.
bool sli_contains(SortedList list, void *key)
{
SortedListNode scan = list->head;
while (scan != NULL)
{
if (list->d_compare(scan->data, key) == 0)
return true;
scan = scan->next;
}
return false;
}
/// \brief Reverses a SortedList_s.
///
/// Reverses the chain of elements from the list and changes the sort order of
/// elements. This function only changes the \c next and \c prev pointers from
/// each element and the \c head and \c tail pointers of the list struct.
///
/// \param[in] list SortedList_s reference to be reversed.
///
/// \return DS_ERR_NULL_POINTER if node references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_reverse(SortedList list)
{
// Reverse just like a doubly-linked list and change the list order
// ASCENDING -> DESCENDING
// DESCENDING -> ASCENDING
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (list->length != 1)
{
SortedListNode prev = NULL;
SortedListNode curr = list->head;
SortedListNode next = NULL;
list->tail = list->head;
while (curr != NULL)
{
next = curr->next;
curr->next = prev;
curr->prev = next;
prev = curr;
curr = next;
}
list->head = prev;
}
// If list length is 1 then just by doing this will do the trick
list->order = (list->order == ASCENDING) ? DESCENDING : ASCENDING;
list->version_id++;
return DS_OK;
}
/// \brief Makes a copy of the specified SortedList_s.
///
/// Makes an exact copy of a list.
///
/// \param[in] list SortedList_s to be copied.
/// \param[out] result Resulting copy.
///
/// \return DS_ERR_INCOMPLETE_TYPE if either a default copy or a default free
/// functions are not set.
/// \return DS_ERR_NULL_POINTER if node references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_copy(SortedList list, SortedList *result)
{
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (list->d_copy == NULL || list->d_free == NULL)
return DS_ERR_INCOMPLETE_TYPE;
Status st = sli_create(result, list->order, list->d_compare, list->d_copy,
list->d_display, list->d_free);
if (st != DS_OK)
return st;
(*result)->limit = list->limit;
SortedListNode scan = list->head;
void *elem;
while (scan != NULL)
{
elem = list->d_copy(scan->data);
st = sli_insert_tail(*result, elem);
if (st != DS_OK)
{
list->d_free(elem);
return st;
}
scan = scan->next;
}
return DS_OK;
}
/// \brief Copies the elements of the list to a C array.
///
/// Makes a copy of every element into an array respecting the order of the
/// elements in the list. The array needs to be an array of void pointers and
/// uninitialized. If any error is returned, the default values for \c result
/// and \c length are \c NULL and -1 respectively.
///
/// \param[in] list SortedList_s reference.
/// \param[out] result Resulting array.
/// \param[out] length Resulting array's length.
///
/// \return DS_ERR_INCOMPLETE_TYPE if a default copy function is not set.
/// \return DS_ERR_NULL_POINTER if list references to \c NULL.
/// \return DS_OK if all operations are successful.
Status sli_to_array(SortedList list, void ***result, index_t *length)
{
// If anything goes wrong...
*result = NULL;
*length = -1;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
if (list->d_copy == NULL)
return DS_ERR_INCOMPLETE_TYPE;
*length = list->length;
*result = malloc(sizeof(void*) * (*length));
if (!(*result))
return DS_ERR_NULL_POINTER;
SortedListNode scan = list->head;
for (index_t i = 0; i < *length; i++)
{
(*result)[i] = list->d_copy(scan->data);
scan = scan->next;
}
return DS_OK;
}
/// \brief Merge two SortedList_s.
///
/// Removes all elements from list2 and inserts them into list1.
///
/// \param[in] list1 SortedList_s where elements are added to.
/// \param[in] list2 SortedList_s where elements are removed from.
///
/// \return DS_ERR_NULL_POINTER if either list1 or list2 references are
/// \c NULL.
Status sli_merge(SortedList list1, SortedList list2)
{
if (list1 == NULL || list2 == NULL)
return DS_ERR_NULL_POINTER;
Status st;
void *result;
while (!sli_empty(list2))
{
st = sli_remove(list2, &result, 0);
if (st != DS_OK)
return st;
st = sli_insert(list1, result);
if (st != DS_OK)
return st;
}
return DS_OK;
}
/// \brief Unlinks elements from the specified SortedList_s.
///
/// Unlinks all elements starting from \c position all the way to the end of
/// the list. The \c result list must not have been initialized.
///
/// \param[in] list SortedList_s reference.
/// \param[out] result Resulting sublist.
/// \param[in] position Position to unlink the elements from the list.
///
/// \return DS_ERR_INVALID_OPERATION if the list is empty.
/// \return DS_ERR_NEGATIVE_VALUE if position parameter is negative.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_ERR_OUT_OF_RANGE if position parameter is greater than or equal
/// to the list's length.
/// \return DS_OK if all operations are successful.
Status sli_unlink(SortedList list, SortedList *result, index_t position)
{
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
if (position < 0)
return DS_ERR_NEGATIVE_VALUE;
if (position >= list->length)
return DS_ERR_OUT_OF_RANGE;
Status st = sli_create(result, list->order, list->d_compare, list->d_copy,
list->d_display, list->d_free);
if (st != DS_OK)
return st;
(*result)->limit = list->limit;
SortedListNode node, new_tail;
// Special case
if (position == 0)
{
// Simply transfer everything from one list to another.
(*result)->length = list->length;
(*result)->head = list->head;
(*result)->tail = list->tail;
list->length = 0;
list->head = NULL;
list->tail = NULL;
}
else
{
st = sli_get_node_at(list, &node, position);
if (st != DS_OK)
return st;
// New list tail. The position parameter is inclusive so go one node
// back.
new_tail = node->prev;
// Separating chains.
node->prev = NULL;
new_tail->next = NULL;
// Resulting list head is node and tail is the old list tail.
(*result)->head = node;
(*result)->tail = list->tail;
list->tail = new_tail;
// Recalculate lengths
(*result)->length = list->length - position;
list->length = position;
}
list->version_id++;
return DS_OK;
}
/// \brief Extracts a sublist from the specified SortedList_s.
///
/// Extracts a sublist from the specified SortedList_s. The sublist is stored
/// in the \c result SortedList_s.
///
/// \param[in] list SortedList_s where the sublist is to be removed from.
/// \param[out] result An uninitialized SortedList_s to receive the resulting
/// sublist.
/// \param[in] start Start of the sublist.
/// \param[in] end End of the sublist.
///
/// \return DS_ERR_INVALID_ARGUMENT if the start parameter is greater than the
/// end parameter.
/// \return DS_ERR_INVALID_OPERATION if the list is empty.
/// \return DS_ERR_NEGATIVE_VALUE if either start or end parameters are
/// negative.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_ERR_OUT_OF_RANGE if the end parameter is greater than or equal
/// to the list's length.
/// \return DS_OK if all operations are successful.
Status sli_sublist(SortedList list, SortedList *result, index_t start,
index_t end)
{
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (start < 0 || end < 0)
return DS_ERR_NEGATIVE_VALUE;
if (end < start)
return DS_ERR_INVALID_ARGUMENT;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
if (end >= list->length)
return DS_ERR_OUT_OF_RANGE;
Status st = sli_create(result, list->order, list->d_compare, list->d_copy,
list->d_display, list->d_free);
if (st != DS_OK)
return st;
(*result)->limit = list->limit;
SortedListNode node;
// Remove only one node
if (start == end)
{
st = sli_get_node_at(list, &node, start);
if (st != DS_OK)
return st;
if (node->next != NULL)
node->next->prev = node->prev;
if (node->prev != NULL)
node->prev->next = node->next;
node->next = NULL, node->prev = NULL;
(*result)->head = node;
(*result)->tail = node;
}
// Simply transfer everything
else if (start == 0 && end == list->length - 1)
{
(*result)->head = list->head;
(*result)->tail = list->tail;
list->head = NULL;
list->tail = NULL;
}
// Remove from head to end
else if (start == 0)
{
st = sli_get_node_at(list, &node, end);
if (st != DS_OK)
return st;
// New list head. The position parameters are inclusive so go one node
// forward.
SortedListNode new_head = node->next;
// Separating chains.
node->next = NULL;
new_head->prev = NULL;
(*result)->head = list->head;
(*result)->tail = node;
list->head = new_head;
}
// Remove from start to tail
else if (end == list->length - 1)
{
st = sli_get_node_at(list, &node, start);
if (st != DS_OK)
return st;
// New list tail. The position parameters are inclusive so go one node
// back.
SortedListNode new_tail = node->prev;
// Separating chains.
node->prev = NULL;
new_tail->next = NULL;
// Resulting list head is node and tail is the old list tail.
(*result)->head = node;
(*result)->tail = list->tail;
list->tail = new_tail;
}
// Start and end are inner nodes
else
{
// 'before' the 'start' node and 'after' the 'end' node
SortedListNode before, after;
st += sli_get_node_at(list, &before, start - 1);
st += sli_get_node_at(list, &after, end + 1);
if (st != DS_OK)
return st;
(*result)->head = before->next;
(*result)->tail = after->prev;
before->next = after;
after->prev = before;
(*result)->head->prev = NULL;
(*result)->tail->next = NULL;
}
(*result)->length = end - start + 1;
list->length -= (*result)->length;
list->version_id++;
return DS_OK;
}
/// \brief Displays a SortedList_s in the console.
///
/// Displays a SortedList_s in the console with its elements separated by
/// arrows indicating a doubly-linked list.
///
/// \param[in] list The SortedList_s to be displayed in the console.
///
/// \return DS_ERR_INCOMPLETE_TYPE if a default display function is not set.
/// \return DS_ERR_NULL_POINTER if the list reference is \c NULL.
/// \return DS_OK if all operations were successful.
Status sli_display(SortedList list)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (list->d_display == NULL)
return DS_ERR_INCOMPLETE_TYPE;
if (sli_empty(list))
{
printf("\nSorted List\n[ empty ]\n");
return DS_OK;
}
SortedListNode scan = list->head;
printf("\nSorted List\nNULL <-> ");
while (scan != NULL)
{
list->d_display(scan->data);
printf(" <-> ");
scan = scan->next;
}
printf(" NULL\n");
return DS_OK;
}
/// \brief Displays a SortedList_s in the console.
///
/// Displays a SortedList_s in the console like an array with its elements
/// separated by commas, delimited with brackets.
///
/// \param[in] list The SortedList_s to be displayed in the console.
///
/// \return DS_ERR_INCOMPLETE_TYPE if a default display function is not set.
/// \return DS_ERR_NULL_POINTER if the list reference is \c NULL.
/// \return DS_OK if all operations were successful.
Status sli_display_array(SortedList list)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (list->d_display == NULL)
return DS_ERR_INCOMPLETE_TYPE;
if (sli_empty(list))
{
printf("\n[ empty ]\n");
return DS_OK;
}
SortedListNode scan = list->head;
printf("\nSorted List\n[ ");
while (scan->next != NULL)
{
list->d_display(scan->data);
printf(", ");
scan = scan->next;
}
list->d_display(scan->data);
printf(" ]\n");
return DS_OK;
}
///////////////////////////////////////////////////// NOT EXPOSED FUNCTIONS ///
/// \brief Builds a new SortedListNode_s.
///
/// Implementation detail. Function responsible for allocating a new
/// SortedListNode_s.
///
/// \param[in,out] node SortedListNode_s to be allocated.
/// \param[in] data Node's data member.
///
/// \return DS_ERR_ALLOC if node allocation failed.
/// \return DS_OK if all operations are successful.
static Status sli_make_node(SortedListNode *node, void *data)
{
*node = malloc(sizeof(SortedListNode_t));
if (!(*node))
return DS_ERR_ALLOC;
(*node)->data = data;
(*node)->next = NULL;
(*node)->prev = NULL;
return DS_OK;
}
/// \brief Frees a SortedListNode_s and its data.
///
/// Implementation detail. Frees a SortedListNode_s and its data using the
/// list's default free function.
///
/// \param[in,out] node SortedListNode_s to be freed from memory.
/// \param[in] free_f List's default free function.
///
/// \return DS_ERR_NULL_POINTER if node references to \c NULL.
/// \return DS_OK if all operations are successful.
static Status sli_free_node(SortedListNode *node, sli_free_f free_f)
{
if (*node == NULL)
return DS_ERR_NULL_POINTER;
free_f((*node)->data);
free(*node);
*node = NULL;
return DS_OK;
}
/// \brief Gets a node from a specific position.
///
/// Implementation detail. Searches for a node in O(n / 2), the search starts
/// at the tail pointer if position is greater than half the list's length,
/// otherwise it starts at the head pointer.
///
/// \param[in] list SortedList_s to search for the node.
/// \param[out] result Resulting node.
/// \param[in] position Node's position.
///
/// \return DS_ERR_INVALID_OPERATION if list is empty.
/// \return DS_ERR_ITER if during iteration the scanner references to \c NULL.
/// \return DS_ERR_NEGATIVE_VALUE if position parameter is negative.
/// \return DS_ERR_NULL_POINTER if the list references to \c NULL.
/// \return DS_ERR_OUT_OF_RANGE if position parameter is greater than or equal
/// to the list's length.
/// \return DS_OK if all operations are successful.
static Status sli_get_node_at(SortedList list, SortedListNode *result,
index_t position)
{
// This function effectively searches for a given node. If the position is
// greater than the list length the search will begin at the end of the list,
// reducing the amount of iterations needed. This effectively reduces searches
// to O(n / 2) iterations.
*result = NULL;
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_empty(list))
return DS_ERR_INVALID_OPERATION;
if (position < 0)
return DS_ERR_NEGATIVE_VALUE;
if (position >= list->length)
return DS_ERR_OUT_OF_RANGE;
// Start looking for the node at the start of the list
if (position <= list->length / 2)
{
(*result) = list->head;
for (index_t i = 0; i < position; i++)
{
// Bad iteration :(
if ((*result) == NULL)
return DS_ERR_ITER;
(*result) = (*result)->next;
}
}
// Start looking for the node at the end of the list
else
{
(*result) = list->tail;
for (index_t i = list->length - 1; i > position; i--)
{
// Bad iteration :(
if ((*result) == NULL)
return DS_ERR_ITER;
(*result) = (*result)->prev;
}
}
return DS_OK;
}
/// \brief Inserts an element at the tail of the list.
///
/// Implementation detail. Used to copy a list.
///
/// \param[in] list SortedList_s to insert the element.
/// \param[in] element Element to be inserted at the tail of the list.
///
/// \return DS_ERR_FULL if the list has reached its limited length.
/// \return DS_ERR_NULL_POINTER if node references to \c NULL.
/// \return DS_OK if all operations are successful.
static Status sli_insert_tail(SortedList list, void *element)
{
if (list == NULL)
return DS_ERR_NULL_POINTER;
if (sli_full(list))
return DS_ERR_FULL;
SortedListNode node;
Status st = sli_make_node(&node, element);
if (st != DS_OK)
return st;
if (sli_empty(list))
{
list->head = node;
list->tail = node;
}
else
{
list->tail->next = node;
node->prev = list->tail;
list->tail = node;
}
(list->length)++;
return DS_OK;
}
////////////////////////////////////////////// END OF NOT EXPOSED FUNCTIONS ///
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T23:11:48.533",
"Id": "207517",
"Score": "1",
"Tags": [
"c",
"linked-list",
"generics"
],
"Title": "C Generic Sorted Doubly-Linked List"
} | 207517 |
<p>I've written an algo to compress a string</p>
<p>eg. aabcbbba to a2bcb3a</p>
<p>I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not. </p>
<p>I'm wondering how I can make this code cleaner and more functional.</p>
<p>I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const signature = `aabcbbba`;
const compressString = signature => {
return compressCharacters(groupCharacters(signature));
}
const groupCharacters = signature => {
let newSignature = "", arr = [];
// convert signature to an array
let result = [...signature].reduce((accumulator, element, index) => {
// check if last letter in accumulator matches the current element
if (accumulator[accumulator.length -1] !== element) {
// add the accumulator string into an array
arr.push(accumulator);
// clear the newSignature string and set it to current element
newSignature = element;
} else {
// if it doesn't match, add it to the accumulator
newSignature = accumulator += element;
}
// check if it's the last item - add to array
if (index === signature.length - 1) arr.push(element);
// return newSignature to accumulator
return newSignature;
})
return arr;
}
const compressCharacters = arr => {
let newArray = [];
let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))
return newArray.join("");
}
compressString(signature);</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Style notes</h2>\n<ul>\n<li>Not putting <code>{</code>, <code>}</code> around single line statement blocks is a bad habit. Always delimit statement code blocks.</li>\n<li>In <code>compressCharacters</code> <code>newArray</code> should be a constant. In <code>groupCharacters</code> <code>arr</code... | {
"AcceptedAnswerId": "207591",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T23:16:09.153",
"Id": "207518",
"Score": "2",
"Tags": [
"javascript",
"functional-programming",
"compression"
],
"Title": "String compression algorithm using functional JavaScript"
} | 207518 |
<p>First time moving from Bash to Python for scripting and looking for feedback/improvements. I've spent the weekend learning about OOP, and am aware that not fully utilizing it in this script — so any feedback is much appreciated!</p>
<p><strong>Summary</strong>: Python script runs every 5 minutes, confirms server creation/deletion via OpenStack API functioning correctly.</p>
<p><strong>Steps</strong>:</p>
<ol>
<li>Check if JSON file exists (this way we can avoid asking for new auth token, as it only expires after 12 hours). If not, get auth token and write to JSON.</li>
<li>Read JSON file, ensure auth token hasn't expired.</li>
<li>Create a new server.</li>
<li>Poll status of server every 5 seconds until 'ACTIVE', or timeout after 2 minutes.</li>
<li>Delete server.</li>
</ol>
<p>I've redacted some code, but should make sense overall. I intend to add logging after more improvements, but back to watching Python-related videos on YouTube for now.</p>
<pre><code>#!/usr/bin/env python3
from datetime import datetime, timedelta
import json
import logging
import os.path
import sys
import time
import requests
OPENSTACK_USER = 'prometheus'
OPENSTACK_PASSWORD = 'REDACTED'
OPENSTACK_PROJECT = 'Prometheus'
SERVER_NAME = 'ServerHealthCheck'
SERVER_FLAVOR = 'e4b7e835-927a-4400-9b89-6e93968f0033'
SERVER_IMAGE = '30fb86b3-31d8-4191-be7d-aacf6c317c3e'
SCRIPT_FILE = os.path.basename(__file__)
STATE_FILE = os.path.splitext(SCRIPT_FILE)[0] + '.json'
LOG_FILE = os.path.splitext(SCRIPT_FILE)[0] + '.log'
logging.basicConfig(filename=LOG_FILE,
format='%(asctime)s: %(levelname)s: %(message)s')
def _url(path):
return 'https://example.org' + path
def token_refresh():
token_request = requests.post(_url(':5000/v3/auth/tokens'), json={
'auth': {
'identity': {
'methods': ['password'],
'password': {
'user': {
'name': OPENSTACK_USER,
'domain': {'id': 'default'},
'password': OPENSTACK_PASSWORD,
}
}
},
'scope': {
'project': {
'domain': {'id': 'default'},
'name': OPENSTACK_PROJECT
}
}
}})
if not token_request.status_code == 201:
logging.error("Token refresh request returned status code {}\n{}\n"
.format(token_request.status_code, token_request.json()))
sys.exit(1)
token = {'token_content': token_request.headers['X-Subject-Token'],
'token_expires': token_request.json()["token"]["expires_at"]}
with open(STATE_FILE, 'w') as json_write:
json.dump(token, json_write)
def server_create():
create_request = requests.post(_url(':8774/v2.1/servers'), headers=headers, json={
'server': {
'name': SERVER_NAME,
'flavorRef': SERVER_FLAVOR,
'imageRef': SERVER_IMAGE
}})
if not create_request.status_code == 202:
logging.error("Server create request returned status code {}\n{}\n"
.format(create_request.status_code, create_request.json()))
sys.exit(1)
return create_request.json()["server"]["id"]
def server_status(server):
status_request = requests.get(_url(':8774/v2.1/servers/' + server), headers=headers)
return status_request.json()["server"]["status"]
def server_delete(server):
delete_request = requests.delete(_url(':8774/v2.1/servers/' + server), headers=headers)
if not delete_request.status_code == 204:
logging.error("Server delete request returned status code {}\n{}\n"
.format(delete_request.status_code, delete_request.json()))
sys.exit(1)
if __name__ == '__main__':
# Get new auth token if state file does not exist
if not os.path.isfile(STATE_FILE):
token_refresh()
# Load JSON state file as dictionary
with open(STATE_FILE, 'r') as f:
data = json.load(f)
# Get new auth token if current token expired
current_gmt = datetime.now() + timedelta(seconds=time.timezone)
if current_gmt.isoformat() >= data["token_expires"]:
token_refresh()
# Set HTTP headers with auth token
headers = {'X-Auth-Token': data["token_content"],
'Content-type': 'application/json'}
# Create new server
server = server_create()
# Poll server status
status = server_status(server)
request_seconds = 0
while not status == 'ACTIVE':
time.sleep(5)
request_seconds += 5
if request_seconds >= 120:
logging.error("Server status {} after 2 minutes".format(status))
server_delete(server)
sys.exit(1)
status = server_status(server)
# Delete server
server_delete(server)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T02:44:44.113",
"Id": "400734",
"Score": "1",
"body": "Python 2 or 3? Python 3 has `async`, which can be used instead of `time.sleep`"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T23:35:37.877",
"Id": "207520",
"Score": "3",
"Tags": [
"python",
"beginner",
"json",
"api",
"status-monitoring"
],
"Title": "Python script for OpenStack health check"
} | 207520 |
<p>I am enapsulating my license backup to disk, using an interface <em>ILicenseProvider</em> and the implementation is <em>DiskLicenseProvider</em>. Also i am throwing an unchecked exception <em>LicenseProviderException</em> which wraps the checked exceptions in order to enable a central point of exception handling. Kindly review my code. What changes should I make?</p>
<pre><code>public class LicenseProviderException extends RuntimeException {
public LicenseProviderException(String message) {
super(message);
}
}
</code></pre>
<pre><code>public class DiskLicenseProvider implements ILicenseProvider {
private static final String APP_DIRECTORY = "test";
private static final String LICENSE_FILENAME = "license.txt";
private static final String TAG = DiskLicenseProvider.class.getSimpleName();
private File appDirectory = new File(Environment.getExternalStorageDirectory(), APP_DIRECTORY);
private File licenseFile = new File(appDirectory, LICENSE_FILENAME);
@Override
public boolean licenseExists() {
return (appDirectory.exists() && licenseFile.exists() && licenseFile.length() > 0);
}
@Override
public String getLicense() throws LicenseProviderException {
StringBuilder builder = new StringBuilder();
if (licenseExists()) {
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(licenseFile));
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "getLicense() called");
throw new LicenseProviderException("Unable to find license file");
} catch (IOException e) {
Log.d(TAG, "getLicense() called");
throw new LicenseProviderException("Unable to read license file");
}
}
return builder.toString();
}
@Override
public void saveLicense(String license) throws LicenseProviderException{
if (!appDirectory.exists()) {
if (!appDirectory.mkdirs()) {
throw new LicenseProviderException("Unable to create application directory");
}
}
try {
FileWriter fileWriter = new FileWriter(licenseFile);
fileWriter.write(license);
fileWriter.close();
} catch (IOException e) {
Log.d(TAG, "saveLicense() called with: license = [" + license + "]");
throw new LicenseProviderException("Unable to save license");
}
}
}
</code></pre>
<pre><code>public interface ILicenseProvider {
boolean licenseExists();
String getLicense();
void saveLicense(String license);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T05:40:56.230",
"Id": "207529",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"android",
"file"
],
"Title": "Encapsulating simple license backup to a disk"
} | 207529 |
<p>I have found the coordinates of the centroid for finding the direction of the normal vectors of the edges of the convex polygons. This method seems to work in the cases I tested. Is this fool proof ? Are there any better alternatives ?</p>
<p><strong>CyrusBeck.cpp</strong></p>
<pre><code>#include<iostream>
#include<cmath>
#include"graphics.hpp"
#define P pair<double, double>
vector<P> V, N;
P C;
double dot(P A, P B){
return (A.first*B.first + A.second*B.second);
}
P operator - (const P &A, const P &B){
return make_pair(A.first-B.first, A.second-B.second);
}
P operator + (const P &A, const P &B){
return make_pair(A.first+B.first, A.second+B.second);
}
P operator * (const P &A, const double t){
return make_pair(t*A.first, t*A.second);
}
void computeNormal(int n = V.size()){
double m;
P prev = V[0];
double x=-1, y;
for(int i=1; i<n; ++i){
m = -(V[i].first-prev.first)/(V[i].second-prev.second);
P d = V[i]-prev;
int lr=1, tb=1;
if(V[i-1].first>C.first)
lr = -1;
if(V[i-1].second>C.second)
tb=-1;
N[i-1].first = lr*abs(cos(atan(m)));
N[i-1].second = tb*abs(sin(atan(m)));
prev = V[i];
}
m = -(V[0].first-prev.first)/(V[0].second-prev.second);
int lr=1, tb=1;
if(V[n-1].first>C.first)
lr = -1;
if(V[n-1].second>C.second)
tb=-1;
N[n-1].first = lr*abs(cos(atan(m)));
N[n-1].second = tb*abs(sin(atan(m)));
}
int check(P A, P B, int n){
P p = B - V[0];
double d1 = dot(p, N[0]);
P q = A - V[0];
double d2 = dot(q, N[0]);
if(d1<0&&d2<0)
return 0;
if(d1>=0&&d2>=0)
return 1;
return -1;
}
void Clip(P A, P B, double &tE, double &tL, int n = V.size()){
tE = 0; tL = 1;
for(int i=0; i<n; ++i){
double d = dot((B-A), N[i]);
if(d==0)
continue;
double t = dot((A-V[i]), N[i])/dot((A-B), N[i]);
if(d>0&&t>tE)
tE = t;
else if(d<0&&t<tL)
tL = t;
}
}
void display(){
cout<<"Enter the number of vertices\n";
int n; cin>>n;
V.resize(n);
N.resize(n);
cout<<"Enter the coordinates of the vertices in order\n";
for(int i=0; i<n; ++i){
cin>>V[i].first>>V[i].second;
C = C + V[i];
}
C.first/=n; C.second/=n;
drawPolygon(V, n, white);
glutSwapBuffers();
cout<<"Enter the co-ordinates of the line(4)\n";
P A, B;
cin>>A.first>>A.second>>B.first>>B.second;
drawLine(A.first, A.second, B.first, B.second, red);
glutSwapBuffers();
char c = '\0';
while(c!='Y'&&c!='y'){
cout<<"Clip? (Y/N)\n";
cin>>c;
}
computeNormal();
int chk = check(A, B, n);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
drawPolygon(V, n, white);
if(chk==-1){
double tE, tL;
Clip(A, B, tE, tL);
if(tE>tL)
chk = 0;
else{
P E = A + (B-A)*tE;
P L = A + (B-A)*tL;
drawLine(E.first, E.second, L.first, L.second, blue);
}
}
if(chk==1)
drawLine(A.first, A.second, B.first, B.second, blue);
glutSwapBuffers();
}
int main(int argc, char *argv[]){
init(&argc, argv);
}
</code></pre>
<p><strong>graphics.hpp</strong></p>
<pre><code>#ifndef GRAPHICS_H
#define GRAPHICS_H
#include<GL/glut.h>
#include<vector>
using namespace std;
extern float red[3];
extern float green[3];
extern float blue[3];
extern float white[3];
int roundoff(double x);
void init(int* argc, char** argv);
void putpixel(float x, float y, float z, float a[3]);
void drawLine(double x1, double y1, double x2, double y2, float a[3]);
void drawRectangle(double x1, double y1, double x2, double y2, float a[3]);
void drawPolygon(vector<pair<double, double>> v, int n, float a[3]);
void MatrixMultiply(vector<vector<double>> &mat1, vector<vector<double>> &mat2, vector<vector<double>> &res,
int n, int m, int r);
void display();
#endif
</code></pre>
<p><strong>graphics.cpp</strong></p>
<pre><code>#include<iostream>
#include"graphics.hpp"
float red[3] = { 1.0f, 0.0f, 0.0f };
float green[3] = { 0.0f, 1.0f, 0.0f };
float blue[3] = { 0.0f, 0.0f, 1.0f };
float white[3] = { 1.0f, 1.0f, 1.0f };
int roundoff(double x){
if (x < 0.0)
return (int)(x - 0.5);
else
return (int)(x + 0.5);
}
void init(int *argc, char** argv){
glutInit(argc, argv); // Initialize GLUT
glutInitWindowSize(800, 800); // Set the window's initial width & height
glutInitWindowPosition(0, 0); // Position the window's initial top-left corner
glutCreateWindow("Graphics"); // Create a window with the given title
gluOrtho2D(0, 800, 0, 800); // specifies the projection matrix
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
glutDisplayFunc(display); // Register display callback handler for window re-paint
glutMainLoop(); // Enter the event-processing loop
}
void putpixel(float x, float y, float z, float a[3]){
glPointSize(2);
glBegin(GL_POINTS); // HERE THE POINTS SHOULD BE CREATED
glColor3f(a[0], a[1], a[2]);
glVertex3f(x, y, z); // Specify points in 3d plane
std::cout<<x<<' '<<y<<' '<<z<<'\n';
glEnd();
}
void drawLine(double x1, double y1, double x2, double y2, float a[3]){
glLineWidth(2.5);
glColor3f(a[0], a[1], a[2]);
glBegin(GL_LINES);
glVertex2d(x1, y1);
glVertex2d(x2, y2);
glEnd();
}
void drawRectangle(double x1, double y1, double x2, double y2, float a[3]){
glColor3f(a[0], a[1], a[2]);
glRectd(x1, y1, x2, y2);
}
void drawPolygon(vector<pair<double, double>> v, int n, float a[3]){
glColor3f(a[0], a[1], a[2]);
glBegin(GL_POLYGON);
for(int i=0; i<n; ++i)
glVertex2d(v[i].first, v[i].second);
glEnd();
}
void MatrixMultiply(vector<vector<double>> &mat1, vector<vector<double>> &mat2, vector<vector<double>> &res,
int n, int m, int r){
int x, i, j;
for(i = 0; i < n; i++){
for (j = 0; j < r; j++){
res[i][j] = 0;
for (x = 0; x < m; x++){
res[i][j] += mat1[i][x] * mat2[x][j];
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T10:45:21.143",
"Id": "400635",
"Score": "0",
"body": "Welcome to Code Review. There's *a lot* to improve in your code, so I hope you get good reviews."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T06:03:03.460",
"Id": "207530",
"Score": "3",
"Tags": [
"c++",
"computational-geometry",
"graphics",
"opengl"
],
"Title": "Implementing Cyrus Beck algorithm for convex polygons"
} | 207530 |
<p>A die is rolled n times. Each time, a random value has been inserted into a vector. This vector then is used to generate a sorted map (wrongly called hashmap in the code) that is later used to create an ASCII histogram. </p>
<p>The histogram, for example, looks like this:</p>
<pre class="lang-none prettyprint-override"><code> 10
#
#
7 #
# #
# # 5
# # #
# 3 # #
# # # #
# # # 1 #
# # # # #
-----------
1 2 3 4 5 6
</code></pre>
<p>And here's the code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <random>
#include <map>
std::vector<int> roll(int times)
{
std::vector<int> rand;
while (times > 0)
{
std::random_device seeder;
std::mt19937 engine(seeder());
std::uniform_int_distribution<int> dist(1, 6);
rand.push_back(dist(engine));
--times;
}
return rand;
}
std::map<int, int> histogram_calculate(int times)
{
std::vector<int> random_numbers = roll(times);
std::map<int, int> cnt_hashmap;
auto max_element = 6;
for (int i = 1; i <= max_element; ++i)
{
cnt_hashmap[i] = 0;
}
for (auto iter = random_numbers.begin(); iter != random_numbers.end(); ++iter)
{
cnt_hashmap[*iter] += 1;
}
return cnt_hashmap;
}
std::string histogram_draw(int times)
{
std::vector<std::string> ret_vec;
std::map<int, int> histogram = histogram_calculate(times);
for (int i = 1; i <= histogram.size(); ++i)
{
std::string to_add = "";
if (histogram[i] > 0)
{
to_add = std::to_string(histogram[i]);
std::string column = "\n";
int j = 0;
while (j <= histogram[i])
{
column += "#";
column += "\n";
++j;
}
to_add += column;
}
to_add += "--";
to_add += std::to_string(i);
ret_vec.push_back(to_add);
}
std::string finalize = "";
for (auto &str : ret_vec)
{
finalize += str;
}
return finalize;
}
int main() {
std::cout << histogram_draw(10) << std::endl;
return 0;
}
</code></pre>
<p>There's three functions:</p>
<ul>
<li>One to fill the random value vector</li>
<li>One to sort out the histogram.</li>
<li>One to display the histogram.</li>
</ul>
<p>That's about it. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T07:04:33.100",
"Id": "400606",
"Score": "0",
"body": "Welcome on Code Review. I afraid to tell you that your code don't match what's this site is about. Only working (as expected) full code can be reviewed. In fact, reading your cod... | [
{
"body": "<p>The <code>roll</code> function generates a random sequence of integers. The loop body shows me that you know how to seed a pseudo-RNG with a true source of randomness but you're doing it for every iteration. You should seed the pseudo-RNG once and then use it in the loop. You know how big your <co... | {
"AcceptedAnswerId": "207539",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T06:12:34.133",
"Id": "207531",
"Score": "6",
"Tags": [
"c++",
"c++14",
"dice",
"ascii-art",
"data-visualization"
],
"Title": "An ASCII histogram of a die rolled n times"
} | 207531 |
<p>I am creating an Ellipsoid <code>class</code> and I then want to instantiate a few constants (pre-defined Ellipsoids).<br>
Below is my current implementation. I am not really satisfied with it except that it works very well but feels a but clumsy and there is probably a much cleaner way to do this. </p>
<pre><code># -*- coding: utf-8 -*-
from collections import namedtuple
ELLIPSOID_DEFS = (
(6377563.396, 299.3249646, 'airy', 'Airy 1830', 'Britain', 7001),
(6377340.189, 299.3249646, 'mod_airy', 'Airy Modified 1849', 'Ireland', 7002),
(6378160, 298.25, 'aust_SA', 'Australian National Spheroid', 'Australia', 7003),
(6377397.155, 299.1528128, 'bessel', 'Bessel 1841', 'Europe, Japan', 7004),
(6377492.018, 299.1528128, 'bessel_mod', 'Bessel Modified', 'Norway, Sweden w/ 1mm increase of semi-major axis', 7005),
(6378206.4, 294.9786982, 'clrk_66', 'Clarke 1866', 'North America', 7008),
(6378249.145, 293.465, 'clarke_rgs', 'Clarke 1880 (RGS)', 'France, Africa', 7012),
(6378249.145, 293.4663077, 'clarke_arc', 'Clarke 1880 (Arc)', 'South Africa', 7013),
(6377276.345, 300.8017, 'evrst30', 'Everest 1830 (1937 Adjustment)', 'India', 7015),
(6377298.556, 300.8017, 'evrstSS', 'Everest 1830 (1967 Definition)', 'Brunei & East Malaysia', 7016),
(6377304.063, 300.8017, 'evrst48', 'Everest 1830 Modified', 'West Malaysia & Singapore', 7018),
(6378137, 298.257222101, 'grs80', 'GRS 1980', 'Global ITRS', 7019),
(6378200, 298.3, 'helmert', 'Helmert 1906', 'Egypt', 7020),
(6378388, 297, 'intl', 'International 1924', 'Europe', 7022),
(6378245, 298.3, 'krass', 'Krassowsky 1940', 'USSR, Russia, Romania', 7024),
(6378145, 298.25, 'nwl9d', 'NWL 9D', 'USA/DoD', 7025),
(6376523, 308.64, 'plessis', 'Plessis 1817', 'France', 7027),
(6378137, 298.257223563, 'wgs84', 'WGS 84', 'Global GPS', 7030),
(6378160, 298.247167427, 'grs67', 'GRS 1967', '', 7036),
(6378135, 298.26, 'wgs72', 'WGS 72', 'USA/DoD', 7043),
(6377301.243, 300.8017255, 'everest_1962', 'Everest 1830 (1962 Definition)', 'Pakistan', 7044),
(6377299.151, 300.8017255, 'everest_1975', 'Everest 1830 (1975 Definition)', 'India', 7045),
(6377483.865, 299.1528128, 'bess_nam', 'Bessel Namibia (GLM)', 'Namibia', 7046),
(6377295.664, 300.8017, 'evrst69', 'Everest 1830 (RSO 1969)', 'Malaysia', 7056)
)
"""
Ellipsdoids = definitions: as per above 'a rf alias name area epsg'
"""
Ellipsoid_Definition = namedtuple('Ellipsoid_Definition', 'a rf alias name area epsg')
class Ellipsoid():
def __init__(self, a, rf, alias='user', name='User Defined', area='local', epsg=None):
self.a = a
self.rf = rf
self.alias = alias
self.name = name
self.area = area
self.epsg = epsg
def __repr__(self):
return f'<Ellipsoid(name="{self.name}", epsg={self.epsg}, a={self.a}, rf={self.rf})>'
@property
def b(self):
# semi-minor axis
return self.a * (1 - 1 / self.rf)
@property
def e2(self):
# squared eccentricity
rf = self.rf
return (2 - 1 / rf) / rf
@property
def n(self):
# third flattening
a = self.a
b = self.b
return (a - b) / (a + b)
@classmethod
def from_def(cls, ellps_def):
if isinstance(ellps_def, Ellipsoid_Definition):
return cls(ellps_def.a, ellps_def.rf, alias=ellps_def.alias, name=ellps_def.name, area=ellps_def.area, epsg=ellps_def.epsg)
else:
raise ValueError('invalid ellipsoid definition')
class Ellipsoids():
def __init__(self, ellps_defs=ELLIPSOID_DEFS):
for ellps_def in ellps_defs:
ellps = Ellipsoid_Definition(*ellps_def)
self.__dict__[ellps.alias] = Ellipsoid(*ellps)
ELLIPSOIDS = Ellipsoids()
</code></pre>
| [] | [
{
"body": "<p>I would explicitly refer the constants in class variables :</p>\n\n<pre><code>class Elipsoids:\n airy = Elipsoid(6377563.396, 299.3249646, 'airy', 'Airy 1830', 'Britain', 7001),\n mod_airy = Elipsoid(6377340.189, 299.3249646, 'mod_airy', 'Airy Modified 1849', 'Ireland', 7002),\n ...\n</co... | {
"AcceptedAnswerId": "207567",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T10:56:00.380",
"Id": "207545",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"constants"
],
"Title": "Class with predefined ellipsoids"
} | 207545 |
<p>The below code works as intended and I'm generally happy with it - the sliders each change an RGB value to modify the color of the circle in circlePanel.
Likewise the diameter slider changes the size.</p>
<p>Could the code be refactored/restructured to make it better/more readable?
The CircleSlider constructor is quite long - I'm wondering could some of it be removed to separate methods/classes.</p>
<p>CircleSlider.java</p>
<pre><code>//import statements
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
//CircleSlider class to setup GUI and main logic
public class CircleSlider extends JFrame{
//instantiate GUI components
private final JPanel circlePanel;
private final JSlider diameterSlider, redSlider, greenSlider, blueSlider;
private final JLabel diameterLabel, redLabel, greenLabel, blueLabel;
private final JTextArea displayArea;
private final GridBagLayout layout;
private final GridBagConstraints constraints;
//circle properties
private int diameter = 75;
private Color circleColor;
//constructor to set up GUI
public CircleSlider(){
//call to JFrame constructor to set title
super("Circle Slider");
//create new layout
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
//add calculation display area
displayArea = new JTextArea(6,10);
displayArea.setText("Adjust the diameter slider to see information on the circle");
addComponent(displayArea, 14, 0, 20, 8, 1, 1,
GridBagConstraints.BOTH, GridBagConstraints.CENTER);
//add JPanel to house the circle
circlePanel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
//set color of drawn graphics
g.setColor(circleColor);
//Draw circle in centre of circlePanel
g.fillOval((circlePanel.getWidth() - diameter) / 2, (circlePanel.getHeight() - diameter) / 2,
diameter, diameter);
}
};
addComponent(circlePanel, 1, 3, 16, 11, 1, 1,
GridBagConstraints.BOTH, GridBagConstraints.CENTER);
//add label for diameter slider
diameterLabel = new JLabel("Diameter");
addComponent(diameterLabel, 1, 1, 1, 1, 0, 1,
GridBagConstraints.NONE, GridBagConstraints.WEST);
//add the slider to control diameter of circle
diameterSlider = new JSlider(0, 150, 50);
//add listener as anonymous inner class
diameterSlider.addChangeListener(
new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
double radius = diameter / 2.0;
setDiameter(diameterSlider.getValue());
String message = String.format(
"Diameter: %d%nArea: %.2f%nCircumference: %.2f",
diameter, getArea(radius), getCircumference(radius));
displayArea.setText(message);
}
}
);
addComponent(diameterSlider, 2, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
//create listener for color sliders
SliderListener sliderListener = new SliderListener();
//add redSlider and label
redLabel = new JLabel("RGB: Red");
addComponent(redLabel, 4, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
redSlider = new JSlider(0, 255, 0);
redSlider.addChangeListener(sliderListener);
addComponent(redSlider, 5, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
//add greenSlider and label
greenLabel = new JLabel("RGB: Green");
addComponent(greenLabel, 7, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
greenSlider = new JSlider(0, 255, 0);
greenSlider.addChangeListener(sliderListener);
addComponent(greenSlider, 8, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
//add blueSlider and label
blueLabel = new JLabel("RGB: Blue");
addComponent(blueLabel, 11, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
blueSlider = new JSlider(0, 255, 0);
blueSlider.addChangeListener(sliderListener);
addComponent(blueSlider, 12, 1, 1, 1, 0, 1, GridBagConstraints.NONE,
GridBagConstraints.WEST);
}
//ChangeListener for color sliders - implemented as private inner class as
//all color sliders perform same method, setColor()
class SliderListener implements ChangeListener{
@Override
public void stateChanged(ChangeEvent e){
setColor(redSlider.getValue(), greenSlider.getValue(), blueSlider.getValue());
}
}
//helper method to add a component to JPanel or JFrame
private void addComponent(Component component, int row, int column, int width, int height,
int weightx, int weighty, int fillConstraint, int anchorConstraint) {
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.fill = fillConstraint;
constraints.anchor = anchorConstraint;
layout.setConstraints(component, constraints);
add(component);
}
//set the diameter of the circle
private void setDiameter(int newDiameter){
//if new diameter is negative, set to 10
diameter = newDiameter >= 0 ? newDiameter : 10;
repaint();
}
//set the color of the circle
private void setColor(int newRed, int newGreen, int newBlue){
circleColor = new Color(
//if any given color is negative, set to 10
newRed >= 0 ? newRed : 10,
newGreen >= 0 ? newGreen : 10,
newBlue >= 0 ? newBlue : 10);
getGraphics().setColor(circleColor);
repaint();
}
//Find the area of a circle given the radius
private double getArea(double radius){
return Math.PI * Math.pow((radius), 2);
}
//find circumference of circle given the radius
private double getCircumference(double radius){
return 2 * Math.PI * radius;
}
}
</code></pre>
<p>CircleSliderTest.java</p>
<pre><code>import javax.swing.*;
public class CircleSliderTest {
public static void main(String[] args){
CircleSlider app = new CircleSlider();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(600,400);
app.setVisible(true);
}
}
</code></pre>
| [] | [
{
"body": "<p>1) Is your CircleSlider really a window? Your code says yes, but as a user, I would find that quite strange. Your CircleSlider should use JFrame as an instance. You can see that clearly in your main method. You are using three methods from it. What about the rest? JFrame has probably 30 methods or... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T11:12:16.410",
"Id": "207546",
"Score": "1",
"Tags": [
"java",
"swing",
"gui"
],
"Title": "Swing GUI application to change colour of circle with JSlider"
} | 207546 |
<p>I've a code that process buffers of samples/audio data. <a href="http://coliru.stacked-crooked.com/a/abf7a13a737e76b8" rel="nofollow noreferrer">Here's</a> the code:</p>
<pre><code>#include <iostream>
#include <math.h>
#include <cstring>
#include <algorithm>
#define PI 3.141592653589793238
#define TWOPI 6.283185307179586476
const int blockSize = 256;
const double mSampleRate = 44100.0;
const double mHostPitch = 2.0;
const double mRadiansPerSample = TWOPI / mSampleRate;
double mGainNormalizedValues[blockSize];
double mPitchNormalizedValues[blockSize];
double mOffsetNormalizedValues[blockSize];
class Oscillator
{
public:
double mPhase = 0.0;
double minPitch = -48.0;
double maxPitch = 48.0;
double rangePitch = maxPitch - minPitch;
double pitchPd = log(2.0) / 12.0;
double minOffset = -900.0;
double maxOffset = 900.0;
double rangeOffset = maxOffset - minOffset;
Oscillator() { }
void ProcessBuffer(double voiceFrequency, int blockSize, double *left, double *right) {
// precomputed data
double bp0 = voiceFrequency * mHostPitch;
// process block
for (int sampleIndex = 0; sampleIndex < blockSize; sampleIndex++) {
double output = (sin(mPhase)) * mGainNormalizedValues[sampleIndex];
*left++ += output;
*right++ += output;
// next phase
mPhase += std::clamp(mRadiansPerSample * (bp0 * WarpPitch(mPitchNormalizedValues[sampleIndex])) + WarpOffset(mOffsetNormalizedValues[sampleIndex]), 0.0, PI);
while (mPhase >= TWOPI) { mPhase -= TWOPI; }
}
}
inline double WarpPitch(double normalizedValue) { return exp((minPitch + normalizedValue * rangePitch) * pitchPd); }
inline double WarpOffset(double normalizedValue) { return minOffset + normalizedValue * rangeOffset; }
};
int main(int argc, const char *argv[]) {
int numBuffer = 1024;
int counterBuffer = 0;
Oscillator oscillator;
// I fill the buffer often
while (counterBuffer < numBuffer) {
// init buffer
double bufferLeft[blockSize];
double bufferRight[blockSize];
memset(&bufferLeft, 0, blockSize * sizeof(double));
memset(&bufferRight, 0, blockSize * sizeof(double));
// emulate params values for this buffer
for(int i = 0; i < blockSize; i++) {
mGainNormalizedValues[i] = i / (double)blockSize;
mPitchNormalizedValues[i] = i / (double)blockSize;
mOffsetNormalizedValues[i] = i / (double)blockSize;
}
// process osc buffer
oscillator.ProcessBuffer(130.81278, blockSize, &bufferLeft[0], &bufferRight[0]);
// do somethings with buffer
counterBuffer++;
}
}
</code></pre>
<p>Basically:</p>
<ol>
<li>init a Oscillator object</li>
<li>for each buffer, fill some param arrays with values (gain, pitch, offset); gain remain normalized <code>[0.0, 1.0]</code>, while pitch and offset range in <code>-48/48</code> and <code>-900/900</code></li>
<li>then I iterate the buffer, calculating the Oscillator's sine due to pitch and offset, and I apply a gain; later, I move the phase, incrementing it</li>
</ol>
<p>The whole domain of operations are normalized <code>[0.0, 1.0]</code>. But when I need to manage pitch and offset, I need to switch domain and use different values (i.e. the Warp functions).</p>
<p>This required lots of computations and process. I'd like to avoid it, so I can improve the code and performances.</p>
<p>How would you do it? Can I keep into <code>[0.0, 1.0]</code>? Could I improve the performance?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T15:57:53.270",
"Id": "400654",
"Score": "0",
"body": "Does it make sense to add optimization that rely on the phase offset per step to be stable for a while, or is it always expected to fluctuate on a sample by sample basis?"
},
... | [
{
"body": "<h1>Prefer C++ headers</h1>\n\n<p>Instead of <code><math.h></code>, it's better to include <code><cmath></code> and qualify names such as <code>std::log</code>.</p>\n\n<h1>Prefer constants to macros</h1>\n\n<p>Re-write <code>pi</code> as a strongly-typed, scoped variable rather than a pre... | {
"AcceptedAnswerId": "207571",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T11:18:49.140",
"Id": "207547",
"Score": "1",
"Tags": [
"c++",
"performance",
"signal-processing"
],
"Title": "Audio processing with normalized [0.0, 1.0] domain"
} | 207547 |
<p>I am working on a custom Bootstrap 3 carousel, with vertical, unidirectional, slide transitions.</p>
<p>I want to prevent slide transitions from overlapping when the bullets are clicked in random order and rapid succession.</p>
<p>I came up with this solution that relies on <em>disabling them as long as a slide transition is in progress</em>, then enabling them between transitions: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var carouselDuration = function() {
$.fn.carousel.Constructor.TRANSITION_DURATION = 1000;
}
carouselDuration();
// While a transition is in progress (slide event), do this
$('#myCarousel').on('slide.bs.carousel', function (e) {
var $indicator = $(this).find('.carousel-indicators>li');
$indicator.css('pointer-events', 'none');
});
// While a transition has finished (slid event), do this
$('#myCarousel').on('slid.bs.carousel', function (e) {
var $indicator = $(this).find('.carousel-indicators>li');
$indicator.css('pointer-events', 'auto');
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.carousel.vertical {
position: relative;
}
.carousel.vertical .carousel-inner {
height: 100%;
width: auto;
}
.carousel.vertical .carousel-inner>.item {
width: auto;
transition: 1s ease-in-out;
transform: translate3d(0, 100%, 0);
top: 0;
}
.carousel.vertical .carousel-inner>.next,
.carousel.vertical .carousel-inner>.prev,
.carousel.vertical .carousel-inner>.right {
transform: translate3d(0, 100%, 0);
top: 0;
}
.carousel.vertical .carousel-inner>.left,
.carousel.vertical .carousel-inner>.prev.right,
.carousel.vertical .carousel-inner>.next.left,
.carousel.vertical .carousel-inner>.active {
transform: translate3d(0, 0, 0);
top: 0;
}
.carousel.vertical .carousel-inner>.active.right,
.carousel.vertical .carousel-inner>.active.left {
transform: translate3d(0, -100%, 0);
top: 0;
}
.carousel.vertical .carousel-indicators {
display: inline-block;
width: auto;
padding: 0;
margin: 0;
left: auto;
right: 10px;
bottom: 2px;
z-index: 9;
font-size: 0;
}
.carousel.vertical .carousel-indicators li {
border: none;
cursor: pointer;
display: inline-block;
width: 18px;
height: 18px;
text-indent: -9999px;
background: url("https://grgs.ro/1/i/sprite.png") no-repeat -528px -502px;
}
.carousel.vertical .carousel-indicators li.active {
background-position: -528px -524px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div id="myCarousel" class="carousel vertical slide" data-ride="carousel" data-interval="9000">
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="https://picsum.photos/1200/300/?gravity=east" alt="">
</div>
<div class="item">
<img src="https://picsum.photos/1200/300/?gravity=south" alt="">
</div>
<div class="item">
<img src="https://picsum.photos/1200/300/?gravity=west" alt="">
</div>
</div>
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Still, I am looking for a <strong>queuing</strong> mechanism, as it is more natural and elegant.</p>
| [] | [
{
"body": "<h2>Feedback</h2>\n\n<p>The code seems fairly concise, though I do have suggestions below that can simplify it even more. I was hoping there was some class name applied to the element with class <em>carousel</em> during the slide transition but apparently the bootstrap code does not do that, though y... | {
"AcceptedAnswerId": "208185",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T13:19:08.047",
"Id": "207554",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"css",
"animation",
"twitter-bootstrap"
],
"Title": "Unidirectional Bootstrap 3 carousel"
} | 207554 |
<pre><code> public static GeneratePassword(minPassLength) {
let small = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split(' ');
let big = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split(' ');
let numbers = "0 1 2 3 4 5 6 7 8 9".split(' ');
let special = "! \" # $ % & ( ) * + - . : ; < = > ? @ [ \ ] _ { | }".split(' ');
var pass = "";
for (let i = 0; i < minPassLength; i++) {
pass += small[this.randomIntFromInterval(0, small.length - 1)];
}
for (let i = 0; i < minPassLength / 4; i++) {
pass += big[this.randomIntFromInterval(0, big.length - 1)];
}
for (let i = 0; i < minPassLength / 4; i++) {
pass += numbers[this.randomIntFromInterval(0, numbers.length - 1)];
}
for (let i = 0; i < minPassLength / 4; i++) {
pass += special[this.randomIntFromInterval(0, special.length - 1)];
}
pass = pass.split('').sort(function () { return 0.5 - Math.random() }).join('');
return pass;
}
private static randomIntFromInterval(min, max) // min and max included
{
return Math.floor(Math.random() * (max - min + 1) + min);
}
</code></pre>
<p>A simple function to generate a new password with at least X (this is function parameter) chars including 1 special, 1 number and 1 uppercase.</p>
<p>Please a code review :-)</p>
| [] | [
{
"body": "<p>You've four for-loops that are doing the same with different input. Make a function for this logic and call it with the different arrays.</p>\n\n<p>I don't know how typescript handles it and how often you call this function, but it could be better to define your characters outside of this because ... | {
"AcceptedAnswerId": "207575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T15:04:28.177",
"Id": "207565",
"Score": "2",
"Tags": [
"strings",
"random",
"typescript"
],
"Title": "New password generation"
} | 207565 |
<p>I am learning how to code in Python by myself and have never coded before, I just want to know if there is any way I can upgrade my PasswordGenerator.</p>
<pre><code>#!/usr/bin/env python3
import random
def passwordgenerator():
mypw = ""
count = 0
alphabet_number = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
symbols = "!?@%#$"
running1 = True
while running1:
if len(symbols) == 1:
# Reset symbols
symbols = "!?@%#$"
if len(alphabet_number) == 1:
# Reset letters/numbers
alphabet_number = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
elif count == pw_length:
if mypw.isupper() or mypw.islower(): # check if there is only upper or only lower letter and rerun if True
passwordgenerator()
else:
x = mypw
y = list(x) # creates a list and put the pw in to shuffle it
random.shuffle(y)
mypw = "".join(y)
print(mypw)
input("\nPress <Enter> to close the program")
running1 = False
elif count % 4 == 0:
# pick a random symbol every 3 loop and add it to the pw
symbols_index = random.randrange(len(symbols))
new_symbols = symbols[symbols_index]
mypw = mypw + new_symbols
# delete the symbols that is picked so there are no duplicate
symbols_list_change = symbols.replace(new_symbols, "")
symbols = symbols_list_change
else:
# pick a random number or letter and add it to the pw
next_index = random.randrange(len(alphabet_number))
new_alphabetnumber = alphabet_number[next_index]
mypw = mypw + new_alphabetnumber
# delete the symbols that is picked so there are no duplicate
an_list_change = alphabet_number.replace(new_alphabetnumber, "")
alphabet_number = an_list_change
count += 1
if __name__ == '__main__':
print("/!\ 12 Characters is a minimum for good security /!\ ")
print("=" * 55) # just to make it pretty
running = True
while running:
pw_length = input("How many Characters do you want?\n")
if pw_length.isdigit(): # verify if user input a number
pw_length = int(pw_length)
passwordgenerator()
running = False
else:
print("A number is needed")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T16:37:10.657",
"Id": "400659",
"Score": "0",
"body": "Why does \"reset letters/numbers\" assign to `symbols`? Is that a bug?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T09:23:44.267",
"Id": "... | [
{
"body": "<p>Not bad a all for a first Python program:</p>\n\n<ul>\n<li>Good use of the line: <code>if __name__ == '__main__':</code> .</li>\n<li>Good use of string methods (<code>replace</code>, <code>isupper</code>, <code>islower</code> etc...). </li>\n<li>Good use of the random module methods.</li>\n</ul>\n... | {
"AcceptedAnswerId": "207588",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T15:57:28.047",
"Id": "207569",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings",
"random"
],
"Title": "Password generator in Python 3.7"
} | 207569 |
<p>I have come up with a recursive function which applies <code>trim()</code> recursively to all string members of an array/object.</p>
<p>I don't have any specific quandaries about my code so I am receptive to all feedback.</p>
<p>My goal is maximum compatibility for all PHP versions: past, present, and future.</p>
<pre><code><?php
/**
* trim_r
*
* Recursively trim an array's or object's string values
* Preserves all non-string values
*
* @access public
* @param mixed
* @param mixed
* @return mixed
*/
function &trim_r( &$o, $character_mask = null )
{
// Only apply trim() to strings
if( is_string( $o ) )
{
// Respect the $character_mask; cannot pass null as 2nd parameter for some HHVM versions
$o = ( $character_mask === null ? trim( $o ) : trim( $o, $character_mask ) );
}
elseif( is_array( $o ) || is_object( $o ) )
{
// Loop this array/object and apply trim_r() to its members
foreach( $o as &$v )
{
trim_r( $v );
}
}
// Supply this just in case the invoker wishes to receive result as a reference
return $o;
}
</code></pre>
| [] | [
{
"body": "<p>Avoid if-else nesting to keep things flat. Return inside the first if is enough to do so.</p>\n\n<hr>\n\n<p>I added <code>is_iterable()</code> so this function can handle more types than just array</p>\n\n<pre><code>/**\n * trim_r\n *\n * Recursively trim an array's or object's string values\n * P... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T16:04:11.880",
"Id": "207570",
"Score": "1",
"Tags": [
"php",
"strings",
"array",
"recursion"
],
"Title": "Recursive trim() function to handle arrays and objects"
} | 207570 |
<p>I would like to receive some feedback on the code I am currently using to display x amount of images on my website per</p>
<pre><code>$success = true;
$page = array_key_exists('page', $_GET) ? $_GET['page'] : 1;
$all_pictures = glob('crossles/*.jpg');
$total_images = 0;
foreach ($all_pictures as $img_total) {
$total_images++;
}
$images_per_page = 30;
$max_pages = ceil($total_images / $images_per_page);
if ($page <= -1) {
$success = false;
}
if ($page > $max_pages) {
$success = false;
}
if ($success === false) {
echo "<div class='container text-center'><p class='text-danger fs-32 mt-100'>No pictures to be displayed.</p></div>";
}
</code></pre>
<p>I know that <code>$_GET</code> is not the safest way of doing this but since it is only to retrieve images I don't think it is that big of an issue.</p>
<p>It would be nice if I could get some feedback to implement it to my code if needed.</p>
| [] | [
{
"body": "<p>If you are concerned about using GET data then consider using POST data. You could also consider using <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow noreferrer\"><code>filter_input()</code></a> or <a href=\"http://php.net/filter_var\" rel=\"nofollow noreferrer\"><co... | {
"AcceptedAnswerId": "207581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T17:52:55.497",
"Id": "207577",
"Score": "2",
"Tags": [
"php",
"validation",
"image"
],
"Title": "Split all images over x amount of pages with $_GET"
} | 207577 |
<p>The problem consists of two categories of events (Work and Rest) which together form a complete set.
The number of Work events is open-ended.
The number of Rest events is fixed at three (3).
The events must be completed in the order as indicated for each category.
Each attempt at an event is recorded as an Activity and the order of the attempt is designated as ActivityOrder.
An Activity consisting of a Rest event establishes the termination of all Work events associated with the set.
An Activity consisting of a Work event establishes the termination of all Rest events associated with the previous set and initiates a new set.
Each (Work/Rest) set is designated as a Group.</p>
<p>The final result must consist of at least one (1) Group.
The final result must include the ActivityOrder for only those events which were completed in order.
Each Group must present the full (Work/Rest) set even if no events which qualified were completed in order.
It is possible that a Group consist of no events which were completed in order.</p>
<p>What I have seems to do what I intend but I imagine that there is some way to produce the desired result more efficiently. Therefore, I welcome any improvements to the following code:</p>
<pre><code>declare @Work table (
ID int identity,
[Order] tinyint,
EventID int
);
declare @Rest table (
ID int identity,
Event01 int,
Event02 int,
Event03 int
);
declare @Activity table (
ID int identity,
EventID int,
[Order] int,
IsComplete bit
);
insert @Work ([Order], EventID)
values
(1, 4),
(2, 9),
(3, 1),
(4, 3);
insert @Rest (Event01, Event02, Event03)
values
(2, 5, 7);
--Work events must be unique
--Rest events must be unique
--Sequence of work order must initiate with 1 and be complete
--Work and Rest events may not coincide
insert @Activity (EventID, [Order], IsComplete)
values
(3, 1, 1), --Test
(6, 2, 1),
(7, 3, 1), --FA
(1, 4, 0), --Test
(4, 5, 1), --Test
(4, 6, 0), --Test
(4, 7, 1), --Test
(9, 8, 1), --Test
(2, 9, 1), --FA
(2, 10, 1), --FA
(8, 11, 0),
(5, 12, 1), --FA
(1, 13, 1), --Test
(7, 14, 1), --FA
(9, 15, 0), --Test
(5, 16, 1), --FA
(4, 17, 1); --Test
with
cteWR as (
select
'Test' as Category,
NULL as [Type],
[Order],
EventID
from @Work
union
select
'FA' as Category,
Name as [Type],
case Name
when 'Event01'
then 1
when 'Event02'
then 2
when 'Event03'
then 3
end as [Order],
Value as StationTypeID
from (
select
Event01,
Event02,
Event03
from @Rest
) as R
unpivot (
Value for Name in (
Event01, Event02, Event03
)
) as upR
),
cteWRA as (
select
cteWR.Category,
cteWR.[Type],
cteWR.[Order],
cteWR.EventID,
oaA.[Order] as ActivityOrder,
oaA.IsComplete
from cteWR
outer apply (
select
vA.[Order],
vA.IsComplete
from @Activity as vA
where vA.EventID = cteWR.EventID
) as oaA
),
cteWRA_R as (
select
1 as [Group],
TestMin,
isnull(TestMax, TestMin) as TestMax,
FAMin,
isnull(FAMax, FAMin) as FAMax
from (
select
case
when WRA.TestMin > WRA.FAMin
then NULL
else WRA.TestMin
end as TestMin,
(select
sWRA.ActivityOrder
from (
select
row_number() over (order by cteWRA.ActivityOrder desc) as RN,
cteWRA.ActivityOrder
from cteWRA
where 1 = 1
and cteWRA.Category = 'Test'
and WRA.TestMin < WRA.FAMin
and cteWRA.ActivityOrder < WRA.FAMin
) as sWRA
where sWRA.RN = 1) as TestMax,
WRA.FAMin,
(select
sWRA.ActivityOrder
from (
select
row_number() over (order by cteWRA.ActivityOrder desc) as RN,
cteWRA.ActivityOrder
from cteWRA
outer apply (
select
row_number() over (order by cteWRA.ActivityOrder) as RN,
cteWRA.ActivityOrder
from cteWRA
where 1 = 1
and cteWRA.Category = 'Test'
and cteWRA.ActivityOrder > WRA.FAMin
) as oaWRA
where 1 = 1
and cteWRA.Category = 'FA'
and (
1 <> 1
or (
oaWRA.ActivityOrder > cteWRA.ActivityOrder
and oaWRA.RN = 1
)
or oaWRA.RN is NULL
)
) as sWRA
where sWRA.RN = 1) as FAMax
from (
select
(select
ActivityOrder
from (
select
row_number() over (order by ActivityOrder) as RN,
ActivityOrder
from cteWRA
where Category = 'Test'
) as WRA
where RN = 1) as TestMin,
(select
ActivityOrder
from (
select
row_number() over (order by ActivityOrder) as RN,
ActivityOrder
from cteWRA
where Category = 'FA'
) as WRA
where RN = 1) as FAMin
) as WRA
) as WRA
union all
select
[Group] + 1 as [Group],
TestMin,
isnull(TestMax, TestMin) as TestMax,
FAMin,
isnull(FAMax, FAMin) as FAMax
from (
select
cteWRA_R.[Group],
case
when caWRA_R.FAMin < caWRA_R.TestMin
then NULL
else caWRA_R.TestMin
end as TestMin,
(select
WRA.ActivityOrder
from (
select
row_number() over (order by cteWRA.ActivityOrder desc) as RN,
cteWRA.ActivityOrder
from cteWRA
where 1 = 1
and cteWRA.Category = 'Test'
and caWRA_R.FAMin > caWRA_R.TestMin
and cteWRA.ActivityOrder < caWRA_R.FAMin
) as WRA
where WRA.RN = 1) as TestMax,
caWRA_R.FAMin,
(select
WRA.ActivityOrder
from (
select
row_number() over (order by cteWRA.ActivityOrder desc) as RN,
cteWRA.ActivityOrder
from cteWRA
cross join (
select
row_number() over (order by cteWRA.ActivityOrder) as RN,
cteWRA.ActivityOrder
from cteWRA
where 1 = 1
and cteWRA.Category = 'Test'
and cteWRA.ActivityOrder > caWRA_R.FAMin
) as cjWRA
where 1 = 1
and cteWRA.Category = 'FA'
and (
1 <> 1
or (
cjWRA.ActivityOrder > cteWRA.ActivityOrder
and cjWRA.RN = 1
)
or cjWRA.RN is NULL
)
) as WRA
where WRA.RN = 1) as FAMax
from cteWRA_R
cross apply (
select
(select
WRA.ActivityOrder
from (
select
row_number() over (order by cteWRA.ActivityOrder) as RN,
cteWRA.ActivityOrder
from cteWRA
where 1 = 1
and cteWRA.Category = 'Test'
and cteWRA.ActivityOrder > cteWRA_R.FAMax
) as WRA
where WRA.RN = 1) as TestMin,
(select
WRA.ActivityOrder
from (
select
row_number() over (order by cteWRA.ActivityOrder) as RN,
cteWRA.ActivityOrder
from cteWRA
where 1 = 1
and cteWRA.Category = 'FA'
and cteWRA.ActivityOrder > cteWRA_R.FAMax
) as WRA
where WRA.RN = 1) as FAMin
) as caWRA_R
where coalesce(caWRA_R.TestMin, caWRA_R.FAMin) is not NULL
) as WRA_R
),
cteWRA_G as (
select
[Group],
[Type] as Category,
max([Min]) as [Min],
max([Max]) as [Max]
from (
select
[Group],
[Type],
case
when right(Names, 3) = 'Min'
then nullif(Name, 0)
end as [Min],
case
when right(Names, 3) = 'Max'
then nullif(Name, 0)
end as [Max]
from (
select
cteWRA_R.[Group],
caType.Name as [Type],
isnull(cteWRA_R.TestMin, 0) as TestMin,
isnull(cteWRA_R.TestMax, 0) as TestMax,
isnull(cteWRA_R.FAMin, 0) as FAMin,
isnull(cteWRA_R.FAMax, 0) as FAMax
from cteWRA_R
cross apply (
values
('Test'),
('FA')
) as caType (Name)
) as WRA_R
unpivot (
Name for Names in (
TestMin, TestMax, FAMin, FAMax
)
) as upWRA_R
where left(Names, len([Type])) = [Type]
) as WRA_R
group by
[Group],
[Type]
),
cteWRA2 as (
select
[Group],
Category,
[Type],
[Order],
EventID,
min(ActivityOrder) as ActivityOrder
from (
select
cteWRA_G.[Group],
cteWRA_G.Category,
WRA.[Type],
WRA.[Order],
WRA.EventID,
case
when WRA.ActivityOrder between cteWRA_G.[Min] and cteWRA_G.[Max]
or WRA.ActivityOrder is NULL
then WRA.ActivityOrder
end as ActivityOrder
from cteWRA_G
join (
select
cteWRA.Category,
cteWRA.[Type],
cteWRA.[Order],
cteWRA.EventID,
case
when isnull(ljWRA.ActivityOrder, 0) < cteWRA.ActivityOrder
and cteWRA.IsComplete = 1
then cteWRA.ActivityOrder
end as ActivityOrder
from cteWRA
left join (
select
Category,
[Type],
[Order],
ActivityOrder
from cteWRA
where IsComplete = 0
) as ljWRA
on 1 = 1
and ljWRA.Category = cteWRA.Category
and (
ljWRA.[Type] = cteWRA.[Type]
or coalesce(ljWRA.[Type], cteWRA.[Type]) is NULL
)
and ljWRA.[Order] = cteWRA.[Order]
) as WRA
on WRA.Category = cteWRA_G.Category
) as WRA2
group by
[Group],
Category,
[Type],
[Order],
EventID
),
cteWRA_R2 as (
select
[Group],
Category,
[Type],
[Order],
EventID,
ActivityOrder,
case
when ActivityOrder is NULL
then 1
else 0
end as IsDone
from cteWRA2
where [Order] = 1
union all
select
cteWRA_R2.[Group],
cteWRA_R2.Category,
caWRA2.[Type],
caWRA2.[Order],
caWRA2.EventID,
case cteWRA_R2.IsDone
when 0
then caWRA2.ActivityOrder
end as ActivityOrder,
case
when caWRA2.ActivityOrder is NULL
or cteWRA_R2.IsDone = 1
then 1
else 0
end as IsDone
from cteWRA_R2
cross apply (
select
cteWRA2.[Type],
cteWRA2.[Order],
cteWRA2.EventID,
cteWRA2.ActivityOrder
from cteWRA2
where 1 = 1
and cteWRA2.[Group] = cteWRA_R2.[Group]
and cteWRA2.Category = cteWRA_R2.Category
and cteWRA2.[Order] = cteWRA_R2.[Order] + 1
) as caWRA2
)
select
[Group],
Category,
[Type],
[Order],
EventID,
ActivityOrder
from cteWRA_R2
order by
[Group],
case Category
when 'Test'
then 1
when 'FA'
then 2
end,
[Order];
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T19:29:59.840",
"Id": "207584",
"Score": "1",
"Tags": [
"sql",
"sql-server"
],
"Title": "Activity grouping and selection according to order and completion requirements"
} | 207584 |
<p>When using dependency injection for nearly everything it's good to have some file access abstraction. I find the idea of ASP.NET Core <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-2.1" rel="noreferrer">FileProvider</a> nice but not sufficient for my needs so inspired by that I decided to create my own with some more functionality.</p>
<p><a href="https://codereview.stackexchange.com/questions/209939/multiple-file-access-abstractions-follow-up-redesign">Follow-up</a></p>
<hr />
<h3>Interfaces</h3>
<p>I have two interfaces that are called just like theirs but they have different members and also other names.</p>
<p>The first interface represents a single file or a directory.</p>
<pre><code>[PublicAPI]
public interface IFileInfo : IEquatable<IFileInfo>, IEquatable<string>
{
[NotNull]
string Path { get; }
[NotNull]
string Name { get; }
bool Exists { get; }
long Length { get; }
DateTime ModifiedOn { get; }
bool IsDirectory { get; }
[NotNull]
Stream CreateReadStream();
}
</code></pre>
<p>The other interface allows me to perform four of the basic file/directory operations:</p>
<pre><code>[PublicAPI]
public interface IFileProvider
{
[NotNull]
IFileInfo GetFileInfo([NotNull] string path);
[NotNull]
IFileInfo CreateDirectory([NotNull] string path);
[NotNull]
IFileInfo DeleteDirectory([NotNull] string path, bool recursive);
[NotNull]
Task<IFileInfo> CreateFileAsync([NotNull] string path, [NotNull] Stream data);
[NotNull]
IFileInfo DeleteFile([NotNull] string path);
}
</code></pre>
<hr />
<p>On top of them I've build three providers:</p>
<ul>
<li><code>PhysicalFileProvider</code> and <code>PhysicalFileInfo</code> - used for operation on the physical drive</li>
<li><code>EmbeddedFileProvider</code> and <code>EmbeddedFileInfo</code> - used for reading of embedded resources (primarily for testing); internally, it automatically adds the root namespace of the specified assembly to the path</li>
<li><code>InMemoryFileProvider</code> and <code>InMemoryFileInfo</code> - used for testing or runtime data</li>
</ul>
<p>There is no <code>GetDirectoryContents</code> API because this is what I have the <a href="https://codereview.stackexchange.com/questions/206519/walking-directory-tree-like-python-does"><code>DirectoryTree</code></a> for.</p>
<p>All providers use the same path schema, this is, with the backslash <code>\</code>. This is also why the <code>EmbeddedFileProvider</code> does some additional converting between the <em>usual</em> patch and the resource path which is separated by dots <code>.</code></p>
<hr />
<h3>Implementations</h3>
<p>So here they are, the three pairs, in the same order as the above list:</p>
<pre><code>[PublicAPI]
public class PhysicalFileProvider : IFileProvider
{
public IFileInfo GetFileInfo(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
return new PhysicalFileInfo(path);
}
public IFileInfo CreateDirectory(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (Directory.Exists(path))
{
return new PhysicalFileInfo(path);
}
try
{
var newDirectory = Directory.CreateDirectory(path);
return new PhysicalFileInfo(newDirectory.FullName);
}
catch (Exception ex)
{
throw new CreateDirectoryException(path, ex);
}
}
public async Task<IFileInfo> CreateFileAsync(string path, Stream data)
{
try
{
using (var fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write))
{
await data.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
return new PhysicalFileInfo(path);
}
catch (Exception ex)
{
throw new CreateFileException(path, ex);
}
}
public IFileInfo DeleteFile(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
try
{
File.Delete(path);
return new PhysicalFileInfo(path);
}
catch (Exception ex)
{
throw new DeleteFileException(path, ex);
}
}
public IFileInfo DeleteDirectory(string path, bool recursive)
{
try
{
Directory.Delete(path, recursive);
return new PhysicalFileInfo(path);
}
catch (Exception ex)
{
throw new DeleteDirectoryException(path, ex);
}
}
}
[PublicAPI]
internal class PhysicalFileInfo : IFileInfo
{
public PhysicalFileInfo([NotNull] string path) => Path = path ?? throw new ArgumentNullException(nameof(path));
#region IFileInfo
public string Path { get; }
public string Name => System.IO.Path.GetFileName(Path);
public bool Exists => File.Exists(Path) || Directory.Exists(Path);
public long Length => Exists && !IsDirectory ? new FileInfo(Path).Length : -1;
public DateTime ModifiedOn => !string.IsNullOrEmpty(Path) ? File.GetLastWriteTime(Path) : default;
public bool IsDirectory => Directory.Exists(Path);
public Stream CreateReadStream()
{
return
IsDirectory
? throw new InvalidOperationException($"Cannot open '{Path}' for reading because it's a directory.")
: Exists
? File.OpenRead(Path)
: throw new InvalidOperationException("Cannot open '{Path}' for reading because the file does not exist.");
}
#endregion
#region IEquatable<IFileInfo>
public override bool Equals(object obj) => obj is IFileInfo file && Equals(file);
public bool Equals(IFileInfo other) => FileInfoEqualityComparer.Default.Equals(other, this);
public bool Equals(string other) => FileInfoEqualityComparer.Default.Equals(other, Path);
public override int GetHashCode() => FileInfoEqualityComparer.Default.GetHashCode(this);
#endregion
}
</code></pre>
<hr />
<pre><code>public class EmbeddedFileProvider : IFileProvider
{
private readonly Assembly _assembly;
public EmbeddedFileProvider([NotNull] Assembly assembly)
{
_assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
BasePath = _assembly.GetName().Name.Replace('.', '\\');
}
public string BasePath { get; }
public IFileInfo GetFileInfo(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
// Embedded resouce names are separated by '.' so replace the windows separator.
var fullName = Path.Combine(BasePath, path).Replace('\\', '.');
// Embedded resource names are case sensitive so find the actual name of the resource.
var actualName = _assembly.GetManifestResourceNames().FirstOrDefault(name => SoftString.Comparer.Equals(name, fullName));
var getManifestResourceStream = actualName is null ? default(Func<Stream>) : () => _assembly.GetManifestResourceStream(actualName);
return new EmbeddedFileInfo(UndoConvertPath(fullName), getManifestResourceStream);
}
// Convert path back to windows format but the last '.' - this is the file extension.
private static string UndoConvertPath(string path) => Regex.Replace(path, @"\.(?=.*?\.)", "\\");
public IFileInfo CreateDirectory(string path)
{
throw new NotSupportedException($"{nameof(EmbeddedFileProvider)} does not support directory creation.");
}
public IFileInfo DeleteDirectory(string path, bool recursive)
{
throw new NotSupportedException($"{nameof(EmbeddedFileProvider)} does not support directory deletion.");
}
public Task<IFileInfo> CreateFileAsync(string path, Stream data)
{
throw new NotSupportedException($"{nameof(EmbeddedFileProvider)} does not support file creation.");
}
public IFileInfo DeleteFile(string path)
{
throw new NotSupportedException($"{nameof(EmbeddedFileProvider)} does not support file deletion.");
}
}
internal class EmbeddedFileInfo : IFileInfo
{
private readonly Func<Stream> _getManifestResourceStream;
public EmbeddedFileInfo(string path, Func<Stream> getManifestResourceStream)
{
_getManifestResourceStream = getManifestResourceStream;
Path = path;
}
public string Path { get; }
public string Name => System.IO.Path.GetFileNameWithoutExtension(Path);
public bool Exists => !(_getManifestResourceStream is null);
public long Length => _getManifestResourceStream()?.Length ?? -1;
public DateTime ModifiedOn { get; }
public bool IsDirectory => false;
// No protection necessary because there are no embedded directories.
public Stream CreateReadStream() => _getManifestResourceStream();
#region IEquatable<IFileInfo>
public override bool Equals(object obj) => obj is IFileInfo file && Equals(file);
public bool Equals(IFileInfo other) => FileInfoEqualityComparer.Default.Equals(other, this);
public bool Equals(string other) => FileInfoEqualityComparer.Default.Equals(other, Path);
public override int GetHashCode() => FileInfoEqualityComparer.Default.GetHashCode(this);
#endregion
}
</code></pre>
<hr />
<pre><code>public class InMemoryFileProvider : Dictionary<string, byte[]>, IFileProvider
{
private readonly ISet<IFileInfo> _files = new HashSet<IFileInfo>();
#region IFileProvider
public IFileInfo GetFileInfo(string path)
{
var file = _files.SingleOrDefault(f => FileInfoEqualityComparer.Default.Equals(f.Path, path));
return file ?? new InMemoryFileInfo(path, default(byte[]));
}
public IFileInfo CreateDirectory(string path)
{
path = path.TrimEnd('\\');
var newDirectory = new InMemoryFileInfo(path, _files.Where(f => f.Path.StartsWith(path)));
_files.Add(newDirectory);
return newDirectory;
}
public IFileInfo DeleteDirectory(string path, bool recursive)
{
return DeleteFile(path);
}
public Task<IFileInfo> CreateFileAsync(string path, Stream data)
{
var file = new InMemoryFileInfo(path, GetByteArray(data));
_files.Remove(file);
_files.Add(file);
return Task.FromResult<IFileInfo>(file);
byte[] GetByteArray(Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
public IFileInfo DeleteFile(string path)
{
var fileToDelete = new InMemoryFileInfo(path, default(byte[]));
_files.Remove(fileToDelete);
return fileToDelete;
}
#endregion
}
internal class InMemoryFileInfo : IFileInfo
{
[CanBeNull]
private readonly byte[] _data;
[CanBeNull]
private readonly IEnumerable<IFileInfo> _files;
private InMemoryFileInfo([NotNull] string path)
{
Path = path ?? throw new ArgumentNullException(nameof(path));
ModifiedOn = DateTime.UtcNow;
}
public InMemoryFileInfo([NotNull] string path, byte[] data)
: this(path)
{
_data = data;
Exists = !(data is null);
IsDirectory = false;
}
public InMemoryFileInfo([NotNull] string path, [NotNull] IEnumerable<IFileInfo> files)
: this(path)
{
_files = files ?? throw new ArgumentNullException(nameof(files));
Exists = true;
IsDirectory = true;
}
#region IFileInfo
public bool Exists { get; }
public long Length => IsDirectory ? throw new InvalidOperationException("Directories have no length.") : _data?.Length ?? -1;
public string Path { get; }
public string Name => System.IO.Path.GetFileNameWithoutExtension(Path);
public DateTime ModifiedOn { get; }
public bool IsDirectory { get; }
public Stream CreateReadStream()
{
return
IsDirectory
? throw new InvalidOperationException("Cannot create read-stream for a directory.")
: Exists
// ReSharper disable once AssignNullToNotNullAttribute - this is never null because it's protected by Exists.
? new MemoryStream(_data)
: throw new InvalidOperationException("Cannot create a read-stream for a file that does not exist.");
}
#endregion
#region IEquatable<IFileInfo>
public override bool Equals(object obj) => obj is IFileInfo file && Equals(file);
public bool Equals(IFileInfo other) => FileInfoEqualityComparer.Default.Equals(other, this);
public bool Equals(string other) => FileInfoEqualityComparer.Default.Equals(other, Path);
public override int GetHashCode() => FileInfoEqualityComparer.Default.GetHashCode(this);
#endregion
}
</code></pre>
<hr />
<h3>Decorator for less typing</h3>
<p>There is one more file provider. I use this to save some typing of paths. The <code>RelativeFileProvider</code> adds its path in front of the other path if there is some root path that doesn't change.</p>
<pre><code>public class RelativeFileProvider : IFileProvider
{
private readonly IFileProvider _fileProvider;
private readonly string _basePath;
public RelativeFileProvider([NotNull] IFileProvider fileProvider, [NotNull] string basePath)
{
_fileProvider = fileProvider ?? throw new ArgumentNullException(nameof(fileProvider));
_basePath = basePath ?? throw new ArgumentNullException(nameof(basePath));
}
public IFileInfo GetFileInfo(string path) => _fileProvider.GetFileInfo(CreateFullPath(path));
public IFileInfo CreateDirectory(string path) => _fileProvider.CreateDirectory(CreateFullPath(path));
public IFileInfo DeleteDirectory(string path, bool recursive) => _fileProvider.DeleteDirectory(CreateFullPath(path), recursive);
public Task<IFileInfo> CreateFileAsync(string path, Stream data) => _fileProvider.CreateFileAsync(CreateFullPath(path), data);
public IFileInfo DeleteFile(string path) => _fileProvider.DeleteFile(CreateFullPath(path));
private string CreateFullPath(string path) => Path.Combine(_basePath, path ?? throw new ArgumentNullException(nameof(path)));
}
</code></pre>
<hr />
<h3>Exceptions</h3>
<p>The providers don't throw pure .NET exception because they aren't usually helpful. I wrap them in my own types:</p>
<pre><code>public class CreateDirectoryException : Exception
{
public CreateDirectoryException(string path, Exception innerException)
: base($"Could not create directory: {path}", innerException)
{ }
}
public class CreateFileException : Exception
{
public CreateFileException(string path, Exception innerException)
: base($"Could not create file: {path}", innerException)
{ }
}
public class DeleteDirectoryException : Exception
{
public DeleteDirectoryException(string path, Exception innerException)
: base($"Could not delete directory: {path}", innerException)
{ }
}
public class DeleteFileException : Exception
{
public DeleteFileException(string path, Exception innerException)
: base($"Could not delete file: {path}", innerException)
{ }
}
</code></pre>
<hr />
<h3>Simple file search</h3>
<p>There is one more provider that allows me to probe multiple providers. It supports only reading:</p>
<pre><code>public class CompositeFileProvider : IFileProvider
{
private readonly IEnumerable<IFileProvider> _fileProviders;
public CompositeFileProvider(IEnumerable<IFileProvider> fileProviders)
{
_fileProviders = fileProviders;
}
public IFileInfo GetFileInfo(string path)
{
foreach (var fileProvider in _fileProviders)
{
var fileInfo = fileProvider.GetFileInfo(path);
if (fileInfo.Exists)
{
return fileInfo;
}
}
return new InMemoryFileInfo(path, new byte[0]);
}
public IFileInfo CreateDirectory(string path)
{
throw new NotSupportedException($"{nameof(CompositeFileProvider)} does not support directory creation.");
}
public IFileInfo DeleteDirectory(string path, bool recursive)
{
throw new NotSupportedException($"{nameof(CompositeFileProvider)} does not support directory deletion.");
}
public Task<IFileInfo> CreateFileAsync(string path, Stream data)
{
throw new NotSupportedException($"{nameof(CompositeFileProvider)} does not support file creation.");
}
public IFileInfo DeleteFile(string path)
{
throw new NotSupportedException($"{nameof(CompositeFileProvider)} does not support file deletion.");
}
}
</code></pre>
<hr />
<h3>Comparing files</h3>
<p>The comparer for the <code>IFileInfo</code> is very straightforward and compares the <code>Path</code> property:</p>
<pre><code>public class FileInfoEqualityComparer : IEqualityComparer<IFileInfo>, IEqualityComparer<string>
{
private static readonly IEqualityComparer PathComparer = StringComparer.OrdinalIgnoreCase;
[NotNull]
public static FileInfoEqualityComparer Default { get; } = new FileInfoEqualityComparer();
public bool Equals(IFileInfo x, IFileInfo y) => Equals(x?.Path, y?.Path);
public int GetHashCode(IFileInfo obj) => GetHashCode(obj.Path);
public bool Equals(string x, string y) => PathComparer.Equals(x, y);
public int GetHashCode(string obj) => PathComparer.GetHashCode(obj);
}
</code></pre>
<hr />
<h3>Example</h3>
<p>As an example I use one of my tests that checks whether the relative and embedded files providers do their job correctly.</p>
<pre><code>[TestClass]
public class RelativeFileProviderTest
{
[TestMethod]
public void GetFileInfo_DoesNotGetNonExistingEmbeddedFile()
{
var fileProvider =
new RelativeFileProvider(
new EmbeddedFileProvider(typeof(RelativeFileProviderTest).Assembly),
@"relative\path");
var file = fileProvider.GetFileInfo(@"file.ext");
Assert.IsFalse(file.Exists);
Assert.IsTrue(SoftString.Comparer.Equals(@"Reusable\Tests\relative\path\file.ext", file.Path));
}
}
</code></pre>
<hr />
<h3>Questions</h3>
<p>Besides of the <em>default</em> question about can this be improved in anyway I have more:</p>
<ul>
<li>should I be concerned about thread-safty here? I didn't use any <code>lock</code>s but adding them isn't a big deal. Should I? Where would you add them? I guess creating files and directories could be good candidates, right?</li>
<li>should the <code>EmbeddedFileProvider</code> use the <code>RelativeFileProvider</code> to add the assembly namespace to the path or should I leave it as is?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T00:01:51.327",
"Id": "400911",
"Score": "0",
"body": "Did you consider [System.IO.Abstractions](https://github.com/System-IO-Abstractions/System.IO.Abstractions)? I like using that one."
},
{
"ContentLicense": "CC BY-SA 4.0"... | [
{
"body": "<p>In <code>PhysicalFileProvider.CreateDirectory()</code> you should place the call to <code>Directory.Exists()</code> inside the <code>try..catch</code> as well because it can throw e.g <code>ArgumentException</code> for <code>\"C:\\test?\"</code> or a <code>NotSupportedException</code> for <code>C... | {
"AcceptedAnswerId": "207638",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T19:35:19.927",
"Id": "207585",
"Score": "8",
"Tags": [
"c#",
"file-system",
"dependency-injection"
],
"Title": "Multiple file access abstractions"
} | 207585 |
<p>I have working code that compares rental prices and owning costs, given some parameters. It works, but it surely does not look good. I hadn't worked with time-series before and I wonder how I could improve the code. See it below:</p>
<pre><code>""" Credit: khanacademy.org/downloads/buyrent.xls"""
""" This code compares the cost of renting with the cost of owning a house.
It was orginally thought for the US case. The adjustment of parameteres was made
to fit the case of Brazil. Two alternatives are available the so-called Price table or SAC:
https://pt.wikipedia.org/wiki/Sistema_de_Amortização_Constante"""
import numpy as np
import matplotlib.pyplot as plt
def flow(purchase_p, downpay, inter, yr, prop_tax_rate, yr_maint, yr_cond, yr_ins, appr, inc_tax_rate, inflat,
rent_price, cash, print_ten=120, choice='price'):
if choice == 'price':
fixed_mortgage_payment = (purchase_p - downpay) * (1 - 1/(1 + inter/12)) / (1 - 1/(1 + inter/12) **
(yr * 12 + 1))
else:
fixed_mortgage_payment = (purchase_p - downpay) / (yr * 12)
home_value = np.zeros(yr * 12 + 1)
debt = np.zeros(yr * 12 + 1)
paid_interest = np.zeros(yr * 12 + 1)
insurance = np.zeros(yr * 12 + 1)
cond = np.zeros(yr * 12 + 1)
maint = np.zeros(yr * 12 + 1)
property_tax = np.zeros(yr * 12 + 1)
cash_outflow = np.zeros(yr * 12 + 1)
rent = np.zeros(yr * 12 + 1)
rent_savings = np.zeros(yr * 12 + 1)
paid_principal = np.zeros(yr * 12 + 1)
income_tax = np.zeros(yr * 12 + 1)
home_value[0] = purchase_p
debt[0] = purchase_p - downpay
insurance[0] = yr_ins/12
cond[0] = yr_cond/12
maint[0] = yr_maint/12
rent[0] = rent_price
rent_savings[0] = downpay
for i in range(yr * 12):
paid_interest[i + 1] = debt[i] * inter / 12
if choice == 'price':
paid_principal[i + 1] = fixed_mortgage_payment - paid_interest[i + 1]
debt[i + 1] = debt[i] - paid_principal[i + 1]
else:
paid_principal[i + 1] = fixed_mortgage_payment
debt[i + 1] = debt[i] - fixed_mortgage_payment
home_value[i + 1] = home_value[i] * (1 + appr/12)
insurance[i + 1] = insurance[i] * (1 + inflat/12)
cond[i + 1] = cond[i] * (1 + inflat/12)
maint[i + 1] = maint[i] * (1 + inflat / 12)
property_tax[i + 1] = home_value[i] * (prop_tax_rate/12)
income_tax[i + 1] = (paid_interest[i + 1] + property_tax[i + 1]) * inc_tax_rate
cash_outflow[i + 1] = insurance[i + 1] + cond[i + 1] + maint[i + 1] + property_tax[i + 1] + \
paid_interest[i + 1] + paid_principal[i + 1] - income_tax[i + 1]
rent[i + 1] = (1 + appr/12) * rent[i]
rent_savings[i + 1] = rent_savings[i] * (1 + cash/12) + cash_outflow[i + 1] - rent[i + 1]
print('Home value after {:.0f} years: {:,.2f}'.format(print_ten/12, home_value[print_ten]))
print('Debt after {:.0f} years: {:,.2f}'.format(print_ten/12, debt[print_ten]))
print('Equity after {:.0f} years: {:,.2f}'.format(print_ten/12, home_value[print_ten] - debt[print_ten]))
print('Savings if renting after {:.0f} years: {:,.2f}'.format(print_ten/12, rent_savings[print_ten]))
print('Selling cost (6% brokerage rate): {:,.2f}'.format(home_value[print_ten] * .06))
print('Benefit of buying over renting? {:,.2f}'.format(home_value[print_ten] - debt[print_ten]
- rent_savings[print_ten] - home_value[print_ten] * .06))
return {'home_value': home_value, 'debt': debt, 'equity': home_value - debt, 'savings_renting': rent_savings,
'benefit_buying': home_value - debt - rent_savings - (home_value * .06)}
def plotting(data):
plt.plot(data['home_value'], label='Home value')
plt.plot(data['debt'], label='Debt')
plt.plot(data['equity'], label='Equity')
plt.plot(data['savings_renting'], label="Savings when renting")
plt.plot(data['benefit_buying'], label='Benefit of buying')
plt.legend()
plt.annotate('Parms: house price {:,.0f}, \ndownpayment {:,.0f}, \ninterest annual {:.3f}, years {:.0f}, '
'\naluguel {:,.0f}, \ncash return annual {:.3f}, \ninflation {:.3f},'
'\ntabela: {} \nhouse appreciation {:.3f}'.format(purchase_price, downpayment, interest, years,
initial_rent, return_cash, inflation, choice,
appreciation),
fontsize=9, xy=(0.43, 0.7), xycoords='axes fraction')
plt.savefig('res1.png')
plt.show()
if __name__ == '__main__':
purchase_price = 800000
downpayment = 0
interest = .08
years = 30
property_tax_rate = 0
yr_maintenance = 0
yr_comdominium = 0
yr_insurance = 0
appreciation = .03 # real appreciation 0%
income_tax_rate = 0 # income deduction on interest and property taxes paid
inflation = .03
initial_rent = purchase_price * .004 # 0.4 % of real values
return_cash = .06 # real return on cash 3%
time = 360
choice = 'SAC'
res = flow(purchase_price, downpayment, interest, years, property_tax_rate, yr_maintenance, yr_comdominium,
yr_insurance, appreciation, income_tax_rate, inflation, initial_rent, return_cash, time, choice)
plotting(res)
</code></pre>
| [] | [
{
"body": "<p>I can't cover everything that can be done to improve the code, so I will start by the most important parts. Once you incorporate these, you can post the updated version as a new question</p>\n\n<h1>variable names</h1>\n\n<p>the naming of functions, variables etc is more than half of the documentat... | {
"AcceptedAnswerId": "207815",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T19:42:25.307",
"Id": "207586",
"Score": "1",
"Tags": [
"python",
"datetime",
"numpy",
"finance"
],
"Title": "Renting vs. owning comparison calculation"
} | 207586 |
<p>I am working on below problem:</p>
<blockquote>
<p>Given an integer, how do you find the square root of the number
without using any built-in function?</p>
</blockquote>
<pre><code> private static double computeSquareRootBinarySearch(double x, double precision) {
double start = 0;
double end = x / 2 + 1;
double mid = (start + ((end - start) / 2));
double prevMid = 0;
double diff = Math.abs(mid - prevMid);
while ((mid * mid != x) && (diff > precision)) {
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
prevMid = mid;
mid = (start + end) / 2;
diff = Math.abs(mid - prevMid);
}
return mid;
}
</code></pre>
<p>I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T21:24:54.047",
"Id": "400702",
"Score": "0",
"body": "If you can use `Math.abs()`, then why not also use `Math.sqrt()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T21:41:36.643",
"Id": "400704... | [
{
"body": "<ul>\n<li><p>It is unlikely that <code>mid * mid</code> would ever be equal to <code>x</code>, so the opportunistic <code>mid * mid != x</code> consumes more cycles than it may save. I recommend to drop it entirely.</p></li>\n<li><p>The convergence rate is not the best. Your algorithm adds (approxima... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T21:04:56.420",
"Id": "207592",
"Score": "0",
"Tags": [
"java",
"binary-search"
],
"Title": "Find the square root of the number without using any built-in function?"
} | 207592 |
<p>This function takes a string from an HTTP POST or GET string, finds the specified variable, and allocates memory for the result and puts it in a string. The destination is given as an address of an empty pointer.</p>
<pre><code>username=johndoe&password=password123
</code></pre>
<p>Would produce:</p>
<pre><code>password123
</code></pre>
<p>when finding variable <code>password</code>.</p>
<pre><code>void httpString(char **dest, char *input, const char *find) {
char *start;
char *o_input = input;
const char *o_find = find;
size_t length = 0;
size_t i = 0;
while (*input) {
if (*input == '&' || input == o_input) {
if (*input == '&') {
input++;
if (*input == 0) {
return;
}
}
while (*input == *find) {
if (*input == 0 || *find == 0) {
return;
}
input++;
find++;
if (*input == '=' && *find == 0) {
input++;
if (*input == 0) {
return;
}
start = input;
while (*input != '&' && *input) {
input++;
length++;
}
*dest = malloc(length + 1);
input = start;
while (*input != '&' && *input) {
(*dest)[i] = *input;
input++;
i++;
}
(*dest)[i] = 0;
return;
}
}
}
find = o_find;
input++;
}
}
</code></pre>
<p>Any feedback related to how this function can be improved would be greatly appreciated. I am worried about potential edge cases where a memory access violation could occur.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T23:58:56.327",
"Id": "400719",
"Score": "1",
"body": "I'll try to do a full review tomorrow but for now I have to be pedantic : What you want to parse is called a [Query String](https://en.m.wikipedia.org/wiki/Query_string) and for ... | [
{
"body": "<p>The easiest way to improve this function is to use the C standard library. As it is, it's difficult to read; you can't understand what it does at a glance. And it's unnecessary difficult, because most of the building blocks are already available for free in <code><string.h></code>:</p>\n\n<u... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T22:15:44.590",
"Id": "207598",
"Score": "3",
"Tags": [
"c",
"parsing",
"http",
"url"
],
"Title": "Parse a GET or POST string in C"
} | 207598 |
<p>This is my version of the possible permutations of a string challenge. Please give me feedback or criticism. There are two vectors here: <code>positions</code> and <code>pointed_to</code>. <code>positions[i]</code> holds the index of the i'th character in the permutation. <code>pointed_to[i]</code> is true if the index of the i'th character in the original string is present somewhere inside the <code>positions</code> vector. I like to think of the <code>positions</code> vector as "character pointers". There are as many "character pointers" as there are characters in the original string. Each "character pointer" points to a character in the original string. The <code>position[0]</code> "points to" the first character in the permutation, the <code>position[1]</code> "points to" the second character in the permutation, and so on.</p>
<p>Inside the function, there is a loop which picks a char in the original string for each "character pointer" to "point to". Each char in the string can be pointed to by no more than one "character pointer". So we are looping until we find an open position for that "character pointer", a char to which no other pointers point to, <code>pointed_to = false</code>.</p>
<p>The position array is pass by reference, or it could be a global variable, because we don't care about storing the previous states of it's data in the recursion stack. Each newly created stack frame finds a position for the 0'th "pointer". This corresponds to <code>position[0]</code>. As the recursive stack grows, it fills in <code>position[1]</code>, then <code>position[2]</code>, <code>[3]</code>, ... and so on. When stack frames get popped off the stack, we no longer care about the "residue" left in <code>position[ the higher insides ]</code>. This is similar in principle to how stack frames in the real recursive stack are not deleted, but simply considered as garbage values. All values <code>position[a]</code> where <code>a > current_position</code> are also considered to be garbage values. When the stack grows to be the size of the string, all the positions will have been filled up anyway, and so we can just print the permutation by following the pointers.</p>
<p>The <code>pointed_by</code> array is stored on the stack, however, and it is passed by value. In positions, only a single element was considered to be data associated with the current stack frame, so we could place it outside the stack. However, the whole <code>pointed_by</code> array is considered to be data associated with the current stack frame. That way when the stack frames are being popped off, we preserve the whole old state of the <code>pointed_to</code> array as it was originally.</p>
<p>I know that this explanation sounds kind of confusing, so sorry about that. Well, this algorithm actually works, and only O(n) memory is taken up.</p>
<pre><code>#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
template <typename TYPE>
void print_vector(vector<TYPE> vect)
{
for (auto x : vect) {
cerr << x << ' ';
}
}
void print_permutations(const string& input,
vector<int>& positions, vector<bool> pointed_to,
size_t current_position, size_t string_length)
{
if (current_position == string_length) {
for (size_t i = 0; i < string_length; ++i) {
cout << input.at( positions.at(i) );
}
cout << endl;
return;
}
for (size_t i = 0; i < string_length; ++i) {
// not empty
if (pointed_to.at(i)) {
continue;
// empty
} else {
positions.at(current_position) = i;
pointed_to.at(i) = true;
print_permutations(input, positions, pointed_to, current_position + 1, string_length);
pointed_to.at(i) = false;
}
}
return;
}
int main()
{
string input;
cout << " > ";
cin >> input;
cout << endl;
size_t string_length = input.length();
vector<int> positions(string_length);
vector<bool> pointed_to(string_length, false);
print_permutations(input, positions, pointed_to, 0, string_length);
return EXIT_SUCCESS;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T00:06:54.037",
"Id": "400720",
"Score": "3",
"body": "Some interesting things to say, I'll do a review tomorrow but I have a question, did you tried [std::next_permutation](http://en.cppreference.com/w/cpp/algorithm/next_permutati... | [
{
"body": "<ul>\n<li><p>Trust yourself. There is no chance to have an out-of-bounds access to any of your vectors. Testing it with <code>.at()</code> is a pure waste of cycles. Prefer <code>[]</code>.</p></li>\n<li><p>Structuring code like</p>\n\n<pre><code> if (pointed_to.at(i)) {\n continue;\n } ... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T23:19:52.857",
"Id": "207602",
"Score": "2",
"Tags": [
"c++",
"beginner",
"strings",
"reinventing-the-wheel",
"combinatorics"
],
"Title": "Generate all possible permutations of a string in C++"
} | 207602 |
<p>First of all, let me answer the question that a lot of you may have:</p>
<blockquote>
<p>The Mandelbrot set is the set of values of c in the complex plane for which the orbit of 0 under iteration of the quadratic map when f(x) = x<sup>2</sup> + c.</p>
</blockquote>
<p>The fun thing about the Mandelbrot set is that it's a fractal and you can indefinitely zoom into it. <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Mandelbrot_sequence_new.gif/220px-Mandelbrot_sequence_new.gif" rel="nofollow noreferrer">Here's</a> a demonstration. </p>
<p>This code does not zoom into the set, it only shows the first iteration of the fractal. This ASCII image is taken directly from the result of my program:</p>
<blockquote>
<pre><code> *
*******
************
***************
*****************
********************
*********************
* * ********************** *
***** *********************** *
******** *****************************
********* *************************
**********************************
***********************************
*************************************
************************************
***********************************
***********************************
***********************************
***********************************
************************************
*************************************
***********************************
**********************************
********* *************************
******** *****************************
***** *********************** *
* * ********************** *
*********************
********************
****************
***************
************
*******
*
</code></pre>
</blockquote>
<p>The code is simple, it calculates if a character between height and width is placed on the set, if it is, it inserts an asterisk. If it's not, it inserts a space. It then adds a newline char. Here's the code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <cmath>
const int height = 40, width = 80;
typedef std::vector<double> tuple;
tuple coord_to_complex(double i, double j)
{
double real = (4*i) / (width - 1) - 2.0;
double imaginary = (2.2 * j) / (height - 1) - 1.1;
tuple ret = {real, imaginary};
return ret;
}
bool is_in_mandelbrot(tuple re_im)
{
auto cr = re_im[0], ci = re_im[1];
auto zr = cr, zi = ci;
for (int t = 0; t <= 1000; ++t)
{
zr = (std::pow(zr, 2) - std::pow(zi, 2)) + cr;
zi = (2*zi*zr) + ci;
if (std::sqrt(std::pow(zr, 2) + std::pow(zi, 2)) > 2)
return false;
}
return true;
}
std::string print_set()
{
std::string ret = "";
for (int i = 0; i <= height; ++i)
{
for (int j = 0; j <= width; ++j)
{
if (is_in_mandelbrot(coord_to_complex(j, i)))
{
ret += '*';
}
else
{
ret += ' ';
}
}
ret += '\n';
}
return ret;
}
int main() {
std::cout << print_set() << std::endl;
return 0;
}
</code></pre>
<p>There's nothing else to say but thanks. So thank you for reading my code. </p>
<p><strong>Credits:</strong> Most of the code is based on a codegolfing practice in Python that I found on Github so thanks to the Python programmer who wrote solved that coding challenge. </p>
| [] | [
{
"body": "<p>Good work! I would only like to give you one piece of advice. I see this line in you code:</p>\n\n<pre><code>typedef std::vector<double> tuple;\n</code></pre>\n\n<p>I don't know if you are aware of this or not, but there is actually a data structure in the C++ standard library called <a href... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T23:22:16.853",
"Id": "207603",
"Score": "1",
"Tags": [
"c++",
"c++14",
"ascii-art",
"fractals"
],
"Title": "ASCII Mandelbrot"
} | 207603 |
<p>Problem: convert this array of hashes:</p>
<pre><code>cars = [
{ :model=>"Ferrari 458", :speed=>320 },
{ :model=>"Maserati MC12", :speed=>330 },
{ :model=>"Ferrari Enzo", :speed=>350 },
{ :model=>"Lamborghini Huracan", :speed=>325 }
]
</code></pre>
<p>to this data structure:</p>
<pre><code>{
above_320: [
{ :model=>"Maserati MC12", :speed=>330 },
{ :model=>"Lamborghini Huracan", :speed=>325 },
{ :model=>"Ferrari Enzo", :speed=>350 }
],
the_rest: [
{ :model=>"Ferrari 458", :speed=>320 }
]
}
</code></pre>
<p>My solution:</p>
<pre><code>cars.partition {|car| car[:speed] > 320}
.map.with_index {|cars,i| [ i == 0 ? :above_320 : :the_rest, cars ]}
.to_h
</code></pre>
<p>Any feedback would be greatly appreciated!</p>
| [] | [
{
"body": "<p>I think that <code>.map.with_index {|cars,i| [ i == 0 ? :above_320 : :the_rest, cars ]}</code> is a bit more verbose and awkward than it needs to be.</p>\n\n<pre><code>Hash[\n [:above_320, :the_rest].zip(cars.partition { |car| car[:speed] > 320 })\n]\n</code></pre>\n\n<p>Alternatively,</p>\n\n... | {
"AcceptedAnswerId": "207620",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T00:01:31.147",
"Id": "207607",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Partition array to hash in ruby"
} | 207607 |
<p>I am looking for a way to turn a list of words that may have duplicates into a dictionary/map that counts the number of occurrences of words. After spending some time with the problem, this seems to be one of the better ways, but maybe there are some downsides I am not seeing to this.</p>
<pre><code>const magazine = "asdf ASDF wer wer";
</code></pre>
<p>This should produce a magazineMap of</p>
<pre><code>const magazineMap = {
asdf: 1,
ASDF: 1,
wer: 2
}
</code></pre>
<p>My solution to this was</p>
<pre><code>function mapMagazine (magazine) {
return magazine
.split(' ')
.reduce((initMap, word) => {
return {
...initMap,
[word]: (initMap[word] || 0) + 1
}
}, {});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T08:03:13.380",
"Id": "400755",
"Score": "0",
"body": "Which language is it? Can you please retag your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T19:18:06.133",
"Id": "400888",
"... | [
{
"body": "<h1>Efficiency and potential problems</h1>\n<p>You could use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> but as you are counting word occurrences using an object is a little more efficient.</p>\n<h2>Efficiency<... | {
"AcceptedAnswerId": "207700",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T00:43:31.517",
"Id": "207609",
"Score": "1",
"Tags": [
"javascript",
"ecmascript-6",
"hash-map"
],
"Title": "Turn a list of words into a dictionary"
} | 207609 |
<p>I have been staring at what I have produced for almost 5 hours and I still cannot see how and where to improve my implementation. I am implementing an Orthogonal sampling method according to the description of Orthogonal <a href="https://en.wikipedia.org/wiki/Latin_hypercube_sampling" rel="nofollow noreferrer">Sampling</a>.</p>
<pre><code>import numpy as np
from numba import jit
import random
def Orthogonal(n):
assert(np.sqrt(n) % 1 == 0),"Please insert an even number of samples"
step = int(np.sqrt(n))
row_constraints = [ False for i in range(n) ]
column_constraints = [ False for i in range(n) ]
subbox_constraints = [ False for i in range(n)]
result = []
append = result.append
def map_coord_to_box(x:int, y:int, step:int)->int:
horz = int(np.floor(x/step))
vert = int(np.floor(y/step))
return vert * step + horz
def remap_value(value:float, olb:int, oub:int, nlb:int, nub:int)->int:
# https://stackoverflow.com/questions/1969240/mapping-a-range-of-values-to-another
delta_old = abs(oub - olb)
delta_new = abs(nub - nlb)
ratio = (value - olb) / delta_old
return ratio * delta_new + nlb
while(all(subbox_constraints) == False):
value = np.random.uniform(low=-2, high=2, size=2)
x = int(np.floor(remap_value(value[0], -2, 2, 0, n)))
y = int(np.floor(remap_value(value[1], -2, 2, 0, n)))
if not (row_constraints[y] or column_constraints[x] or subbox_constraints[map_coord_to_box(x, y, step)]): #check_constraints(row_constraints, column_constraints, subbox_constraints, x, y, step):
append(tuple(value))
row_constraints[y] = True
column_constraints[x] = True
subbox_constraints[map_coord_to_box(x, y, step)] = True
return result
</code></pre>
<p>The problem is obvious when generating 100 samples it takes on average 300 ms, and I need something faster as I need to generate at least 10.000 samples. So I have not sat still. I tried to use jit for the sub-functions but it does not make it faster, but slower. I am aware that these function calls in python have a higher overhead. And so far on my own I thought using these functions are a way to approach the sampling method I want to implement. I have also asked a friend and he came up with a different approach which is on average a factor 100 faster than the above code. So he only prunes every row and columns and after randomly choosing those and stores the indices in to a list which later fills randomly.</p>
<pre><code>def orthogonal_l(n):
bs = int(np.sqrt(n))
result = [0 for i in range(n)]
columns = [[i for i in range(bs)] for j in range(bs)]
c = 0
for h in range(bs):
rows = [i for i in range(bs)]
for z in range(bs):
w = random.choice(rows)
x = random.choice(columns[w])
columns[w].remove(x)
rows.remove(w)
x += w * bs
result[x] = c
c += 1
return result, bs
</code></pre>
<p>How can I make use of pruning with my own code and is it wise to do so? If not, how can I improve the code, if so, where?</p>
| [] | [
{
"body": "<p>So after talking with other students and some drawings I realised that I have three choices: use the definition of my friend which is faster than my original function, use my original function OR create an efficient datastructure to deal with the look-up complexity. </p>\n\n<p>So here goes the fre... | {
"AcceptedAnswerId": "207972",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T00:53:10.860",
"Id": "207610",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"random"
],
"Title": "Orthogonal sampling"
} | 207610 |
<p>This method is an attempt at removing duplicates from arrays without the use of extensions.</p>
<pre><code>func arrayWithDuplicatesRemoved<T: Equatable>(from array: [T]) -> [T] {
var results = [T]()
return array.compactMap { (element) -> T? in
if results.contains(element) {
return nil
} else {
results.append(element)
return element
}
}
}
let dirty = ["apple", "kiwi", "grapefruit", "kiwi", "kiwi", "strawberry", "watermelon", "apple", "banana"]
let clean = arrayWithDuplicatesRemoved(from: dirty)
print(clean) // ["apple", "kiwi", "grapes", "strawberry", "watermelon", "banana"]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T19:16:07.163",
"Id": "401022",
"Score": "0",
"body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. Thi... | [
{
"body": "<p>Your algorithm is O(n^2) so not very scalable... The immediate improvement I can think of is to use a <code>Set</code> for results (which means making T <code>Hashable</code>).</p>\n\n<p>If you aren't worried about position, then just create a Set from an array and you are done.</p>\n",
"comme... | {
"AcceptedAnswerId": "207743",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T01:07:34.143",
"Id": "207612",
"Score": "1",
"Tags": [
"array",
"swift"
],
"Title": "A scalable way to remove duplicates from Arrays without extensions in Swift 4"
} | 207612 |
<p>I'm really new to Python (like only a month of study) and I was testing out dictionaries, so I tried to make an 'inventory' where you can pick an item from your inventory and examine it. But I can tell that I'm not doing this in the most efficient or elegant way.</p>
<p>Originally I thought I could make each item its separate dictionary, kind of like this:</p>
<pre><code>#define what's in your inventory using a list
inventory = ["apple", "tire"]
#create a list of items with attributes using dictionaries
apple = {
"name":"apple",
"type":"fruit",
"edible":"edible",
"color":"red",
}
tire = {
"name":"tire",
"type":"object",
"edible":"not edible",
"color":"grey"
}
#explain the program to the user
print("Choose an item to examine. Items in your inventory are:")
print(*inventory, sep = ", ")
#set the loop to true
itemsloop = True
#begin the loop
while itemsloop == True:
#ask for user input
x = input()
</code></pre>
<p>But then I got stuck at the part where it's time to take the input and match it to the name of a dictionary, because one is a string and one isn't. The following code is working, but feels... inelegant and unnecessary to type out (prefix)-name, (prefix)-type, (prefix)-edible for every entry. I feel like there must be a simpler way to accomplish this that I'm just not seeing because I don't think like a programmer yet. I don't know.</p>
<p>If you can explain any more efficient methods with simple terminology (again, huge newbie not just to Python but programming in general), I'd really appreciate it!</p>
<pre><code>#define what's in your inventory using a list
inventory = ["apple", "tire"]
#create a list of items with attributes using a dictionary
items = {
"apple-name":"apple",
"apple-type":"fruit",
"apple-edible":"edible",
"apple-color":"red",
"tire-name":"tire",
"tire-type":"object",
"tire-edible":"not edible",
"tire-color":"grey"
}
#explain the program to the user
print("Choose an item to examine. Items in your inventory are:")
print(*inventory, sep = ", ")
#set the loop to true
itemsloop = True
#begin the loop
while itemsloop == True:
#ask for user input
x = input()
if x in inventory:
#if the input matches something you have, find the attributes of
#the item in the inventory and print them.
print("This is a " + items[x + "-color"] + " " +
items[x + "-name"] + ", a type of " + items[x + "-type"]
+ ". It is " + items[x + "-edible"] + ".")
elif x == "quit":
#if the player wishes to quit, end the program.
itemsloop == False
break
else:
#if the item is not recognized, let the player know.
print("You don't have that in your inventory.")
</code></pre>
<p>(The sample output would be something like, "This is a red apple, a type of fruit. It is edible.")</p>
| [] | [
{
"body": "<p>As you use item's <code>name</code> to search the item <code>information</code>, so you can design the <code>name</code> as the key of <code>items</code> hash table.</p>\n\n<pre><code>items = {\n \"apple\":\n {\n #type, edible,color information\n },\n ...\n}\n</code>... | {
"AcceptedAnswerId": "207634",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T02:51:10.157",
"Id": "207616",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"game"
],
"Title": "Creating a description of an item from an inventory"
} | 207616 |
<p>I am trying to write a Haskell function which takes a list <code>ls</code> and returns all sub-lists obtained by removing one element from <code>ls</code>. An additional constraint is that the returned list of lists must be in the order of the missing element.</p>
<p>Here is what I have. I know there must be a simpler solution.</p>
<pre><code>subOneLists :: [a] -> [[a]]
subOneLists ls = let helper :: [a] -> [a] -> [[a]] -> [[a]]
helper _ [] ss = ss
helper ps (x:xs) ss = helper ps' xs ss'
where ps' = ps ++ [x]
ss' = ss ++ [ps ++ xs]
in helper [] ls []
λ> subOneLists [1, 2, 3, 4]
[[2,3,4],[1,3,4],[1,2,4],[1,2,3]]
</code></pre>
| [] | [
{
"body": "<p>Here's a simpler way to implement it:</p>\n\n<pre><code>subOneLists :: [a] -> [[a]]\nsubOneLists [] = []\nsubOneLists (x:xs) = xs : map (x :) (subOneLists xs)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T04:10:40.197"... | {
"AcceptedAnswerId": "207621",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T03:24:42.960",
"Id": "207619",
"Score": "12",
"Tags": [
"haskell"
],
"Title": "Given a Haskell list, return all sub-lists obtained by removing one element"
} | 207619 |
<p>I implemented this max-heap to satisfy the C++ Container requirements. I am fairly confident I implemented <code>bubble_up</code>, <code>bubble_down</code>, and <code>sort</code> correctly. It passes for small sets of numbers I give it. If you're wondering what <code>bubble_down(iterator, iterator)</code> does, it does the bubble down action but ignores positions past <code>last</code> (inclusive). In <code>sort</code>, the vector becomes sorted from right to left, so as the root bubbles down it will not interact with the already sorted part. Also note that after sorting you will want to call <code>build</code> to rebuild the heap.</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <utility>
#include <sstream>
#include <cmath>
template<typename Type>
class max_heap {
public:
using value_type = Type;
using reference = Type&;
using const_reference = const Type&;
using iterator = typename std::vector<Type>::iterator;
using const_iterator = typename std::vector<Type>::const_iterator;
using difference_type = typename std::vector<Type>::difference_type;
using size_type = typename std::vector<Type>::size_type;
max_heap() = default;
~max_heap() = default;
max_heap(iterator begin, iterator end);
max_heap(const max_heap<Type>& other);
max_heap(max_heap<Type>&& other);
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
reference operator=(max_heap<Type> other);
reference operator=(max_heap<Type>&& other);
bool operator==(const max_heap<Type>& other);
bool operator!=(const max_heap<Type>& other);
void swap(max_heap& other);
template<typename T>
friend void swap(max_heap<T>& lhs, max_heap<T>& rhs);
size_type size() const;
size_type max_size() const;
bool empty() const;
void sort();
void insert(value_type value);
void remove(iterator elem);
void remove_maximum();
reference maximum();
const_reference maximum() const;
// build tree in linear time
void build();
private:
iterator parent_of(iterator child);
iterator left_child_of(iterator parent);
iterator right_child_of(iterator parent);
void bubble_up(iterator elem);
void bubble_down(iterator elem);
void bubble_down(iterator elem, iterator last);
std::vector<int> rep;
};
template<typename Type>
max_heap<Type>::max_heap(iterator begin, iterator end)
: rep(begin, end) {
build();
}
template<typename Type>
max_heap<Type>::max_heap(const max_heap<Type>& other)
: rep(other.rep) { }
template<typename Type>
max_heap<Type>::max_heap(max_heap<Type>&& other) {
std::swap(rep, other.rep);
}
template<typename Type>
typename max_heap<Type>::iterator
max_heap<Type>::begin() { return rep.begin(); }
template<typename Type>
typename max_heap<Type>::const_iterator
max_heap<Type>::begin() const { return rep.begin(); }
template<typename Type>
typename max_heap<Type>::const_iterator
max_heap<Type>::cbegin() const { return rep.begin(); }
template<typename Type>
typename max_heap<Type>::iterator
max_heap<Type>::end() { return rep.end(); }
template<typename Type>
typename max_heap<Type>::const_iterator
max_heap<Type>::end() const { return rep.end(); }
template<typename Type>
typename max_heap<Type>::const_iterator
max_heap<Type>::cend() const { return rep.end(); }
template<typename Type>
typename max_heap<Type>::reference
max_heap<Type>::operator=(max_heap<Type> other) {
// copy-swap
std::swap(rep, other.rep);
return *this;
}
template<typename Type>
typename max_heap<Type>::reference
max_heap<Type>::operator=(max_heap<Type>&& other) {
// copy-swap
std::swap(rep, other.rep);
return *this;
}
template<typename Type>
bool max_heap<Type>::operator==(const max_heap<Type>& other) {
return std::equal(begin(), end(), other.begin(), other.end());
}
template<typename Type>
bool max_heap<Type>::operator!=(const max_heap<Type>& other) {
return !operator==(other);
}
template<typename Type>
void max_heap<Type>::swap(max_heap<Type>& other) {
std::swap(rep, other.rep);
}
template<typename Type>
void swap(max_heap<Type>& lhs, max_heap<Type> rhs) {
lhs.swap(rhs);
}
template<typename Type>
typename max_heap<Type>::size_type
max_heap<Type>::size() const { return rep.size(); }
template<typename Type>
typename max_heap<Type>::size_type
max_heap<Type>::max_size() const { return rep.max_size(); }
template<typename Type>
bool max_heap<Type>::empty() const { return rep.empty(); }
template<typename Type>
void max_heap<Type>::build() {
// skip leaf nodes
const auto n = begin() + std::ceil(size() / 2);
for (auto i = n; i >= begin(); --i)
bubble_down(i);
}
template<typename Type>
void max_heap<Type>::sort() {
auto iter = end() - 1;
while (iter >= begin()) {
std::swap(*begin(), *iter);
// bubble root down but ignore elements past iter
bubble_down(begin(), iter);
--iter;
}
}
template<typename Type>
typename max_heap<Type>::reference
max_heap<Type>::maximum() { return *begin(); }
template<typename Type>
typename max_heap<Type>::const_reference
max_heap<Type>::maximum() const { return *begin(); }
template<typename Type>
void max_heap<Type>::remove(iterator elem) {
std::swap(*elem, *(end() - 1));
rep.resize(size() - 1);
if (size() > 0)
bubble_down(begin());
}
template<typename Type>
void max_heap<Type>::remove_maximum() {
remove(begin());
}
template<typename Type>
typename max_heap<Type>::iterator
max_heap<Type>::parent_of(iterator child) {
// parent = floor((i - 1) / 2)
const auto idx = std::distance(begin(), child);
return begin() + (idx - 1) / 2;
}
template<typename Type>
typename max_heap<Type>::iterator
max_heap<Type>::left_child_of(iterator parent) {
// left_child = 2i + 1
const auto idx = std::distance(begin(), parent);
return begin() + (2 * idx) + 1;
}
template<typename Type>
typename max_heap<Type>::iterator
max_heap<Type>::right_child_of(iterator parent) {
// right_child = 2i + 2
const auto idx = std::distance(begin(), parent);
return begin() + (2 * idx) + 2;
}
template<typename Type>
void max_heap<Type>::bubble_up(iterator elem) {
auto child = elem;
auto parent = parent_of(child);
// bubble up
while (child != parent && *child > *parent) {
std::swap(*child, *parent);
child = parent;
parent = parent_of(parent);
}
}
template<typename Type>
void max_heap<Type>::bubble_down(iterator elem) {
bubble_down(elem, end());
}
template<typename Type>
void max_heap<Type>::bubble_down(iterator elem, iterator last) {
auto parent = elem;
auto left_child = left_child_of(parent);
auto right_child = right_child_of(parent);
// stop at last
while (left_child < last || right_child < last) {
// find maximum of parent, left_child, right_child
auto max = parent;
if (left_child < last)
if (*max < *left_child)
max = left_child;
if (right_child < last)
if (*max < *right_child)
max = right_child;
// max_heap property fixed
if (parent == max) break;
// swap with the greater child
std::swap(*parent, *max);
parent = max;
left_child = left_child_of(parent);
right_child = right_child_of(parent);
}
}
template<typename Type>
void max_heap<Type>::insert(value_type value) {
rep.push_back(value);
bubble_up(end() - 1);
}
template<typename Type>
std::ostream& operator<<(std::ostream& out, const max_heap<Type>& max_heap) {
// output contents of max_heap
if (max_heap.size() > 0) {
std::cout << *max_heap.begin();
for (auto i = max_heap.begin() + 1; i < max_heap.end(); ++i)
std::cout << ' ' << *i;
}
return out;
}
int main() {
std::string line;
// get set of integers from stdin
do {
std::cout << "insert set of integers: ";
std::getline(std::cin, line);
} while (line == "");
// parse stdin input into vector<int>
std::stringstream stream(line);
std::vector<int> arr;
while (std::getline(stream, line, ' ')) {
try {
const int n = std::stoi(line);
arr.push_back(n);
} catch (...) {
// ignore for now
continue;
}
}
// linear time to build max_heap
max_heap<int> h(arr.begin(), arr.end());
std::cout << "h before: " << h << '\n';
h.sort();
std::cout << "h sorted: " << h << '\n';
h.build();
h.insert(22);
std::cout << "h inserted: " << h << '\n';
}
</code></pre>
<p>EDIT: I also realized I can <code>std::move</code> the value into the vector in <code>insert</code>.</p>
<p>EDIT2: I realized that inside of <code>build</code> it should be <code>const auto n = begin() + (size() / 2) - 1;</code>. What is above is not strictly wrong but it may do one more <code>bubble_down</code> than is necessary.</p>
| [] | [
{
"body": "<p>You have a container that can store anything</p>\n\n<pre><code>template<typename Type>\nclass max_heap\n</code></pre>\n\n<p>but your underlying storage is this</p>\n\n<pre><code>std::vector<int> rep;\n</code></pre>\n\n<p>I'm somewhat shocked that you didn't notice this. Did you only te... | {
"AcceptedAnswerId": "207627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T04:15:08.650",
"Id": "207624",
"Score": "5",
"Tags": [
"c++",
"reinventing-the-wheel",
"heap",
"heap-sort"
],
"Title": "Maximum Heap Container"
} | 207624 |
<p>I'm working on some code for an FRC Robot. I wanted to see if there's any obvious improvements that can be made here, that stands out, or stuff I should avoid doing. This is a test bed for the base code, the actual robot code will consist mainly of several classes derived from these.</p>
<p>The program overall will run at 200 or 400 hz per thread to mitigate propagation delay from one thread to another. The actual code might be a bit too big to fit into here, but this is just meant to be a framework with some testing.</p>
<p>My only concern (other than the fact that this hasn't been tested on the robot yet) at the moment is that I may want to use std::cout statements from the Master Thread, which can run at a much lower frequency (<20 hz). That will require accessing the thread-safe arrays of variables to retrieve and display the state of the robot. If this takes too long, it can hold the worker threads up. This can be found in MultiThreadDataArray::PrintData() and SafeMultithreadDataArray::PrintData().</p>
<p>Actual robot code is currently here: <a href="https://github.com/JakeAllison/RobotTestPC01" rel="nofollow noreferrer">https://github.com/JakeAllison/RobotTestPC01</a></p>
<p>Here's the file list that will be on the robot:</p>
<ul>
<li>CheckedData.h / CheckedData.cpp</li>
<li>MultithreadDataArray.h / MultithreadDataArray.cpp</li>
<li>SafeMultithreadDataArray.h / SafeMultithreadDataArray.cpp</li>
<li>ThreadDataBase.h / ThreadDataBase.cpp</li>
<li>ThreadDataContainer.h / ThreadDataContainer.cpp</li>
<li>ThreadTaskBase.h / ThreadTaskBase.cpp</li>
</ul>
<p>Below here are test files that represent the main thread, and any worker threads.</p>
<ul>
<li>TestData.h / TestData.cpp</li>
<li>TestTask.h / TestTask.cpp</li>
<li>Test2Data.h / Test2Data.cpp</li>
<li>Test2Task.h / Test2Task.cpp</li>
<li>Bot_Codebase_Test.cpp (main)</li>
<li>Defines.h</li>
</ul>
<p>This first class contains a single element of data. It has fields for validity, range checking, and a period of time before data becomes "stale" due to not being updated recently enough. These are critical for ensuring that the robot does not go crazy. If one of the control systems, sensors, or whatever stops working or gives bad data, then the robot can easily injure someone.</p>
<p>CheckedData.h:</p>
<pre><code>/*
* CheckedData.h
*
* Created on: Nov 8, 2018
* Author: Jake
*/
#ifndef SRC_UTILITIES_THREADSAFEDATA_CHECKEDDATA_H_
#define SRC_UTILITIES_THREADSAFEDATA_CHECKEDDATA_H_
#include <chrono>
#include <Defines.h>
namespace frc {
enum DataValidity {
DATA_VALIDITY_VALID,
DATA_VALIDITY_INVALID,
DATA_VALIDITY_DEGRADED,
DATA_VALIDITY_TEST
};
template <typename T>
class CheckedData {
public:
CheckedData();
CheckedData(T initData = 0, T rangeMin = 0, T rangeMax = 0, unsigned int timeoutUS = 0);
virtual ~CheckedData();
bool SetRange(T rangeMin, T rangeMax);
bool SetTimeoutUS(unsigned int timeoutUS);
DataValidity SetData(T inputData, bool isTest = false, bool forceIfDegraded = false);
DataValidity GetData(T& outputData, bool forceIfTest = true, bool forceIfDegraded = true,
bool forceIfInvalid = true);
private:
const std::chrono::steady_clock::duration _zeroCompare;
std::chrono::steady_clock::time_point _updateDeadline;
std::chrono::steady_clock::duration _timeoutUS;
DataValidity _validity;
T _rangeMin, _rangeMax;
T _storedData;
};
} /* namespace frc */
#include <Utilities/ThreadSafeData/CheckedData.cpp>
#endif /* SRC_UTILITIES_THREADSAFEDATA_CHECKEDDATA_H_ */
</code></pre>
<p>CheckedData.cpp</p>
<pre><code>/*
* CheckedData.cpp
*
* Created on: Nov 8, 2018
* Author: Jake
*/
#ifndef SRC_UTILITIES_THREADSAFEDATA_CHECKEDDATA_CPP_
#define SRC_UTILITIES_THREADSAFEDATA_CHECKEDDATA_CPP_
#include <Utilities/ThreadSafeData/CheckedData.h>
namespace frc {
template <typename T>
CheckedData<T>::CheckedData()
: _zeroCompare(std::chrono::microseconds(0))
, _updateDeadline(std::chrono::steady_clock::now())
, _timeoutUS(std::chrono::microseconds(0))
, _validity(DataValidity::DATA_VALIDITY_INVALID)
, _rangeMin(0)
, _rangeMax(0)
, _storedData(0) {
// Nothing to do.
}
template <typename T>
CheckedData<T>::CheckedData(T initData, T rangeMin, T rangeMax, unsigned int timeoutUS)
: _zeroCompare(std::chrono::microseconds(0))
, _updateDeadline(std::chrono::steady_clock::now())
, _timeoutUS(std::chrono::microseconds(timeoutUS))
, _validity(DataValidity::DATA_VALIDITY_INVALID)
, _rangeMin(rangeMin)
, _rangeMax(rangeMax)
, _storedData(initData) {
// Nothing here
}
template <typename T>
CheckedData<T>::~CheckedData() {
// Nothing here
}
template <typename T>
bool CheckedData<T>::SetRange(T rangeMin, T rangeMax) {
bool success = true;
if (rangeMax >= rangeMin) {
_rangeMax = rangeMax;
_rangeMin = rangeMin;
} else {
success = false;
}
return success;
}
template <typename T>
bool CheckedData<T>::SetTimeoutUS(unsigned int timeoutUS) {
_timeoutUS = std::chrono::microseconds(timeoutUS);
return true;
}
template <typename T>
DataValidity CheckedData<T>::SetData(T inputData, bool isTest, bool forceIfDegraded) {
DataValidity tempValid = DataValidity::DATA_VALIDITY_INVALID;
if (isTest) {
tempValid = DataValidity::DATA_VALIDITY_TEST;
_storedData = inputData;
_validity = tempValid;
_updateDeadline = _timeoutUS + std::chrono::steady_clock::now();
} else if ((_rangeMax > _rangeMin) && (inputData > _rangeMax || inputData < _rangeMin)) {
tempValid = DataValidity::DATA_VALIDITY_DEGRADED;
if (forceIfDegraded) {
_storedData = inputData;
_validity = tempValid;
_updateDeadline = _timeoutUS + std::chrono::steady_clock::now();
}
} else {
tempValid = DataValidity::DATA_VALIDITY_VALID;
_storedData = inputData;
_validity = tempValid;
_updateDeadline = _timeoutUS + std::chrono::steady_clock::now();
}
return tempValid;
}
template <typename T>
DataValidity CheckedData<T>::GetData(T& outputData, bool forceIfTest, bool forceIfDegraded, bool forceIfInvalid) {
if (_validity != DataValidity::DATA_VALIDITY_TEST && _timeoutUS > _zeroCompare) {
auto timestamp = std::chrono::steady_clock::now();
if (timestamp > _updateDeadline) {
_validity = DataValidity::DATA_VALIDITY_INVALID;
}
}
switch (_validity) {
case DataValidity::DATA_VALIDITY_VALID:
outputData = _storedData;
break;
case DataValidity::DATA_VALIDITY_INVALID:
if (forceIfInvalid) {
outputData = _storedData;
}
break;
case DataValidity::DATA_VALIDITY_DEGRADED:
if (forceIfDegraded) {
outputData = _storedData;
}
break;
case DataValidity::DATA_VALIDITY_TEST:
if (forceIfTest) {
outputData = _storedData;
}
break;
default:
// Do nothing
break;
}
return _validity;
}
} /* namespace frc */
#endif /* SRC_UTILITIES_THREADSAFEDATA_CHECKEDDATA_CPP_ */
</code></pre>
<p>This class is designed to allow all threads to access an array of data using strings as keys. The purpose of this is to allow the developers of the threads to agree on variables such as "Gyro Angle", "Motor Speed Demand", "Turn Rate", and so forth. This class houses regular data types that aren't safety critical.</p>
<p>MultiThreadDataArray.h:</p>
<pre><code>/*
* MultithreadDataArray.h
*
* Created on: Nov 9, 2018
* Author: Jake
*/
#ifndef SRC_UTILITIES_THREADSAFEDATA_MULTITHREADDATAARRAY_H_
#define SRC_UTILITIES_THREADSAFEDATA_MULTITHREADDATAARRAY_H_
#include <unordered_map>
#include <mutex>
#include <string>
#include <Defines.h>
namespace frc {
template <typename T>
class MultithreadDataArray {
public:
MultithreadDataArray();
virtual ~MultithreadDataArray();
bool AddKey(std::string NewKey, T InitData = 0);
bool RemoveKey(std::string RemovedKey);
bool GetData(std::string DataKey, T& OutputData, std::string ContextMessage = "");
bool SetData(std::string DataKey, T InputData, std::string ContextMessage = "");
void PrintData();
#ifdef FOR_ROBOT
void SendToSmartDashboard();
#endif
private:
std::mutex _dataGuard;
std::unordered_map<std::string, T> _storedData;
};
} /* namespace frc */
#include <Utilities/ThreadSafeData/MultithreadDataArray.cpp>
#endif /* SRC_UTILITIES_THREADSAFEDATA_MULTITHREADDATAARRAY_H_ */
</code></pre>
<p>MultithreadDataArray.cpp</p>
<pre><code>/*
* MultithreadDataArray.cpp
*
* Created on: Nov 9, 2018
* Author: Jake
*/
#ifndef SRC_UTILITIES_THREADSAFEDATA_MULTITHREADDATAARRAY_CPP_
#define SRC_UTILITIES_THREADSAFEDATA_MULTITHREADDATAARRAY_CPP_
#include <Utilities/ThreadSafeData/MultithreadDataArray.h>
#include <iostream>
#ifdef FOR_ROBOT
#include <SmartDashboard/SmartDashboard.h>
#endif
namespace frc {
template <typename T>
MultithreadDataArray<T>::MultithreadDataArray() {
// TODO Auto-generated constructor stub
}
template <typename T>
MultithreadDataArray<T>::~MultithreadDataArray() {
// TODO Auto-generated destructor stub
}
template <typename T>
bool MultithreadDataArray<T>::AddKey(std::string NewKey, T InitData) {
bool success = true;
_dataGuard.lock();
bool insertSuccess = _storedData.insert(std::pair<std::string, T>(NewKey, InitData)).second;
if (!insertSuccess) {
success = false;
}
_dataGuard.unlock();
return success;
}
template <typename T>
bool MultithreadDataArray<T>::RemoveKey(std::string RemovedKey) {
bool success = false;
_dataGuard.lock();
bool keyErased = _storedData.erase(RemovedKey) != 0;
if (keyErased) {
success = true;
}
_dataGuard.unlock();
return success;
}
template <typename T>
bool MultithreadDataArray<T>::GetData(std::string DataKey, T& OutputData, std::string ContextMessage) {
bool success = true;
_dataGuard.lock();
bool keyExists = _storedData.find(DataKey) != _storedData.end();
if (keyExists) {
OutputData = _storedData.at(DataKey);
} else {
if (ContextMessage != "") {
std::cout << "Get() Key Failure: " << ContextMessage << ", " << DataKey << std::endl;
}
success = false;
}
_dataGuard.unlock();
return success;
}
template <typename T>
bool MultithreadDataArray<T>::SetData(std::string DataKey, T InputData, std::string ContextMessage) {
bool success = true;
_dataGuard.lock();
if (_storedData.find(DataKey) != _storedData.end()) {
_storedData[DataKey] = InputData;
} else {
if (ContextMessage != "") {
std::cout << "Set() Key Failure: " << ContextMessage << ", " << DataKey << ": " << InputData
<< std::endl;
}
success = false;
}
_dataGuard.unlock();
return success;
}
template <typename T>
void MultithreadDataArray<T>::PrintData() {
_dataGuard.lock();
for (std::pair<std::string, T> element : _storedData) {
T temp = element.second;
std::cout << element.first << ": " << temp << std::endl;
}
_dataGuard.unlock();
}
#ifdef FOR_ROBOT
template <typename T>
void MultithreadDataArray<T>::SendToSmartDashboard() {
for (std::pair<std::string, T> element : _storedData) {
T temp = element.second;
frc::SmartDashboard::PutNumber(element.first, static_cast<double>(temp));
}
}
#endif
} /* namespace frc */
#endif
</code></pre>
<p>Similar to the last, but made for CheckedData datatypes.</p>
<p>SafeMultiThreadDataArray.h:</p>
<pre><code>/*
* SafeMultithreadDataArray.h
*
* Created on: Nov 9, 2018
* Author: Jake
*/
#ifndef SRC_UTILITIES_THREADSAFEDATA_SAFEMULTITHREADDATAARRAY_H_
#define SRC_UTILITIES_THREADSAFEDATA_SAFEMULTITHREADDATAARRAY_H_
#include <unordered_map>
#include <mutex>
#include <string>
#include <Defines.h>
#include <Utilities/ThreadSafeData/CheckedData.h>
namespace frc {
template <typename T>
class SafeMultithreadDataArray {
public:
SafeMultithreadDataArray();
virtual ~SafeMultithreadDataArray();
bool AddKey(std::string NewKey, T InitData, T rangeMin = 0, T rangeMax = 0, unsigned int timeoutUS = 0);
bool RemoveKey(std::string RemovedKey);
bool GetData(std::string DataKey, T& OutputData, std::string ContextMessage = "", bool forceIfTest = false, bool forceIfDegraded = true, bool forceIfInvalid = false);
bool SetData(std::string DataKey, T InputData, std::string ContextMessage = "", bool isTest = false, bool forceIfDegraded = false);
void PrintData();
#ifdef FOR_ROBOT
void SendToSmartDashboard();
#endif
private:
std::mutex _dataGuard;
std::unordered_map<std::string, CheckedData<T>> _storedData;
};
} /* namespace frc */
#include <Utilities/ThreadSafeData/SafeMultithreadDataArray.cpp>
#endif /* SRC_UTILITIES_THREADSAFEDATA_SAFEMULTITHREADDATAARRAY_H_ */
</code></pre>
<p>SafeMultiThreadedDataArray.cpp</p>
<pre><code>/*
* SafeMultithreadDataArray.cpp
*
* Created on: Nov 9, 2018
* Author: Jake
*/
#ifndef SRC_UTILITIES_THREADSAFEDATA_SAFEMULTITHREADDATAARRAY_CPP_
#define SRC_UTILITIES_THREADSAFEDATA_SAFEMULTITHREADDATAARRAY_CPP_
#include <Utilities/ThreadSafeData/SafeMultithreadDataArray.h>
#include <iostream>
#ifdef FOR_ROBOT
#include <SmartDashboard/SmartDashboard.h>
#endif
namespace frc {
template <typename T>
SafeMultithreadDataArray<T>::SafeMultithreadDataArray() {
// TODO Auto-generated constructor stub
}
template <typename T>
SafeMultithreadDataArray<T>::~SafeMultithreadDataArray() {
// TODO Auto-generated destructor stub
}
template <typename T>
bool SafeMultithreadDataArray<T>::AddKey(std::string NewKey, T InitData, T rangeMin, T rangeMax, unsigned int timeoutUS) {
bool success = true;
_dataGuard.lock();
bool insertSuccess = _storedData.emplace(std::pair<std::string, CheckedData<T>>(NewKey, CheckedData<T>(InitData, rangeMin, rangeMax, timeoutUS))).second;
if (!insertSuccess) {
success = false;
}
_dataGuard.unlock();
return success;
}
template <typename T>
bool SafeMultithreadDataArray<T>::RemoveKey(std::string RemovedKey) {
bool success = false;
_dataGuard.lock();
bool keyErased = _storedData.erase(RemovedKey) != 0;
if (keyErased) {
success = true;
}
_dataGuard.unlock();
return success;
}
template <typename T>
bool SafeMultithreadDataArray<T>::GetData(std::string DataKey, T& OutputData, std::string ContextMessage, bool forceIfTest, bool forceIfDegraded,
bool forceIfInvalid) {
bool success = true;
_dataGuard.lock();
bool keyExists = _storedData.find(DataKey) != _storedData.end();
if (keyExists) {
DataValidity validity = _storedData.at(DataKey).GetData(OutputData, forceIfTest, forceIfDegraded, forceIfInvalid);
switch (validity) {
case DataValidity::DATA_VALIDITY_DEGRADED:
if(forceIfDegraded) {
if (ContextMessage != "") {
std::cout << "Get() Forced Degraded: " << ContextMessage << ", " << DataKey << std::endl;
}
} else {
if (ContextMessage != "") {
std::cout << "Get() Degraded: " << ContextMessage << ", " << DataKey << std::endl;
}
success = false;
}
break;
case DataValidity::DATA_VALIDITY_INVALID:
if(forceIfDegraded) {
if (ContextMessage != "") {
std::cout << "Get() Forced Invalid: " << ContextMessage << ", " << DataKey << std::endl;
}
} else {
if (ContextMessage != "") {
std::cout << "Get() Invalid: " << ContextMessage << ", " << DataKey << std::endl;
}
success = false;
}
break;
case DataValidity::DATA_VALIDITY_TEST:
if(forceIfDegraded) {
if (ContextMessage != "") {
std::cout << "Get() Forced Test: " << ContextMessage << ", " << DataKey << std::endl;
}
} else {
if (ContextMessage != "") {
std::cout << "Get() Test: " << ContextMessage << ", " << DataKey << std::endl;
}
success = false;
}
break;
default:
break;
}
} else {
if (ContextMessage != "") {
std::cout << "Get() Key Failure: " << ContextMessage << ", " << DataKey << std::endl;
}
success = false;
}
_dataGuard.unlock();
return success;
}
template <typename T>
bool SafeMultithreadDataArray<T>::SetData(std::string DataKey, T InputData, std::string ContextMessage, bool isTest, bool forceIfDegraded) {
bool success = true;
_dataGuard.lock();
if (_storedData.find(DataKey) != _storedData.end()) {
DataValidity validity = _storedData.at(DataKey).SetData(InputData, isTest, forceIfDegraded);
switch (validity) {
case DataValidity::DATA_VALIDITY_DEGRADED:
if(forceIfDegraded) {
if (ContextMessage != "") {
std::cout << "Set() Forced Degraded: " << ContextMessage << ", " << DataKey << std::endl;
}
} else {
if (ContextMessage != "") {
std::cout << "Set() Degraded: " << ContextMessage << ", " << DataKey << std::endl;
}
success = false;
}
break;
default:
// Nothing here
break;
}
} else {
if (ContextMessage != "") {
std::cout << "Set() Key Failure: " << ContextMessage << ", " << DataKey << ": " << InputData
<< std::endl;
}
success = false;
}
_dataGuard.unlock();
return success;
}
template <typename T>
void SafeMultithreadDataArray<T>::PrintData() {
for (std::pair<std::string, CheckedData<T>> element : _storedData) {
T temp;
DataValidity validity = element.second.GetData(temp, true, true, true);
std::cout << element.first << ": " << validity << ", " << temp << std::endl;
}
}
#ifdef FOR_ROBOT
template <typename T>
void SafeMultithreadDataArray<T>::SendToSmartDashboard() {
for (std::pair<std::string, CheckedData<T>> element : _storedData) {
T temp;
DataValidity validity = element.second.GetData(temp, true, true, true);
frc::SmartDashboard::PutNumber(element.first + " Validity", static_cast<double>(validity));
frc::SmartDashboard::PutNumber(element.first, static_cast<double>(temp));
}
}
#endif
} /* namespace frc */
#endif
</code></pre>
<p>This will contain all the data for a thread. Friends of the Derived classes from this will be able call the functions required to modify the data within this. Any thread will be able to use the Get() functions.</p>
<p>ThreadDataBase.h</p>
<pre><code>/*
* ThreadDataBase.h
*
* Created on: Oct 23, 2018
* Author: Jake
*/
#ifndef SRC_THREADDATABASE_H_
#define SRC_THREADDATABASE_H_
#include <Utilities/ThreadSafeData/MultithreadDataArray.h>
#include <Utilities/ThreadSafeData/SafeMultithreadDataArray.h>
#include <unordered_map>
#include <mutex>
#include <string>
#include <condition_variable>
#include <Defines.h>
namespace frc {
class ThreadDataBase {
public:
ThreadDataBase();
virtual ~ThreadDataBase();
template<typename T>
bool GetData(std::string DataKey, T& OutputData, std::string ContextMessage = "");
template<typename T>
bool GetSafeData(std::string DataKey, T& OutputData, std::string ContextMessage = "", bool forceIfTest = true, bool forceIfDegraded = true, bool forceIfInvalid = true);
void PrintData();
#ifdef FOR_ROBOT
void SendToSmartDashboard();
#endif
// void MakeAServiceRequest(bool Blocking, unsigned int MaxBlockTimeUS);
protected:
template<typename T>
bool SetData(std::string DataKey, T InputData, std::string ContextMessage = "");
template<typename T>
bool SetSafeData(std::string DataKey, T InputData, std::string ContextMessage = "", bool isTest = false, bool forceIfDegraded = false);
template<typename T>
bool AddKey(std::string NewIndex, T initData = 0);
template<typename T>
bool AddSafeKey(std::string NewIndex, T initData = 0, T Min = 0, T Max = 0, unsigned int TimeoutUS = 0);
template<typename T>
bool RemoveKey(std::string RemovedKey);
template<typename T>
bool RemoveSafeKey(std::string RemovedKey);
std::mutex serviceGuard;
std::mutex mtxNotifier;
std::condition_variable conditionWait;
private:
MultithreadDataArray<int> _intData;
MultithreadDataArray<double> _doubleData;
SafeMultithreadDataArray<int> _intDataSafe;
SafeMultithreadDataArray<double> _doubleDataSafe;
};
} /* namespace frc */
#endif /* SRC_THREADDATABASE_H_ */
</code></pre>
<p>ThreadDataBase.cpp</p>
<pre><code>/*
* ThreadDataBase.cpp
*
* Created on: Oct 23, 2018
* Author: Jake
*/
#include <ThreadBases/ThreadDataBase.h>
#include <iostream>
#ifdef FOR_ROBOT
#include <SmartDashboard/SmartDashboard.h>
#endif
namespace frc {
ThreadDataBase::ThreadDataBase() {
// TODO Auto-generated constructor stub
}
ThreadDataBase::~ThreadDataBase() {
// TODO Auto-generated destructor stub
}
/**
* Adds new key for type int.
* Returns true if the DataKey was successfully created.
* Returns false if the DataKey already exists.
* @param NewKey String that is used to identify the desired data.
* @param InitData Data being retrieved.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::AddKey<int>(std::string NewKey, int initData) {
bool success = _intData.AddKey(NewKey, initData);
return success;
}
/**
* Adds new key for type double.
* Returns true if the DataKey was successfully created.
* Returns false if the DataKey already exists.
* @param NewKey String that is used to identify the desired data.
* @param InitData Data being retrieved.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::AddKey<double>(std::string NewKey, double initData) {
bool success = _doubleData.AddKey(NewKey, initData);
return success;
}
/**
* Adds new key for type int.
* Returns true if the DataKey was successfully created.
* Returns false if the DataKey already exists.
* @param NewKey String that is used to identify the desired data.
* @param InitData Data being retrieved.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::AddSafeKey<int>(
std::string NewKey, int initData, int Min, int Max, unsigned int TimeoutUS) {
bool success = _intDataSafe.AddKey(NewKey, initData, Min, Max, TimeoutUS);
return success;
}
/**
* Adds new key for type double.
* Returns true if the DataKey was successfully created.
* Returns false if the DataKey already exists.
* @param NewKey String that is used to identify the desired data.
* @param InitData Data being retrieved.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::AddSafeKey<double>(
std::string NewKey, double initData, double Min, double Max, unsigned int TimeoutUS) {
bool success = _doubleDataSafe.AddKey(NewKey, initData, Min, Max, TimeoutUS);
return success;
}
/**
* Removes key for int data types.
* Returns true if the DataKey was successfully removed.
* Returns false if the DataKey doesn't exist.
* @param RemovedKey String that is used to identify the desired data.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::RemoveKey<int>(std::string RemovedKey) {
bool success = _intData.RemoveKey(RemovedKey);
return success;
}
/**
* Removes key for double data types.
* Returns true if the DataKey was successfully removed.
* Returns false if the DataKey doesn't exist.
* @param RemovedKey String that is used to identify the desired data.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::RemoveKey<double>(std::string RemovedKey) {
bool success = _doubleData.RemoveKey(RemovedKey);
return success;
}
/**
* Removes key for safe int data types.
* Returns true if the DataKey was successfully removed.
* Returns false if the DataKey doesn't exist.
* @param RemovedKey String that is used to identify the desired data.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::RemoveSafeKey<int>(std::string RemovedKey) {
bool success = _intDataSafe.RemoveKey(RemovedKey);
return success;
}
/**
* Removes key for safe double data types.
* Returns true if the DataKey was successfully removed.
* Returns false if the DataKey doesn't exist.
* @param RemovedKey String that is used to identify the desired data.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::RemoveSafeKey<double>(std::string RemovedKey) {
bool success = _doubleDataSafe.RemoveKey(RemovedKey);
return success;
}
/**
* Gets data of type int.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param OutputData Data being retrieved.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::GetData<int>(std::string DataKey, int& OutputData, std::string ContextMessage) {
bool success = _intData.GetData(DataKey, OutputData, ContextMessage);
return success;
}
/**
* Gets data of type double.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param OutputData Data being retrieved.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::GetData<double>(std::string DataKey, double& OutputData, std::string ContextMessage) {
bool success = _doubleData.GetData(DataKey, OutputData, ContextMessage);
return success;
}
/**
* Gets data of type int.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param OutputData Data being retrieved.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::GetSafeData<int>(std::string DataKey, int& OutputData, std::string ContextMessage, bool forceIfTest, bool forceIfDegraded, bool forceIfInvalid) {
bool success = _intDataSafe.GetData(DataKey, OutputData, ContextMessage, forceIfTest, forceIfDegraded, forceIfInvalid);
return success;
}
/**
* Gets data of type double.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param OutputData Data being retrieved.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::GetSafeData<double>(std::string DataKey, double& OutputData, std::string ContextMessage, bool forceIfTest, bool forceIfDegraded, bool forceIfInvalid) {
bool success = _doubleDataSafe.GetData(DataKey, OutputData, ContextMessage, forceIfTest, forceIfDegraded, forceIfInvalid);
return success;
}
/**
* Sets data of type int.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param Data being written.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::SetData<int>(std::string DataKey, int InputData, std::string ContextMessage) {
bool success = _intData.SetData(DataKey, InputData, ContextMessage);
return success;
}
/**
* Sets data of type double.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param Data being written.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::SetData<double>(std::string DataKey, double InputData, std::string ContextMessage) {
bool success = _doubleData.SetData(DataKey, InputData, ContextMessage);
return success;
}
/**
* Sets data of type int.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param Data being written.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::SetSafeData<int>(std::string DataKey, int InputData, std::string ContextMessage, bool isTest, bool forceIfDegraded) {
bool success = _intDataSafe.SetData(DataKey, InputData, ContextMessage, isTest, forceIfDegraded);
return success;
}
/**
* Sets data of type double.
* Returns true if the DataKey exists for the output type.
* Returns false otherwise.
* @param DataKey String that is used to identify the desired data.
* @param Data being written.
* @param ContextMessage Optional string for debugging.
* @return success Returns success as true or false.
*/
template<>
bool ThreadDataBase::SetSafeData<double>(std::string DataKey, double InputData, std::string ContextMessage, bool isTest, bool forceIfDegraded) {
bool success = _doubleDataSafe.SetData(DataKey, InputData, ContextMessage, isTest, forceIfDegraded);
return success;
}
void ThreadDataBase::PrintData() {
_intData.PrintData();
_doubleData.PrintData();
_intDataSafe.PrintData();
_doubleDataSafe.PrintData();
}
#ifdef FOR_ROBOT
void ThreadDataBase::SendToSmartDashboard() {
_intData.PrintData();
_doubleData.PrintData();
_intDataSafe.PrintData();
_doubleDataSafe.PrintData();
}
#endif
} /* namespace frc */
</code></pre>
<p>This is simply a place to put the data for all the threads. Each thread will have it's own data structure in here that only it can write to, but all the other threads can read from. Each thread will have a pointer to the actual instance of this class. The threads should be able to read and write with absolutely no regards for the activities of the other threads.</p>
<p>ThreadDataContainer.h</p>
<pre><code>/*
* ThreadDataContainer.h
*
* Created on: Nov 12, 2018
* Author: Jake
*/
#ifndef THREADBASES_THREADDATACONTAINER_H_
#define THREADBASES_THREADDATACONTAINER_H_
#include <Test/TestData.h>
#include <Test2/Test2Data.h>
namespace frc {
class ThreadDataContainer {
public:
ThreadDataContainer();
virtual ~ThreadDataContainer();
TestData _testData;
Test2Data _test2Data;
};
} /* namespace frc */
#endif /* THREADBASES_THREADDATACONTAINER_H_ */
</code></pre>
<p>This is basically empty, but stuff can be added if needed.</p>
<p>ThreadDataContainer.cpp</p>
<pre><code>/*
* ThreadDataContainer.cpp
*
* Created on: Nov 12, 2018
* Author: Jake
*/
#include <ThreadBases/ThreadDataContainer.h>
namespace frc {
ThreadDataContainer::ThreadDataContainer() {
// TODO Auto-generated constructor stub
}
ThreadDataContainer::~ThreadDataContainer() {
// TODO Auto-generated destructor stub
}
} /* namespace frc */
</code></pre>
<p>This is probably the most important part of the entire program. This is where the threads are created and controlled.</p>
<p>ThreadTaskBase.h</p>
<pre><code>/*
* ThreadTaskBase.h
*
* Created on: Oct 23, 2018
* Author: Jake
*/
#ifndef SRC_THREADTASKBASE_H_
#define SRC_THREADTASKBASE_H_
#include <thread>
#include <mutex>
#include <condition_variable>
#include <Defines.h>
#include <ThreadBases/ThreadDataContainer.h>
namespace frc {
class ThreadTaskBase {
public:
ThreadTaskBase(ThreadDataContainer* threadData);
virtual ~ThreadTaskBase();
bool Start(const int periodUS);
void Stop(bool joinThread);
double GetPeriod();
protected:
ThreadDataContainer* _threadData;
private:
bool _stopThread = false;
bool _taskOverloaded = false;
long int _periodUS = 10000;
std::thread _workerThread;
std::mutex _workerThreadGuard;
void ThreadMain(int periodUS);
virtual void ThreadTask();
// void ServiceRequestTemplate();
};
} /* namespace frc */
#endif /* SRC_THREADTASKBASE_H_ */
</code></pre>
<p>ThreadTaskBase.cpp</p>
<pre><code>/*
* ThreadTaskBase.cpp
*
* Created on: Oct 23, 2018
* Author: Jake
*/
#include <ThreadBases/ThreadTaskBase.h>
#include <iostream>
#ifdef FOR_ROBOT
#include <SmartDashboard/SmartDashboard.h>
#endif
namespace frc {
/**
* Default constructor.
* Runs the default constructor for the worker thread, but doesn't
* actually start the thread.
*/
ThreadTaskBase::ThreadTaskBase(ThreadDataContainer* threadData)
: _threadData(threadData),
_workerThread() {
// Nothing to do here.
}
/**
* Default destructor.
* Calls the Stop() function with the parameter TRUE to end the worker thread's
* execution and wait for it to finish.
*/
ThreadTaskBase::~ThreadTaskBase() {
Stop(true);
}
/**
* Default task that is executed periodically by ThreadMain().
* This is overridden by the user.
*/
void ThreadTaskBase::ThreadTask() {
// Override this!!!
};
/**
* Starts the worker thread which executes the main thread.
* Success if a worker thread was successfully created.
* Failure if a worker thread is already running, indicated by the mutex lock.
* @param periodUS The time period for processing cycles to occur in microseconds (US).
* @return Success Returns true if success, false if failure.
*/
bool ThreadTaskBase::Start(int periodUS) {
if (_workerThreadGuard.try_lock()) {
_workerThread = std::thread(&ThreadTaskBase::ThreadMain, this, periodUS);
_workerThreadGuard.unlock();
return true;
} else {
return false;
}
}
/**
* Sends the signal to stop thread execution.
* @param joinThread Whether or not to wait for the thread to finish execution.
*/
void ThreadTaskBase::Stop(bool joinThread) {
_stopThread = true;
if (joinThread && _workerThread.joinable()) {
_workerThread.join();
}
}
/**
* Returns the period of thread in seconds.
* @return Period Period between processing cycles.
*/
double ThreadTaskBase::GetPeriod() {
return _periodUS;
}
/**
* Main worker thread which executes ThreadTask() periodically.
* @param periodUS The time period for processing cycles to occur in microseconds (US).
*/
void ThreadTaskBase::ThreadMain(const int periodUS) {
_periodUS = periodUS;
_stopThread = false;
_workerThreadGuard.lock();
while (!_stopThread) {
auto nextCycleTime = std::chrono::steady_clock::now() + std::chrono::microseconds(periodUS);
ThreadTask();
auto cycleEndTime = std::chrono::steady_clock::now();
if (cycleEndTime > nextCycleTime) {
_taskOverloaded = true;
} else {
_taskOverloaded = false;
}
std::this_thread::sleep_until(nextCycleTime);
}
_workerThreadGuard.unlock();
}
} /* namespace frc */
</code></pre>
<p>This is the data class for output data from TestTask class.</p>
<p>TestData.h</p>
<pre><code>/*
* TestData.h
*
* Created on: Nov 10, 2018
* Author: Jake
*/
#ifndef TEST_TESTDATA_H_
#define TEST_TESTDATA_H_
#include <ThreadBases/ThreadDataBase.h>
#include <string>
namespace frc {
class TestData : public ThreadDataBase {
public:
friend class TestTask;
TestData();
virtual ~TestData();
void SetDataManual(std::string datakey, int inputdata, std::string contextmessage = "") {
SetData(datakey, inputdata, contextmessage);
}
void SetDataManual(std::string datakey, double inputdata, std::string contextmessage = "") {
SetData(datakey, inputdata, contextmessage);
}
void SetSafeDataManual(std::string datakey, int inputdata, std::string contextmessage = "", bool isTest = false, bool forceIfDegraded = false) {
SetSafeData(datakey, inputdata, contextmessage, isTest, forceIfDegraded);
}
void SetSafeDataManual(std::string datakey, double inputdata, std::string contextmessage = "", bool isTest = false, bool forceIfDegraded = false) {
SetSafeData(datakey, inputdata, contextmessage, isTest, forceIfDegraded);
}
};
} /* namespace frc */
#endif /* TEST_TESTDATA_H_ */
</code></pre>
<p>TestData.cpp</p>
<pre><code>/*
* TestData.cpp
*
* Created on: Nov 10, 2018
* Author: Jake
*/
#include <Test/TestData.h>
namespace frc {
TestData::TestData() {
// TODO Auto-generated constructor stub
}
TestData::~TestData() {
// TODO Auto-generated destructor stub
}
} /* namespace frc */
</code></pre>
<p>This is the first bit of code that does actual work. It creates several keys during the constructor, then does periodic processing on the data.</p>
<p>TestTask.h</p>
<pre><code>/*
* TestTaskData.h
*
* Created on: Nov 10, 2018
* Author: Jake
*/
#ifndef TEST_TESTTASK_H_
#define TEST_TESTTASK_H_
#include <ThreadBases/ThreadTaskBase.h>
namespace frc {
class TestTask : public ThreadTaskBase {
public:
TestTask(ThreadDataContainer* threadData);
virtual ~TestTask();
private:
void ThreadTask() override;
};
} /* namespace frc */
#endif /* TEST_TESTTASK_H_ */
</code></pre>
<p>TestTask.cpp</p>
<pre><code>/*
* TestTaskData.cpp
*
* Created on: Nov 10, 2018
* Author: Jake
*/
#include <Test/TestTask.h>
#include <iostream>
namespace frc {
TestTask::TestTask(ThreadDataContainer* threadData):
ThreadTaskBase(threadData) {
// ThreadCountKey demonstrates the worker thread's ability to update data.
_threadData->_testData.AddKey<int>("ThreadCountKey");
// UserCountKey demonstrates the ability of other threads to update data.
_threadData->_testData.AddKey<int>("UserCountKey");
// Demonstration of data storage without range limitaions or minimum update periods.
_threadData->_testData.AddKey<int>("Key 1");
_threadData->_testData.AddKey<double>("Key 2");
// Demonstration of "Safe" data storage with no limits set.
_threadData->_testData.AddSafeKey<int>("Key 3");
_threadData->_testData.AddSafeKey<double>("Key 4");
// Demonstration of "Safe" data storage with:
// 1) Range checking. This will not update out-of-range values unless forced.
// 2) Data "Validity" requires that the data be updated every so often, or else the data is marked as stale, or "Invalid".
//
// These examples use ranges [-6, 6] and [-5, 5].
// The timeouts were set to 2,000,000 microseconds, or 2 seconds.
_threadData->_testData.AddSafeKey<int>("Key 5", 0, -6, 6, 2000000);
_threadData->_testData.AddSafeKey<double>("Key 6", 0, -5, 5, 2000000);
// This demonstrates the ability of both threads to share common data.
// Only the "owner" thread should be able to write to this and it is discouraged to have
// multiple thread writing to the same data structure, but reading and writing can be done.
// That's why the "TestTask" class is a friend of "TestData".
_threadData->_testData.AddKey<int>("Shared Key");
}
TestTask::~TestTask() {
// TODO Auto-generated destructor stub
}
void TestTask::ThreadTask() {
// This function reads the data, does some processing on the data, then writes the data back.
// This is done for both it's own data, and the shared data.
int temp1 = -0xFFFF;
_threadData->_testData.GetData("ThreadCountKey", temp1, "Thread Task");
temp1++;
_threadData->_testData.SetData("ThreadCountKey", temp1, "Thread Task");
int temp2 = -0xFFFF;
_threadData->_testData.GetData("Shared Key", temp2, "Thread Task");
temp2 += 1000;
_threadData->_testData.SetData("Shared Key", temp2, "Thread Task");
_threadData->_testData.PrintData();
}
} /* namespace frc */
</code></pre>
<p>Output data for 2nd worker thread.</p>
<p>Test2Data.h</p>
<pre><code>/*
* Test2Data.h
*
* Created on: Nov 11, 2018
* Author: Jake
*/
#ifndef TEST2_TEST2DATA_H_
#define TEST2_TEST2DATA_H_
#include <ThreadBases/ThreadDataBase.h>
namespace frc {
class Test2Data : public ThreadDataBase {
public:
friend class Test2Task;
friend int main();
Test2Data();
virtual ~Test2Data();
};
} /* namespace frc */
#endif /* TEST2_TEST2DATA_H_ */
</code></pre>
<p>Test2Data.cpp</p>
<pre><code>/*
* Test2Data.cpp
*
* Created on: Nov 11, 2018
* Author: Jake
*/
#include <Test2/Test2Data.h>
namespace frc {
Test2Data::Test2Data() {
// TODO Auto-generated constructor stub
}
Test2Data::~Test2Data() {
// TODO Auto-generated destructor stub
}
} /* namespace frc */
</code></pre>
<p>A 2nd worker thread to demonstrate multitasking abilities and the abilities of the threads to maintain consistent timing, as well as inter-thread communication.</p>
<p>Test2Task.h</p>
<pre><code>/*
* Test2Task.h
*
* Created on: Nov 11, 2018
* Author: Jake
*/
#ifndef TEST2_TEST2TASK_H_
#define TEST2_TEST2TASK_H_
#include <ThreadBases/ThreadTaskBase.h>
namespace frc {
class Test2Task : public ThreadTaskBase {
public:
Test2Task(ThreadDataContainer* threadData);
virtual ~Test2Task();
private:
void ThreadTask() override;
};
} /* namespace frc */
#endif /* TEST2_TEST2TASK_H_ */
</code></pre>
<p>Test2Task.cpp</p>
<pre><code>/*
* Test2Task.cpp
*
* Created on: Nov 11, 2018
* Author: Jake
*/
#include <Test2/Test2Task.h>
#include <iostream>
namespace frc {
Test2Task::Test2Task(ThreadDataContainer* threadData):
ThreadTaskBase(threadData) {
// TODO Auto-generated constructor stub
}
Test2Task::~Test2Task() {
// TODO Auto-generated destructor stub
}
void Test2Task::ThreadTask() {
// This task reads one of the variables in the data from the other thread.
int temp = -0xFFFF;
_threadData->_testData.GetSafeData("Key 5", temp,"", true, true, true);
std::cout << "Thread 2: " << temp << std::endl;
}
} /* namespace frc */
</code></pre>
<p>Master thread for the whole program.</p>
<p>Bot_Codebase_Test.cpp</p>
<pre><code>/*
* Bot_Codebase_Test.cpp.h
*
* Created on: Nov 08, 2018
* Author: Jake
*/
#define WAIT_FOR_ENTER_PRESS std::cin.ignore();
#include <iostream>
using namespace std;
#include <Test/TestTask.h>
#include <Test/TestData.h>
#include <Test2/Test2Task.h>
int main() {
frc::ThreadDataContainer threadData; // Contains data structures for each thread.
frc::TestTask testTask(&threadData); // 1st worker thread.
frc::Test2Task test2Task(&threadData); // 2nd worker thread.
testTask.Start(1000000); // 1 hz
test2Task.Start(333333); // 3 hz
int temp1 = 0;
double temp2 = 0;
int temp3 = 0;
double temp4 = 0;
int temp5 = 0;
double temp6 = 0;
while (true) {
WAIT_FOR_ENTER_PRESS
temp1 += 1;
temp2 += 0.333;
temp3 = ((temp3 < 10) ? (temp3 + 1) : -10);
temp4 = ((temp4 < 10.0) ? (temp4 + 0.5) : -10.0);
temp5 = ((temp5 < 10) ? (temp5 + 1) : -10);
temp6 = ((temp6 < 10.0) ? (temp6 + 0.4) : -10.0);
threadData._testData.SetDataManual("Key 1", temp1, "Input 1");
threadData._testData.SetDataManual("Key 2", temp2, "Input 2");
threadData._testData.SetSafeDataManual("Key 3", temp3, "Input 3", false, true);
threadData._testData.SetSafeDataManual("Key 4", temp4, "Input 4");
threadData._testData.SetSafeDataManual("Key 5", temp5, "Input 5");
threadData._testData.SetSafeDataManual("Key 6", temp6, "Input 6", true, false);
int temp2 = -0xFFFF;
threadData._testData.GetData("Shared Key", temp2, "Thread Task");
temp2 += 1;
threadData._testData.SetDataManual("Shared Key", temp2, "Thread Task");
int tempCount = -0xFFFF;
threadData._testData.GetData("UserCountKey", tempCount);
tempCount++;
threadData._testData.SetDataManual("UserCountKey", tempCount);
//Sleep(1500);
}
return 0;
}
</code></pre>
<p>Not really used at the moment.</p>
<p>Defines.h</p>
<pre><code>/*
* Defines.h
*
* Created on: Nov 9, 2018
* Author: Jake
*/
#ifndef SRC_DEFINES_H_
#define SRC_DEFINES_H_
#endif /* SRC_DEFINES_H_ */
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T04:56:08.137",
"Id": "207625",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"thread-safety"
],
"Title": "Multithreaded FRC Robot Framework (Kinda Big)"
} | 207625 |
<p>I am new to C++ threading library. I would love to get some comments on how to improve this code (if there are possible bugs, I would appreciate that feedback too). In particular, I want to refactor the code for the methods of the linked list:</p>
<ol>
<li>How to return unique_lock in a function so that it didn't unlock the mutex under the hood? </li>
<li>Are there possible deadlocks with the lock acquisition that takes place in my code?</li>
<li><p>Does it look correct?</p>
<pre><code>#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
using namespace std;
/*
* This is an implementation of a singly linked list with node-level locks to
* ensure mutual exclusion. The structure looks like this:
* head_ -> node_0 -> node_1 -> ... -> node_n -> tail_
* Note that head_ and tail_ are dummy nodes.
*/
class LockBasedLinkedList {
public:
// Initialize head_ to point to tail_ (empty list).
LockBasedLinkedList() {
tail_ = new Node(0);
head_ = new Node(0, tail_);
}
/*
* Insert a node with value val at position pos.
*
* To ensure mutual exclusion, the locks of the current node and the
* previous nodes must be acquired for insertion to work. As soon as the
* locks are acquired the code does roughly the following:
*
* | prev -> node | prev -> node | prev node |
* | | ^ | v ^ |
* | new_node | new_node | new_node |
*/
void insert(int val, int pos) {
Node *new_node = new Node(val);
Node *prev = head_;
unique_lock<mutex> prev_lk(prev->m);
Node *node = prev->next;
unique_lock<mutex> node_lk(node->m);
for (int i = 0; i < pos && node != tail_; i++) {
prev = node;
node = node->next;
prev_lk.swap(node_lk);
node_lk = unique_lock<mutex>(node->m);
}
new_node->next = node;
prev->next = new_node;
}
/*
* Erase the node at position pos.
*
* To ensure mutual exclusion, follow the steps from insert(). As soon as
* the locks are acquired the code does roughly the following:
*
* (*) (*) (*) (*) (*)
* | prev -> node -> next | prev node -> next | prev ---------> next |
* | | v--------------^ | |
*
* (*) highlights the nodes whose locks are acquired.
*/
void erase(int pos) {
Node *prev = head_;
unique_lock<mutex> prev_lk(prev->m);
Node *node = prev->next;
unique_lock<mutex> node_lk(node->m);
for (int i = 0; i < pos && node != tail_; i++) {
prev = node;
node = node->next;
prev_lk.swap(node_lk);
node_lk = unique_lock<mutex>(node->m);
}
if (node == tail_) {
return;
}
prev->next = node->next;
node_lk.unlock();
delete node;
}
int get(int pos) {
Node *prev = head_;
unique_lock<mutex> prev_lk(prev->m);
Node *node = prev->next;
unique_lock<mutex> node_lk(node->m);
for (int i = 0; i < pos && node != tail_; i++) {
prev = node;
node = node->next;
prev_lk.swap(node_lk);
node_lk = unique_lock<mutex>(node->m);
}
if (node == tail_) {
return 0;
}
return node->val;
}
private:
struct Node {
int val;
Node *next;
mutex m;
Node(int val_, Node *next_ = nullptr) : val(val_), next(next_) {}
};
Node *head_, *tail_;
};
void testNThread(int n) {
const int N = 10;
vector<thread> threads(n);
LockBasedLinkedList lst;
for (int i = 0; i < n; i++) {
threads[i] = thread([i, &lst, N]() {
for (int j = 0; j < N; j++) {
lst.insert(i, 0);
}
});
}
for (int i = 0; i < n; i++) {
threads[i].join();
}
for (int i = 0; i < N * n; i++) {
int val = lst.get(0);
lst.erase(0);
cout << val << " ";
}
cout << "\n";
}
int main(int argc, char **argv) {
int n = 10;
if (argc >= 2) {
n = atoi(argv[1]);
}
testNThread(n);
}
</code></pre></li>
</ol>
| [] | [
{
"body": "<p>Congratulations — I think this is the first concurrency-related code I've reviewed on CodeReview in which I have <em>not</em> managed to find any concurrency-related bugs! It looks like a solid implementation of \"hand-over-hand\" traversal. (Now that I've said that, I bet someone else will find a... | {
"AcceptedAnswerId": "207629",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T05:54:19.857",
"Id": "207626",
"Score": "5",
"Tags": [
"c++",
"multithreading",
"thread-safety"
],
"Title": "Linked list node-level locking"
} | 207626 |
<p>My first attempt at Scheme (Chicken Scheme) - a simple RPN calculator. Please comment on exception handling as well as the general coding style. Here is the code:</p>
<pre><code>(use stack)
(use srfi-69)
(use simple-exceptions)
(define prompt "> ")
(define stack (make-stack))
(define words (make-hash-table))
(define (init-words)
(hash-table-set! words "bye" '(quit))
(hash-table-set! words ".s" '(stack-print))
(hash-table-set! words "+" '(add))
(hash-table-set! words "-" '(subtract))
(hash-table-set! words "*" '(multiply))
(hash-table-set! words "/" '(divide))
(hash-table-set! words "." '(pop-print))
(hash-table-set! words "dup" '(dup))
(hash-table-set! words "drop" '(drop))
(hash-table-set! words "swap" '(swap)))
(define (stack-print)
(display (stack->list stack))
(newline))
(define (pop-print)
(display (stack-pop! stack))
(newline))
(define (add)
(stack-push! stack
(+ (stack-pop! stack)
(stack-pop! stack))))
(define (subtract)
(swap)
(stack-push! stack
(- (stack-pop! stack)
(stack-pop! stack))))
(define (multiply)
(stack-push! stack
(* (stack-pop! stack)
(stack-pop! stack))))
(define (divide)
(swap)
(stack-push! stack
(/ (stack-pop! stack)
(stack-pop! stack))))
(define (dup)
(let ((first (stack-pop! stack)))
(stack-push! stack first)
(stack-push! stack first)))
(define (drop)
(stack-pop! stack))
(define (swap)
(let ((first (stack-pop! stack))
(second (stack-pop! stack)))
(stack-push! stack first)
(stack-push! stack second)))
(define (f-read)
(display prompt)
(flush-output)
(read-line))
(define (f-parse line)
(string-split line))
(define (process word)
(cond
((hash-table-exists? words word)
(eval (hash-table-ref words word)))
((string->number word)
(stack-push! stack (string->number word)))))
(define (f-eval words)
(cond
((null? words) "")
(else (process (car words))
(f-eval (cdr words)))))
(define (f-print line)
(display line))
;; user-interrupt ?
(define (repl)
(guard
(exn (((exception-of? 'user-interrupt) exn)
(quit))
((exception? exn)
(display (message exn))
(newline)
(repl))
(else
(display (arguments exn))
(newline)
(repl)))
(init-words)
(f-print (f-eval (f-parse (f-read))))
(repl)))
</code></pre>
| [] | [
{
"body": "<p>You've actually run into a big gotcha here. Scheme doesn't actually specify the order to evaluate operands. This can be a problem for code with side effects, especially if you aren't careful to encapsulate the order you expect explicitly. Any time you see an exclamation mark at the end of the func... | {
"AcceptedAnswerId": "236003",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T07:51:54.237",
"Id": "207631",
"Score": "4",
"Tags": [
"beginner",
"scheme",
"math-expression-eval",
"interpreter"
],
"Title": "RPN calculator in Chicken Scheme"
} | 207631 |
<p>I am creating a very small application to demonstrate solid principles and also a brief implementation of a builder pattern, does anyone have any feedback as to how this could be improved or how it breaks the solid principles? The app is a small app that just converts units, e.g. yards to meters, inches to cms.</p>
<p><strong>Interface</strong></p>
<pre><code>public interface IConverter
{
double ConversionRate { get; set; }
string[] ConvertedUnits { get; set; }
string DisplayText { get; set; }
string[] Convert(string input);
}
</code></pre>
<p><strong>Class implementing interface</strong></p>
<pre><code> public class Converter : IConverter
{
public double ConversionRate { get; set; }
public string[] ConvertedUnits { get; set; }
public string DisplayText { get; set; }
public Converter(double conversionRate, string[] convertedUnits, string displayText)
{
ConversionRate = conversionRate;
ConvertedUnits = convertedUnits;
DisplayText = displayText;
}
public string[] Convert(string input)
{
if (!input.Contains('\n'))
{
double d = double.Parse(input, CultureInfo.InvariantCulture) * ConversionRate;
string[] array = new string[1];
array[0] = d.ToString();
return array;
}
else
{
double[] doubles = new double[input.Split('\n').Count()];
for (int i = 0; i < input.Split('\n').Count(); i++)
{
double value = double.Parse(input.Split('\n')[i]);
doubles[i] = value;
string.Format("{0}", value * ConversionRate);
}
string[] strings = new string[doubles.Length];
for (int i = 0; i < input.Split('\n').Length; i++)
{
strings[i] = string.Format("{0}", doubles[i] * ConversionRate);
}
return strings;
}
}
}
</code></pre>
<p><strong>Builder (abstract class)</strong></p>
<pre><code>public abstract class ConverterBuilder
{
protected double _conversionRate;
protected string[] _convertedUnits;
protected string _displayText;
public ConverterBuilder AddConversionRate(double conversionRate)
{
_conversionRate = conversionRate;
return this;
}
public ConverterBuilder AddConversionRate(string[] convertedUnits)
{
_convertedUnits = convertedUnits;
return this;
}
public ConverterBuilder AddDisplayText(string displayText)
{
_displayText = displayText;
return this;
}
public Converter Build()
{
return new Converter(_conversionRate, _convertedUnits, _displayText);
}
}
</code></pre>
<p><strong>Builder implementing abstract builder class</strong></p>
<pre><code>public class UnitConverterBuilder : ConverterBuilder
{
public UnitConverterBuilder()
{
}
}
</code></pre>
<p><strong>Controller</strong></p>
<pre><code>public IActionResult Convert(string text, double conversionRate)
{
Converter converter = new UnitConverterBuilder()
.AddConversionRate(conversionRate)
.Build();
string output = "";
for (int i = 0; i < converter.Convert(text).Count(); i++)
{
output += converter.Convert(text)[i] + Environment.NewLine;
}
return Content(output);
}
</code></pre>
<p><strong>View</strong></p>
<p>
<p>Enter values to convert</p></p>
<pre><code><form asp-controller="Home" asp-action="Convert" method="post">
<textarea id="text" name="text" rows="10" cols="40"></textarea>
<select name="conversionRate">
<option value="">Please Select</option>
<option value="0.9144">Yards to Meters</option>
<option value="2.54">Inches To Centimeters</option>
</select>
<button>Convert</button>
</form>
</code></pre>
<p></p>
<p>The app is built using .net core, any feedback greatly appreciated :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T10:32:02.280",
"Id": "400786",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your ... | [
{
"body": "<p>Only targeting <code>public string[] Convert(string input)</code> </p>\n\n<ul>\n<li>Because this is a <code>public</code> method you should validate the input. Right now if one passes <code>null</code> this will throw an <code>ArgumentNullException</code> which isn't that bad but the stacktrace b... | {
"AcceptedAnswerId": "207714",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T10:11:01.600",
"Id": "207640",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"asp.net-core"
],
"Title": "Length units converter"
} | 207640 |
<p>I'm working with a REST API, first time doing this and I have a working code but it's long and just looks messy to me. I just know there's a better and faster way to do it.</p>
<pre><code>try {
$LOCATIONS = new \Picqer\Financials\Exact\ItemWarehouse($connection);
$LOCATIONS_GET = $LOCATIONS->get();
foreach($LOCATIONS_GET as $LOCATIONS){
$locationID = $LOCATIONS->ID;
$locationDefaultStorageLocationCode = $LOCATIONS->DefaultStorageLocationCode;
$locationDefaultStorageLocatoinDescription = $LOCATIONS->DefaultStorageLocationDescription;
$locationWarehouseCode = $LOCATIONS->WarehouseCode;
$locationDefaultStorageLocation = $LOCATIONS->DefaultStorageLocation;
$locationLocatieType = 0; //Locatie type
$LOCATIONS_CHECK = $conn->query("SELECT ID FROM data_exact_locations WHERE ID='$locationID' LIMIT 1");
if($LOCATIONS_CHECK->num_rows == 0){
$LOCATIONS_SQL = "INSERT INTO data_exact_locations (ID, Code, Omschrijving, Magazijn, Standaardlocatie, Locatie_type)
VALUES ('$locationID','$locationDefaultStorageLocationCode','$locationDefaultStorageLocatoinDescription', '$locationWarehouseCode', '$locationDefaultStorageLocation')";
if (mysqli_query($conn, $LOCATIONS_SQL)){
echo "Worked! <BR>";
} else{
echo ("Try again! <BR>" . mysqli_error($conn));
}
} else {
echo ("Already in database! <BR>");
}
}
} catch (\Exception $e) {
echo get_class($e) . ' : ' . $e->getMessage();
}
</code></pre>
<p>This is what the code looks like, but this is a short version. There are also instances where I need to get something like 30 variables out of the JSON file, and upload those to a database.</p>
<p>Another example from the same code:</p>
<pre><code>try {
$CRM = new \Picqer\Financials\Exact\Account($connection);
$CRM_GET = $CRM->filter("IsSupplier eq true");
foreach($CRM_GET as $CRM){
$crmID = $CRM->ID;
$crmCode = $CRM->Code;
$crmSearchCode =$CRM->SearchCode;
$crmName = $CRM->Name;
$crmAddressLine1 = $CRM->AddressLine1;
$crmAddressline2 = $CRM->AddressLine2;
$crmAddressline3 = $CRM->AddressLine3;
$crmVatNumber = $CRM->VATNumber;
$crmCountry = $CRM->Country;
$crmCity = $CRM->City;
$crmPostcode = $CRM->Postcode;
$crmState = $CRM->State;
$crmRemarks = $CRM->Remarks;
$CRM_CHECK = $conn->query("SELECT ID FROM data_exact_crm WHERE ID='$crmID' LIMIT 1");
if($CRM_CHECK->num_rows == 0){
$CRM_SQL = "INSERT INTO data_exact_crm (ID, Code, SearchCode, Name, AddressLine1, AddressLine2, AddressLine3, VATNumber, CountryDescription, City, PostCode, StateDescription, Remarks)
VALUES ('$crmID','$crmCode','$crmSearchCode','$crmName','$crmAddressLine1','$crmAddressline2','$crmAddressline3','$crmVatNumber','$crmCountry','$crmCity','$crmPostcode','$crmState','$crmRemarks')";
if (mysqli_query($conn, $CRM_SQL)){
echo "Worked! <BR>";
} else{
echo ("Try Again! <BR>" . mysqli_error($conn));
}
} else {
echo ("Already in database! <BR>");
}
}
} catch (\Exception $e) {
echo get_class($e) . ' : ' . $e->getMessage();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T20:49:34.267",
"Id": "401049",
"Score": "0",
"body": "I might be wrong, but does this code work? The value parameters are string representations of your variable name and I'm not sure this works in PHP (or in a lot of languages)"
... | [
{
"body": "<p>PDO has a great feature for you, <a href=\"https://phpdelusions.net/pdo#prepared\" rel=\"nofollow noreferrer\">it can accept an array with parameters for <code>execute()</code></a>. It means you won't have to extract separate variables anymore.</p>\n\n<p>So just use PDO instead of mysqli and your ... | {
"AcceptedAnswerId": "207658",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T11:18:02.707",
"Id": "207646",
"Score": "-1",
"Tags": [
"php",
"mysql",
"json",
"database"
],
"Title": "Getting data from REST API (JSON), extract variables and upload those to database using MySQL"
} | 207646 |
<p>In one of my java projects I use singletons a lot and I was looking for a way to reduce repeating code. I made a <code>SingletonUtils</code> class that accepts a class and supplier parameter. Then stores the instance in a hash map. This way the static instance isn't stored as a static variable in the class I want to make a singleton.</p>
<p>My question is, is there any problems/cons with implementing the singleton pattern like this and is there an easier way to do this or is this the best way?</p>
<pre><code>public class SingletonUtils {
public static HashMap<Class, Object> instances = new HashMap<>();
public static <T> T getInstance(final Class<T> singletonObj, final Supplier<T> creator) {
if(!instances.containsKey(singletonObj)) {
if(creator == null) return null;
else instances.put(singletonObj, creator.get());
}
return (T) instances.get(singletonObj);
}
public static boolean instanceExists(final Class singletonObj) {
return instances.containsKey(singletonObj);
}
public static void removeInstance(final Class singletonObj) {
instances.remove(singletonObj);
}
}
public final class AuthManager {
private AuthManager() { }
public static AuthManager getNewInstance() {
return SingletonUtils.getInstance(AuthManager.class, AuthManager::new);
}
}
</code></pre>
| [] | [
{
"body": "<p>Let me just express the first thing that came to mind when I read this question's title:</p>\n\n<blockquote>\n <p>Not another Singleton question.</p>\n</blockquote>\n\n<p>Let's ignore in the following that Singletons are an anti-pattern in Object-Oriented Programming.</p>\n\n<p>Look. I get it. Si... | {
"AcceptedAnswerId": "207653",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T11:52:04.643",
"Id": "207649",
"Score": "0",
"Tags": [
"java",
"singleton"
],
"Title": "Storing singleton instances in a generic utils class"
} | 207649 |
<p>Given the Josephus Problem.</p>
<blockquote>
<p>Josephus Problem</p>
<p>N people (numbered 1 to N) are standing in a circle. Person 1 kills Person 2 with a sword and gives it to Person 3. Person 3 kills Person 4 and gives the sword to Person 5. This process is repeated until only one person is alive.</p>
<p>Task:
(Medium) Given the number of people N, write a program to find the number of the person that stays alive at the end.
(Hard) Show each step of the process.</p>
<p>(The description from Sololearn application)"</p>
</blockquote>
<p>This is my code. The <code>forEachRemaining</code> method solution is correct? I have to do something with this inherited method, but it has no meaning. </p>
<pre><code>import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
class CyclicIterator implements Iterator {
private final List list;
private Iterator iterator;
public CyclicIterator(List list) {
this.list = list;
initIterator(list);
}
private void initIterator(List list) {
this.iterator = list.iterator();
}
@Override
public boolean hasNext() {
return !list.isEmpty();
}
@Override
public Object next() {
if (!this.iterator.hasNext())
initIterator(list);
return this.iterator.next();
}
@Override
public void remove() {
this.iterator.remove();
}
@Override
public void forEachRemaining(Consumer action) {
throw new UnsupportedOperationException("This method has no meaning in CyclicIterator class!");
}
}
public class JosephusProblem {
public static void main(String[] args) {
execution(0);
execution(1);
execution(2);
execution(4);
execution(6);
}
private static void execution(int members) {
if (members < 1) {
System.out.println("The parameter (members) has to be bigger than 0!");
return;
}
if (members == 1) {
System.out.println("There is olny one person, so he is the survivor. Peaceful version! :)");
return;
}
LinkedList<Integer> list = new LinkedList();
for (int index = 0; index < members; index++)
list.add(index + 1);
Iterator<Integer> it = new CyclicIterator(list);
System.out.println("For " + members + " members: ");
while (members-- > 1) {
System.out.print(it.next() + " kills " + it.next() + ", ");
it.remove();
}
System.out.println("\n The survivor: " + it.next());
}
</code></pre>
<p>}</p>
| [] | [
{
"body": "<p>The documentation for <code>forEachRemaining</code> states that the behavior is equivalent to</p>\n\n<pre><code>while (hasNext())\n action.accept(next());\n</code></pre>\n\n<p>so why not just put that there?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"Cr... | {
"AcceptedAnswerId": "209755",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T13:27:46.633",
"Id": "207657",
"Score": "0",
"Tags": [
"java",
"linked-list",
"circular-list"
],
"Title": "Josephus Problem with cyclic iterator"
} | 207657 |
<p>I have a file as content a list of dictionaries (Around 75000). For instance, this is an example of first line I got when reading the file (value for v): </p>
<blockquote>
<pre><code>{
"id": 1,
"name": "Explosives",
"category_id": 1,
"average_price": 294,
"is_rare": 0,
"max_buy_price": 755,
"max_sell_price": 1774,
"min_buy_price": 99,
"min_sell_price": 18,
"buy_price_lower_average": 176,
"sell_price_upper_average": 924,
"is_non_marketable": 0,
"ed_id": 128049204,
"category": {
"id": 1,
"name": "Chemicals"
}
}
</code></pre>
</blockquote>
<p>My actual working code is :</p>
<pre><code>for v in d:
commodities_reference = []
for k, g in v.items():
if isinstance(g, dict):
dict1 = g
my_value1 = dict1.get("id")
my_value2 = dict1.get("name")
for s, i in v.items():
if not isinstance(i, dict):
commodities_reference.append(i)
commodities_reference.append(my_value1)
commodities_reference.append(my_value2)
</code></pre>
<p>Output wanted = All the values in same list in the same order for doing a SQL INSERT Statement afterwards (Meaning values from the nested dict must be also at the end.)</p>
<pre><code>[1, 'Explosives', 1, 294, 0, 755, 1774, 99, 18, 176, 924, 0, 128049204, 1, 'Chemicals']
</code></pre>
<p>From a performance perspective, with SQLITE3/python 3.7, it is a catastrophe. I am looking for some advices in order to make it more efficient. I am thinking about using <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.executemany" rel="nofollow noreferrer"><code>executemany</code></a> statement but it seems it takes tuple instead of list.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T14:12:55.300",
"Id": "400823",
"Score": "1",
"body": "I'm not sure I fully understand the requirement (same order as what?) - could you show the actual expected output from the given input? That would make it clearer."
},
{
... | [
{
"body": "<p>Currently you iterate over each dictionary twice. You can do it in one pass:</p>\n\n<pre><code>for v in d:\n commodities_reference = []\n for k, g in v.items():\n if isinstance(g, dict):\n commodities_reference.append(g[\"id\"])\n commodities_reference.append(g[\... | {
"AcceptedAnswerId": "207732",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T14:01:56.867",
"Id": "207659",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Read list of dictionaries with nested dictionaries"
} | 207659 |
<p>Gallery will be displayed in RecyclerView. User can select some images and delete it with one button.</p>
<p>It all works, but i think I have bad code, because I don't use some instruments (like fragment). I just don't understand what and where I need it exactly. </p>
<p>So I need help with readability (code style) and refactoring.</p>
<p><a href="https://github.com/KirstenLy/GalleryApp/tree/b3219910ed7fc88d4acb0d56c2b96301d5ac9a8f" rel="nofollow noreferrer">https://github.com/KirstenLy/GalleryApp</a></p>
<p>Some points about code:</p>
<p><strong>MainActivity</strong> - Just logo and autoswitch to the next activity after two seconds.</p>
<p><strong>GalleryActivity</strong> - Here i show the gallery and write code to take and save photo.</p>
<ul>
<li><p><strong>onCreate</strong>. I take a path to directory with images, and if it's ok, i create <code>File[] files</code> with images, then create <code>ArrayList<String> imageNamesList</code> which contains files names and put it into RecyclerView adapter to display.</p>
<ol>
<li>I use this library to animate my Recycler: <a href="https://github.com/wasabeef/recyclerview-animators" rel="nofollow noreferrer">https://github.com/wasabeef/recyclerview-animators</a>. I used their methods and classes on 138 - 153 lines.</li>
</ol></li>
<li><p><strong>onActivityResult</strong></p>
<ol>
<li><code>tempFile.length() == 0</code> i used it, because if user activate camera and then press "back", photo will be created in <code>tempFile</code> but it will be empty, and RecyclerView will display empty cell with border.</li>
</ol></li>
<li><p><strong>Methods</strong></p>
<ol>
<li><code>deleteAllPhoto</code> method. Method deleted all selected photo. I returned my own class <code>DellAllPhotoResult</code> and then work with it. Method count succsess and failed results.</li>
<li><code>takeAPhoto</code> method. I use this to write it: <a href="https://developer.android.com/training/camera/photobasics" rel="nofollow noreferrer">https://developer.android.com/training/camera/photobasics</a></li>
</ol></li>
</ul>
<p><strong>RVAdapter</strong> - my own adapter, extends RecyclerView.Adapter. He take <code>ArrayList<String> imageNamesList</code>, and create <code>file</code> and cell for every name on the list.</p>
<ul>
<li><strong>onBindViewHolder</strong>. Here i work with cell content. I used Glide library to avoid OOM when 5+ images displayed.
<ol>
<li><code>viewHolder.img.setOnClickListener</code>. RecyclerView widget placed inside invisible layout named <code>scaledImg</code>. When user click on image, i make this layout visible and put user's image in it. This way i "scaled" image.</li>
</ol></li>
</ul>
<p><strong>Functions</strong> - class with simple functions.</p>
<ol>
<li><code>prepareData</code>. This method take <code>file[]</code> array and return <code>Arraylist<String></code> with them names. Check on <code>.jpg</code> is about to avoid sutiation when user put file with another format in directory.</li>
</ol>
<p>Another things are simple, in my opinion. But i can write explanation of any part, if someone need it.</p>
<p><strong>MainActivity</strong></p>
<pre><code>public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable = new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this, GalleryActivity.class);
startActivity(intent);
finish();
}
};
Handler handler = new Handler();
handler.postDelayed(runnable, 2000);
}
}
</code></pre>
<p><strong>GalleryActivity</strong></p>
<pre><code>public class GalleryActivity extends AppCompatActivity {
final int REQUEST_TAKE_PHOTO = 1;
private File tempFile;
private void takeAPhoto(String PATH, int REQUEST_TAKE_PHOTO) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
tempFile = Functions.createImageFile(PATH);
} catch (IOException ex) {
Toast.makeText(getApplicationContext(), "Denied. Create file error.", Toast.LENGTH_LONG).show();
return;
}
if (tempFile != null) {
Uri photoURI = FileProvider.getUriForFile(getApplicationContext(),
"com.kirsten.testapps.fileprovider",
tempFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} else {
Toast.makeText(getApplicationContext(), "Denied. Can't find a camera.", Toast.LENGTH_LONG).show();
}
}
private DellAllPhotoResult deleteAllPhoto(RVAdapter adapter, ArrayList<String> imageNames, String PATH) {
boolean[] isSelected = adapter.getIsSelected();
boolean noErrorResult = true;
int successDeletedFileCounter = 0;
int failedDeletedFileCounter = 0;
StringBuilder pathString = new StringBuilder();
for (int i = 0; i < imageNames.size(); i++) {
if (isSelected[i]) {
tempFile = new File(pathString.
append(PATH).
append("/").
append(imageNames.get(i)).
toString());
if (tempFile.delete() && !tempFile.exists()) {
successDeletedFileCounter++;
} else {
failedDeletedFileCounter++;
}
}
}
if (failedDeletedFileCounter > 0) {
noErrorResult = false;
}
return new DellAllPhotoResult(noErrorResult, successDeletedFileCounter, failedDeletedFileCounter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && tempFile != null) {
if (tempFile.length() == 0) {
if (!tempFile.delete()) {
Toast.makeText(this, "Unknown error, app will be closed", Toast.LENGTH_LONG).show();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
recreate();
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton(R.string.yes_dialog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton(R.string.no_dialog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
final String PATH;
try {
PATH = getExternalFilesDir(DIRECTORY_PICTURES).getPath();
} catch (NullPointerException ex) {
Toast.makeText(getApplicationContext(), "Unknown error. Can't get access to app directory.", Toast.LENGTH_LONG).show();
return;
}
File directory = new File(PATH);
File[] files = directory.listFiles();
if (files == null){
Toast.makeText(getApplicationContext(), "Unknown error. App directory is not exist.", Toast.LENGTH_LONG).show();
return;
}
final RecyclerView recyclerView = findViewById(R.id.image_gallery);
recyclerView.setItemAnimator(new SlideInLeftAnimator());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.getItemAnimator().setMoveDuration(1000);
recyclerView.getItemAnimator().setRemoveDuration(1000);
recyclerView.getItemAnimator().setAddDuration(1000);
final ArrayList<String> imageNamesList = Functions.prepareData(files);
final ImageView scaledImage = findViewById(R.id.scaled_image);
final RVAdapter adapter = new RVAdapter(getApplicationContext(), imageNamesList, PATH, scaledImage);
ScaleInAnimationAdapter alphaAdapter = new ScaleInAnimationAdapter(adapter);
alphaAdapter.setFirstOnly(false);
alphaAdapter.setDuration(500);
recyclerView.setAdapter(alphaAdapter);
final Button takePhotoButton = findViewById(R.id.take_photo_button);
takePhotoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takeAPhoto(PATH, REQUEST_TAKE_PHOTO);
}
});
final Button delAllPhotoButton = findViewById(R.id.delete_all_photo_button);
delAllPhotoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean[] isSelected = adapter.getIsSelected();
boolean isSomethingSelected = Functions.checkArray(isSelected);
if (!isSomethingSelected) {
Toast.makeText(getApplicationContext(), "No one image selected", Toast.LENGTH_LONG).show();
return;
}
DellAllPhotoResult result = deleteAllPhoto(adapter, imageNamesList, PATH);
if (result.isResult()) {
Toast.makeText(getApplicationContext(), new StringBuilder().
append("Done.").
append(result.getSuccessResults()).
append(" files deleted.").
toString(), Toast.LENGTH_LONG).show();
recreate();
} else {
Toast.makeText(getApplicationContext(), new StringBuilder().
append("Done. ").
append("Unknown error.").
append(result.getSuccessResults()).
append(" files deleted.").
append(result.getFailedResults()).
append(" files are not.").toString(), Toast.LENGTH_LONG).show();
recreate();
}
}
});
}
}
</code></pre>
<p><strong>RVAdapter</strong></p>
<pre><code>public class RVAdapter extends RecyclerView.Adapter<RVAdapter.ViewHolder> {
private ArrayList<String> imageNameList;
private Context context;
private final String PATH;
private ImageView scaledImg;
private static boolean[] isSelected;
private boolean isScaled = false;
public RVAdapter(Context context, ArrayList<String> imageNameList, String path, ImageView scaledImg) {
this.imageNameList = imageNameList;
this.context = context;
this.PATH = path;
this.scaledImg = scaledImg;
isSelected = new boolean[imageNameList.size()];
}
private void deleteImageFromListWithRefresh(final RVAdapter.ViewHolder viewHolder, int i) {
imageNameList.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, imageNameList.size());
viewHolder.cellLayout.removeAllViews();
viewHolder.cellLayout.refreshDrawableState();
}
public boolean[] getIsSelected() {
return isSelected;
}
@Override
public RVAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final RVAdapter.ViewHolder viewHolder, final int i) {
final File image = new File(new StringBuilder().
append(PATH).
append("/").
append(imageNameList.get(i)).
toString());
Glide.with(context).load(image).into(viewHolder.img);
viewHolder.filename.setText(imageNameList.get(i));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isSelected[i]) {
isSelected[i] = !isSelected[i];
viewHolder.cellLayout.setBackgroundColor(context.getResources().getColor(R.color.colorCellActive));
viewHolder.filename.setTextColor(Color.BLACK);
} else {
isSelected[i] = !isSelected[i];
viewHolder.cellLayout.setBackgroundColor(Color.TRANSPARENT);
viewHolder.filename.setTextColor(Color.WHITE);
}
}
});
viewHolder.img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isScaled) {
scaledImg.setImageURI(Uri.fromFile(image));
scaledImg.setVisibility(View.VISIBLE);
isScaled = !isScaled;
}
}
});
scaledImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scaledImg.setVisibility(View.INVISIBLE);
isScaled = !isScaled;
}
});
viewHolder.delButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isDeleted = image.delete();
if (isDeleted) {
Toast.makeText(context, "Done.", Toast.LENGTH_LONG).show();
deleteImageFromListWithRefresh(viewHolder, i);
} else if (image.exists()) {
Toast.makeText(context, "Unknown error. File was not deleted.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Unknown error. Gallery refresh started...", Toast.LENGTH_LONG).show();
deleteImageFromListWithRefresh(viewHolder, i);
}
}
});
}
@Override
public int getItemCount() {
return imageNameList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView filename;
private ImageView img;
private Button delButton;
private LinearLayout cellLayout;
ViewHolder(View view) {
super(view);
filename = view.findViewById(R.id.filename);
img = view.findViewById(R.id.img);
delButton = view.findViewById(R.id.delete_button);
cellLayout = view.findViewById(R.id.cell);
}
}
}
</code></pre>
<p><strong>Functions</strong></p>
<pre><code>public class Functions {
public static boolean checkArray(boolean[] checked) {
for (boolean b : checked) {
if (b) {
return true;
}
}
return false;
}
public static ArrayList<String> prepareData(File[] files) {
if (files == null) {
return null;
}
ArrayList<String> imageList = new ArrayList<>();
for (File file : files) {
if (!file.getName().endsWith(".jpg")) {
continue;
}
imageList.add(file.getName());
}
return imageList;
}
public static File createImageFile(String path) throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
return File.createTempFile(imageFileName, ".jpg", new File(path));
}
}
</code></pre>
<p><strong>DelAllPhotoResult</strong></p>
<pre><code>public class DellAllPhotoResult {
private final boolean result;
private final int successResults;
private final int failedResults;
public DellAllPhotoResult(boolean result, int sucsessResults, int failedResults) {
this.result = result;
this.successResults = sucsessResults;
this.failedResults = failedResults;
}
public boolean isResult() {
return result;
}
public int getSuccessResults() {
return successResults;
}
public int getFailedResults() {
return failedResults;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-16T12:10:27.217",
"Id": "401172",
"Score": "0",
"body": "What's wrong with my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-18T05:24:30.473",
"Id": "401429",
"Score": "0",
"body": "I... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T15:01:43.960",
"Id": "207660",
"Score": "1",
"Tags": [
"java",
"beginner",
"android",
"image"
],
"Title": "Android app to take a photos and show them in a gallery"
} | 207660 |
<p>I'm a junior programmer, and I've only been in the industry a couple of months. </p>
<p>One of the aspects that I struggle with most is testing my code. I can write tests, and I can ensure that my code passes the tests successfully. However the issues I have relates to whether or not I am doing my testing correctly. At the moment my testing strategy seems to consist of checking that anything that can go wrong with my code doesn't actually go wrong. So I end up testing for many different eventualities e.g. input is valid, input is null, input is incorrect etc.</p>
<p>Today one of my mentors showed me his style of testing, which consists of BDD oriented testing. Although I can see where the advantages lies, I feel like that with his style of testing I am writing a lot more code to cover the same area.</p>
<p>Today I've written a number of tests in both my normal style and the BDD style. I'd really appreciate it if someone could have a look through two of my test classes and tell me which is the more effective testing style, and if I should ditch the way I usually test. </p>
<p>This code is testing a custom built JSON schema generator. First a JSON file is fed into the program and a JSON schema document is created. Below one of the classes that is used in the program <code>SchemaDefinitionPropertyFactory</code> is being tested to ensure correct functionality. For more information please see here: <a href="https://json-schema.org/understanding-json-schema/structuring.html" rel="nofollow noreferrer">https://json-schema.org/understanding-json-schema/structuring.html</a></p>
<p>My style of testing:</p>
<pre><code> private Question _question;
private SchemaDefinitionPropertyFactory _factory;
[SetUp]
public void Setup()
{
_question = new Question
{
Id = 1,
Text = "Question 1",
Type = "text",
Required = "1",
Valid_answers = null,
Conditional_question_id = null,
Conditional_question_answered = null,
Fk_section_id = "1"
};
_factory = new SchemaDefinitionPropertyFactory();
}
[Test]
public void BuildPropertiesList_ValidQuestionInput_ReturnsCorrectListOfPropertyFieldsAndOnlyOneSchemaPropertyInList()
{
List<SchemaProperty> propertyList = _factory.BuildPropertiesList(_question);
List <SchemaPropertyField> propertyFields = propertyList[0].PropertyFields;
Assert.That(propertyFields.Count, Is.EqualTo(2));
Assert.That(propertyFields[0].Name, Is.EqualTo("type"));
Assert.That(propertyFields[0].Value, Is.EqualTo("string"));
Assert.That(propertyFields[1].Name, Is.EqualTo("minLength"));
Assert.That(propertyFields[1].Value, Is.EqualTo("1"));
Assert.That(propertyList.Count, Is.EqualTo(1));
}
[Test]
public void BuildPropertiesList_NonRequiredQuestion_PropertyDoesNotHaveMinimumLength()
{
_question.Required = "0";
List<SchemaProperty> propertyList = _factory.BuildPropertiesList(_question);
List<SchemaPropertyField> propertyFields = propertyList[0].PropertyFields;
Assert.That(propertyFields.Count, Is.EqualTo(1));
Assert.That(propertyFields[0].Name, Is.EqualTo("type"));
Assert.That(propertyFields[0].Value, Is.EqualTo("string"));
}
</code></pre>
<p>BDD Testing style</p>
<pre><code> private List<SchemaProperty> _propertyList;
private List<SchemaPropertyField> _propertyFields;
private Question _question;
protected override void GivenThat()
{
ClassUnderTest = new SchemaDefinitionPropertyFactory();
_question = new Question
{
Id = 1,
Text = "Question 1",
Type = "text",
Required = "1",
Valid_answers = null,
Conditional_question_id = null,
Conditional_question_answered = null,
Fk_section_id = "1"
};
}
protected override void When()
{
_propertyList = ClassUnderTest.BuildPropertiesList(_question);
_propertyFields = _propertyList[0].PropertyFields;
}
[Then]
public void ReturnsCorrectListOfPropertyFields()
{
Assert.That(_propertyFields.Count, Is.EqualTo(2));
Assert.That(_propertyFields[0].Name, Is.EqualTo("type"));
Assert.That(_propertyFields[0].Value, Is.EqualTo("string"));
Assert.That(_propertyFields[1].Name, Is.EqualTo("minLength"));
Assert.That(_propertyFields[1].Value, Is.EqualTo("1"));
}
[Then]
public void ThereIsOnlyOneSchemaPropertyInList()
{
Assert.That(_propertyList.Count, Is.EqualTo(1));
}
[Then]
public void PropertyDoesNotHaveInvalidFields()
{
Assert.That(_propertyFields[0].Name, Is.EqualTo("type"));
Assert.That(_propertyFields[0].Value, Is.EqualTo("string"));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T16:26:23.623",
"Id": "400844",
"Score": "1",
"body": "The first thing that you need to do on on Code Review is to explain what your code is doing so please [edit] your question and describe what you are testing. Then I think it shou... | [
{
"body": "<h3>Your style of testing</h3>\n\n<p>I myself was using your style for a long time... until after several weeks I couldn't make any sense of them anymore. They are testing something, yes, but what and why? Nobody could say that anymore and especially when I wanted to know whether I tested a particula... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T16:08:08.347",
"Id": "207663",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"comparative-review"
],
"Title": "Two different styles of testing a custom JSON schema generator"
} | 207663 |
<p>I'd like to optimize my code and get a better of understanding of how I can perform the task I am doing better. I've only used Perl threads about 3 or 4 times now.</p>
<p>The purpose of my script / code block is to scrape the Pastebin API for every new public paste that appears at regular intervals using a crontab. Then search inside those new pastes for user defined regular expressions such as "google.com." The paste is then saved to a sqlite DB for later viewing and a notification is sent to a listening nodejs bot.</p>
<p>That being said here is my code block I wish to have improved upon:</p>
<pre><code>sub threadCheckKey {
my ($url, $key, @regexs) = @_;
my $fullURL = $url.$key;
my @flaggedRegex = ();
my $date = strftime "%D", localtime;
my @data = ();
my $thread = threads->create(sub {
my $dbConnection = openDB();
open(GET_DATA, "-|", "curl -s " . $fullURL . " -k") or die("$!");
open(WRITE_FILE, ">", $key . ".txt") or die("$!");
while(my $line = <GET_DATA>) {
print WRITE_FILE $line;
foreach my $regex(@regexs) {
if($line =~ m/$regex/) {
if(!(grep(/$regex/, @flaggedRegex))) {
push(@flaggedRegex, $regex);
}
}
}
}
close(WRITE_FILE);
close(GET_DATA);
my $flaggedSize = @flaggedRegex;
if($flaggedSize == 0) {
#Uncomment below for debugging.
#print "No user defined regex found\n";
return;
}
open(READ_FILE, "<", $key . ".txt") or die("$!");
while(my $line = <READ_FILE>) {
push(@data, $line);
}
close(READ_FILE);
my $inputData = join("\r", @data);
my $flaggedReg = join(" | ", @flaggedRegex);
my $updateRow = qq(UPDATE $tables[0] set data = ?, date = ?, regex = ? where pastekey = ?);
my $updateRowPrepare = $dbConnection->prepare($updateRow);
my $executeRowUpdate = $updateRowPrepare->execute($inputData, $date, $flaggedReg, $key);
if($executeRowUpdate < 0) {
print $DBI::errstr;
}
my $msg = qq(**Alert:** New paste found! The paste can be viewed via https://pastebin.com/$key - Regex Trigger: $flaggedReg);
open(SEND_ALERT, "-|", "curl https://localhost:8051/bots/bot_service_id/alert -k --data '{\"text\":\"$msg\"}' -H \"Content-Type: application/json\" -X POST") or die("$!");
close(SEND_ALERT);
$dbConnection->disconnect();
});
if($thread->is_running()) {
sleep(2);
}
if($thread->is_joinable()) {
$thread->join();
}
unlink $key . ".txt";
return;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:14:23.507",
"Id": "416659",
"Score": "0",
"body": "Any specific reason you don't [use scalars](https://perlmaven.com/open-files-in-the-old-way) for file operations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDat... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T16:28:04.367",
"Id": "207665",
"Score": "4",
"Tags": [
"multithreading",
"io",
"perl",
"sqlite",
"curl"
],
"Title": "Perl PasteBin scraper"
} | 207665 |
<p>I have this function which converts a couple of 2D NumPy arrays into strings and then saves them in a text file (<code>grid</code>, <code>quality</code>, <code>roadMap</code>, <code>fireEffectMap</code>, <code>hospitalEffectMap</code>, <code>policeEffectMap</code>, <code>fireMap</code>, <code>densityMap</code>, <code>errorMap</code>, <code>waterMap</code>) as well as a couple of other vars (<code>cash</code>, <code>size</code>), size being 48, but this is long and ugly. Also, I have 3 different strings/lines for a variable, because each of the values in the <code>waterMap</code> var can be 3 characters long, e.g. 0-255, that and density, but the rest are 1 character per "slot" in the 2d array. How do I make this more compact, easier to understand/read and also add more in the future if needed?</p>
<pre><code> def save(saves, seed, cash, grid, quality, roadMap, fireEffectMap, hospitalEffectMap, policeEffectMap, fireMap, densityMap, errorMap, waterMap, size):
print("Saving File...")
currentDir = os.getcwd() #Get current directory
os.chdir('saves') #Set the current dir to saves
newFileName = "Save" + str(len(saves) + 1) + ".simcity" #Set the name of the save to Save + biggest number.simcity
file = open(newFileName, "w") #Open/Create a new file
seedString = ""
for i in range(size):
for j in range(size):
seedString = seedString + str(seed[i, j])
file.write(seedString + "\n")
file.write(str(cash) + "\n") #Store your cash in line 2
gridString = ""
qualityString = ""
roadMapString = ""
fireEffectMapString = ""
hospitalEffectMapString = ""
policeEffectMapString = ""
fireMapString = ""
errorMapString = ""
densityMapStringValue = ""
densityMapString1 = ""
densityMapString2 = ""
waterMapString = ""
waterMapString1 = ""
waterMapString2 = ""
waterMapString3 = ""
for j in range(size):
for i in range(size): #Storing all of the 2d numpy arrays in strings on seperate lines
gridString = gridString + grid[i, j]
qualityString = qualityString + str(quality[i, j])
roadMapString = roadMapString + str(roadMap[i, j])
fireEffectMapString = fireEffectMapString + str(fireEffectMap[i, j])
hospitalEffectMapString = hospitalEffectMapString + str(hospitalEffectMap[i, j])
policeEffectMapString = policeEffectMapString + str(policeEffectMap[i, j])
fireMapString = fireMapString + str(fireMap[i, j])
errorMapString = errorMapString + str(errorMap[i, j])
densityMapStringValue = str(densityMap[i, j])
waterMapStringValue = str(waterMap[i, j])
if len(str(densityMap[i,j])) == 2:
densityMapString1 = densityMapString1 + str(densityMapStringValue[0])
densityMapString2 = densityMapString2 + str(densityMapStringValue[1])
else:
densityMapString1 = densityMapString1 + "0"
densityMapString2 = densityMapString2 + str(densityMapStringValue[0])
if len(str(waterMap[i,j])) == 3:
waterMapString1 = waterMapString1 + str(waterMapStringValue[0])
waterMapString2 = waterMapString2 + str(waterMapStringValue[1])
waterMapString3 = waterMapString3 + str(waterMapStringValue[2])
elif len(str(waterMap[i,j])) == 2:
waterMapString1 = waterMapString1 + "0"
waterMapString2 = waterMapString2 + str(waterMapStringValue[0])
waterMapString3 = waterMapString3 + str(waterMapStringValue[1])
else:
waterMapString1 = waterMapString1 + "0"
waterMapString2 = waterMapString2 + "0"
waterMapString3 = waterMapString3 + str(waterMapStringValue[0])
file.write(gridString + "\n")
file.write(qualityString + "\n")
file.write(roadMapString + "\n")
file.write(fireEffectMapString + "\n")
file.write(hospitalEffectMapString + "\n")
file.write(policeEffectMapString + "\n")
file.write(fireMapString + "\n")
file.write(errorMapString + "\n")
file.write(densityMapString1 + "\n")
file.write(densityMapString2 + "\n")
file.write(waterMapString1 + "\n")
file.write(waterMapString2 + "\n")
file.write(waterMapString3 + "\n")
file.close()
os.chdir(currentDir)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T20:57:20.197",
"Id": "400896",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T18:29:39.960",
"Id": "207671",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"numpy",
"pygame"
],
"Title": "Converting 2D arrays into strings"
} | 207671 |
<p>I need a concurrent data structure with the following properties:</p>
<ul>
<li>Low overhead for enumeration</li>
<li>Insert only at end.</li>
<li>Removal from any point.</li>
<li>Enumeration should be safe with concurrent writing</li>
<li>Enumeration does not require the list to be in a constant state</li>
<li>Not a problem if I enumerate over removed items</li>
</ul>
<p>I have designed the following linked list class which should meet my requirements. </p>
<pre><code>using System.Collections;
using System.Collections.Generic;
internal class ConcurrentLinkedList<T> : IEnumerable<Node<T>> {
private readonly BaseNode<T> _root;
private BaseNode<T> _end;
public ConcurrentLinkedList() {
_end = _root = new BaseNode<T>();
}
public Node<T> Insert(T value) {
var node = new Node<T>(value);
lock (node) {
lock (_end) {
node.Previous = _end;
_end = _end.Next = node;
return node;
}
}
}
public void Remove(Node<T> node) {
lock (node.Previous) {
lock (node) {
if (node.Next == null) {
if (node.Previous.Next != node) return;
node.Previous.Next = null;
if (_end == node) _end = node.Previous;
} else {
lock (node.Next) {
if (node.Previous.Next == node) node.Previous.Next = node.Next;
if (node.Next.Previous == node) node.Next.Previous = node.Previous;
}
}
}
}
}
public IEnumerator<Node<T>> GetEnumerator() {
for (var current = _root.Next; current != null; current = current.Next) {
yield return current;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
internal class BaseNode<T> {
internal volatile Node<T> Next;
}
internal class Node<T> : BaseNode<T> {
internal BaseNode<T> Previous;
public T Value { get; }
public Node(T value) {
Value = value;
}
}
</code></pre>
<p>I am aware the calls is vary easy to misuse but as it is only for internal use i am not concerned about this. I am considering making the all the class private subclass to ensure that there is no accidental misuse.</p>
<p>In the code all the writing is in a lock but there are shared volatile which are read out of lock. Apart from the possibility of enumerating deleted nodes, is there any other danger with this?</p>
<p>For the locking, I lock no all the node being changed. This should allow other parts of the list to be concurrency modified, the list can get long. Is this sufficient?</p>
<p>To avoid deadlock I always lock from the lowest node to the last.</p>
<p>Is the provided locking sufficient to protect the <code>_end</code> field? I believe that according to the logic used the current <code>_end</code> will always be locked when changing the value of <code>_end</code>. Is this sufficient? </p>
<p>Is this code trying to be too clever and would it better to either:</p>
<ul>
<li>have one write lock and continue using the volatile for reading.</li>
<li>use a standard <code>ReadWriteLock</code> for the whole list.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T04:07:35.543",
"Id": "400925",
"Score": "0",
"body": "Initially `_end` points to the same object as `_root`. `_end.Next` is assigned to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T06:54:33.987",
... | [
{
"body": "<h1>EDIT: Possible race condition</h1>\n\n<p>I would not accept this code to production without proper documentation containing good proof, that it works as expected. <code>lock (node.Previous)</code> could get interrupted by another <code>Remove</code> changing <code>node.Previous</code> after it wa... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T19:39:55.830",
"Id": "207677",
"Score": "6",
"Tags": [
"c#",
".net",
"linked-list",
"concurrency"
],
"Title": "Specialized ConcurrentLinkedList"
} | 207677 |
<p>Actually my implementation is not working very well for big areas (I don't know why) <a href="https://stackoverflow.com/questions/53307270/flood-filling-algorithm-doesnt-work-as-expected-it-creates-gaps-between-pixel">I already created a question on Stackoverflow</a>. But I figured out how to do it to work with an O(n) implementation (you can see what I mean <a href="https://stackoverflow.com/a/52953249/3286975">here</a> (see the fiddle I attached)).</p>
<p>But for some reason as I said it is not working very well on big areas.</p>
<pre><code>/// <summary>
/// Floods the fill.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="target">The target.</param>
/// <param name="replacement">The replacement.</param>
public static void FloodFill<T>(this T[] source, int x, int y, int width, int height, T target, T replacement)
where T : IEquatable<T>
{
int i;
source.FloodFill(x, y, width, height, target, replacement, out i);
}
/// <summary>
/// Floods the array following Flood Fill algorithm
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="target">The target to replace.</param>
/// <param name="replacement">The replacement.</param>
/// <param name="i">The i.</param>
// This was generic
public static void FloodFill<T>(this T[] source, int x, int y, int width, int height, T target, T replacement, out int i)
where T : IEquatable<T>
{
i = 0;
HashSet<int> queue = new HashSet<int>();
queue.Add(P(x, y, width, height));
while (queue.Count > 0)
{
int _i = queue.First(),
_x = _i % width,
_y = _i / width;
queue.Remove(_i);
if (source[_i].Equals(target))
source[_i] = replacement;
for (int offsetX = -1; offsetX < 2; offsetX++)
for (int offsetY = -1; offsetY < 2; offsetY++)
{
// do not check origin or diagonal neighbours
if (offsetX == 0 && offsetY == 0 || offsetX == offsetY || offsetX == -offsetY || -offsetX == offsetY)
continue;
int targetIndex = Pn(_x + offsetX, _y + offsetY, width); // This is already inverted that's why we don't use F.P(...)
int _tx = targetIndex % width,
_ty = targetIndex / width;
// skip out of bounds point
if (_tx < 0 || _ty < 0 || _tx >= width || _ty >= height)
continue;
if (!queue.Contains(targetIndex) && source[targetIndex].Equals(target))
{
queue.Add(targetIndex);
if (Monitor.IsEntered(i))
++i;
else
Interlocked.Increment(ref i);
}
}
if (i > 100000)
break;
}
}
</code></pre>
<p>My main concerns are the following:</p>
<ul>
<li>I don't know if there is a better way to debug how many iterations has the algorithm done (and if I'm getting them correctly).</li>
<li>I don't like to use <code>Monitor.IsEntered</code> (I'm not sure if this is needed).</li>
<li>I would like to speed-up it, but I don't know how (I think this is slow) (you can compare it with ms-paint to see differences, I know it's written on C++, but... I would like to get a significant perfomance).</li>
<li>Also, I don't know if there is a better way to do it (to avoid unnecesary memory consumption).</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T22:40:15.287",
"Id": "400904",
"Score": "2",
"body": "What is P in queue.Add(P(x, y, width, height)), and Pn later?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T11:38:10.690",
"Id": "400963",
... | [
{
"body": "<h2><code>Monitor.IsEntered</code></h2>\n\n<p>This call basically makes no sense. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.monitor.isentered?view=netframework-4.7.2\" rel=\"noreferrer\"><code>Monitor.IsEntered</code></a> is used for coordination/mutual exclusion between ... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T20:06:59.500",
"Id": "207678",
"Score": "5",
"Tags": [
"c#",
"performance",
"algorithm"
],
"Title": "Optimizing Floodfill algorithm implementation as much as possible"
} | 207678 |
<p>I would like to solve a problem from <a href="https://stackoverflow.com/questions/44983929/proving-that-a-particular-matrix-exists?noredirect=1&lq=1">https://stackoverflow.com/questions/44983929/proving-that-a-particular-matrix-exists?noredirect=1&lq=1</a></p>
<p>I found this problem in a programming forum Ohjelmointiputka:</p>
<pre><code>https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=ahdruu and
https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=ahdruu2
</code></pre>
<p>Somebody said that there is a solution found by a computer, but I was unable to find a proof.</p>
<p>Prove that there is a matrix with 117 elements containing the digits such that one can read the squares of the numbers 1, 2, ..., 100.</p>
<p>Here read means that you fix the starting position and direction (8 possibilities) and then go in that direction, concatenating the numbers. For example, if you can find for example the digits 1,0,0,0,0,4 consecutively, you have found the integer 100004, which contains the square numbers of 1, 2, 10, 100 and 20, since you can read off 1, 4, 100, 10000, and 400 (reversed) from that sequence.</p>
<p>But there are so many numbers to be found (100 square numbers, to be precise, or 81 if you remove those that are contained in another square number with total 312 digits) and so few integers in a matrix that you have to put all those square numbers so densely that finding such a matrix is difficult, at least for me.</p>
<p>I found that if there is such a matrix <span class="math-container">\$m \times n\$</span>, we may assume without loss of generality that <span class="math-container">\$m \le n\$</span>. Therefore, the matrix must be of the type 1x117, 3x39 or 9x13. But what kind of algorithm will find the matrix?</p>
<p>I have managed to do the program that checks if numbers to be added can be put on the board. But how can I implemented the searching algorithm?</p>
<p>This looks a hard problem but one has solved the case 121 for 11x11 grid in <a href="https://stackoverflow.com/questions/3382859/solving-a-recreational-square-packing-problem?noredirect=1&lq=1">https://stackoverflow.com/questions/3382859/solving-a-recreational-square-packing-problem?noredirect=1&lq=1</a> .</p>
<p>I was unable to modify this to the 9x13 case.</p>
<p>But can how one can write a code that can be used for any size rectangle?</p>
<p>I was able to write the code for 11x11 case as follows. But is this easy to generalized? </p>
<pre><code># Coordinates like in unit circle with 45 degree steps.
# means right, 1*45 means up right...
def getnumber(matrix, x, y, length, direction):
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, -1, -1, -1, 0, 1, 1, 1]
s = ""
for i in range(length):
try:
s += matrix[y+dy[direction]*i][x+dx[direction]*i]
except IndexError:
break
return s
# This puts number to the board.
def putnumber(matrix, x, y, number, direction,emptychar):
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, -1, -1, -1, 0, 1, 1, 1]
for i in range(len(number)):
if matrix[y+dy[direction]*i][x+dx[direction]*i] not in (number[i],emptychar):
return None
matrix[y+dy[direction]*i][x+dx[direction]*i] = number[i]
return matrix
# This generates all numbers.
def gen_numbers(limit):
numbers = []
i = limit**2
numbers.append(str(i))
tmp = ""
for j in range(limit):
i = (limit-j)**2
if str(i) not in tmp:
if str(i)[::-1] not in tmp:
numbers.append(str(i))
tmp += str(i)+" "
tmp = tmp[0:len(tmp)-1]
numbers = tmp.split(" ")
return numbers
# def get_all_indexes(5,8,"10000",2);
def get_all_indexes(x,y,number,direction):
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, -1, -1, -1, 0, 1, 1, 1]
j = []
for i in range(len(number)):
j.append([x+dx[direction]*i,y+dy[direction]*i])
return j
def get_numbers_near_index(matrix, x, y, length):
j = []
for direction in range(9):
j.append(getnumber(matrix, x, y, length, direction))
# print(j)
j = list(set(j))
return j
# This method prints a matrix.
def printmatrix(Matrix):
if Matrix is not None:
for i in range(w):
print(Matrix[i])
# Creates a grid of width 11 and height 11.
w, h = 11, 11
# Defines what we put if an tem in the grid is empty
emptychar = 'X'
# This is the maximum number of integer whose square we put to the table.
limit = 100
# Create an empty array
Matrix = [[emptychar for y in range(w)] for x in range(h)]
# We put to the location Matrix[put_x][put_y] the number "number" going to the direction.
#
coords = [[5,8,2,100**2],
[3,9,1,99**2],
[0,4,7,98**2],
[3,0,7,97**2],
[0,7,6,96**2],
[0,1,7,95**2],
[4,10,4,94**2],
[3,10,3,93**2],
[4,10,1,92**2],
[2,8,0,91**2],
[7,8,3,90**2],
[8,0,4,89**2],
[2,1,0,88**2],
[9,8,3,87**2],
[10,1,5,86**2],
[3,1,6,85**2],
[8,5,6,84**2],
[0,6,7,83**2],
[10,9,4,82**2],
[6,10,2,81**2],
[6,8,1,80**2],
[7,4,2,79**2],
[1,5,6,78**2],
[5,3,0,77**2],
[5,3,3,76**2],
[8,7,6,75**2],
[10,3,2,74**2],
[10,3,3,73**2],
[6,9,3,72**2],
[5,3,2,71**2],
[7,2,5,70**2],
[4,0,5,69**2],
[7,9,1,68**2],
[3,7,4,67**2],
[10,6,6,66**2],
[2,7,7,65**2],
[4,1,7,64**2],
[9,2,5,63**2],
[9,2,4,62**2],
[10,7,5,61**2],
[2,5,0,60**2],
[2,5,7,59**2],
[7,5,1,58**2],
[9,0,5,57**2],
[9,0,6,56**2],
[7,5,7,55**2],
[0,3,6,54**2],
[3,8,1,53**2],
[3,2,0,52**2],
[3,2,4,51**2],
[2,3,7,50**2],
[3,8,3,49**2],
[7,3,7,48**2],
[7,3,5,47**2],
[4,9,1,46**2],
[6,4,4,45**2],
[10,4,4,44**2],
[5,0,7,43**2],
[10,10,3,42**2],
[10,4,3,41**2],
[6,6,0,40**2],
[7,10,0,39**2],
[0,9,1,38**2],
[9,1,6,37**2],
[0,9,2,36**2],
[1,3,0,35**2],
[0,2,7,34**2],
[6,6,5,33**2],
[1,3,2,32**2],
[0,7,2,31**2],
[6,5,4,30**2],
[7,8,6,29**2],
[1,9,1,28**2],
[2,1,4,27**2],
[2,0,6,26**2],
[3,5,1,25**2],
[8,7,7,24**2],
[2,4,4,23**2],
[3,7,7,22**2],
[2,7,5,21**2],
[10,6,4,20**2],
[2,5,4,19**2],
[3,3,6,16**2],
[0,2,2,14**2]
]
for row in range(0,len(coords)):
# coords = [coords[4*row+0],coords[4*row+1],coords[4*row+2],coords[4*row+3]]
datarow = [str(coords[row][3]),coords[row][0],coords[row][1],coords[row][2]]
Matrix = putnumber(Matrix, datarow[1], datarow[2], datarow[0], datarow[3], emptychar)
printmatrix(Matrix)
nextrow = coords[row]
print((int(nextrow[3]**0.5)-1)**2)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T21:33:53.160",
"Id": "207681",
"Score": "1",
"Tags": [
"python",
"algorithm"
],
"Title": "Filling a matrix with square number digits"
} | 207681 |
<p>I am trying to program the board game <a href="https://www.boardgamegeek.com/boardgame/164928/orleans" rel="nofollow noreferrer">Orleans</a>. I am planning on making a computer player that plays randomly at first. The part of the game that I'm struggling to code elegantly at the moment has to do with the planning of worker placement. I'll try to explain it in a way that doesn't require familiarity with the game. A player can have workers of 6 different types (and 1 wildcard type), and each action space requires some combination of those 6 types to activate. Each action space requires 1-3 workers of different types. I want to develop a list of all the possible action spaces that can be triggered given a player's current collection of workers, and the requirements of each action space. This is with a view to then randomly select from these later.</p>
<p>I have a <code>Player</code> class, which has a dictionary that stores the action spaces a player has access to, and a list of workers that the player has access to. The list of actions can expand as the game progresses, and the number and type of workers can also change.</p>
<pre><code>class Player:
def __init__(self):
self.workers = ["boatman", "farmer", "craftsman", "trader"]
self.action_spaces = {'farmhouse': ActionSpace(["boatman", "craftsman"]),
'village': ActionSpace(["boatman", "craftsman"]),
'university': ActionSpace(["farmer", "craftsman", "trader"]),
'castle': ActionSpace(["boatman", "farmer", "trader"]),
'monastery': ActionSpace(["scholar", "trader"]),
'wagon': ActionSpace(["farmer", "trader", "knight"]),
'ship': ActionSpace(["boatman", "farmer", "knight"]),
'guildhall': ActionSpace(["farmer", "craftsman", "knight"]),
'scriptorium': ActionSpace(["knight", "scholar"]),
'townhall': ActionSpace([])}
</code></pre>
<p>And an action space class that codes the requirements and current workers placed on each action space.</p>
<pre><code>class ActionSpace:
def __init__(self, requirements):
self.requirements = requirements
self.placed_workers = []
</code></pre>
<p>Then I have some very tortuous code that uses that information to produce a list of the possible combinations of action spaces that can be triggered with the player's workers.</p>
<pre><code>def plan_worker_placement(player):
# loop through all action spaces that a player owns and make a list of tuples recording the requirements for each action space. I convert it to a set because I will find the intersection with this set and another later
reqs_of_available_spaces = set([tuple(v.requirements) for k, v in player.action_spaces.items()])
# get a list of workers
workers = [w for w in player.workers]
combos_of_workers = []
# get all possible combinations of workers for groups of size 1-3 workers
for r in range(1, 4):
combos_of_workers.extend(set(combinations(workers, r)))
# narrow down list to those action spaces that are playable given the player's workers
reqs_of_playable_spaces = reqs_of_available_spaces.intersection(combos_of_workers)
# convert back to list of lists
reqs_of_playable_spaces = [list(c) for c in reqs_of_playable_spaces]
combos_of_reqs_of_playable_spaces = []
# can activate 1 or more action space
for r in range(1, len(reqs_of_playable_spaces) + 1):
combos_of_reqs_of_playable_spaces.extend(combinations(reqs_of_playable_spaces, r))
combos_of_reqs_of_playable_spaces = [list(c) for c in combos_of_reqs_of_playable_spaces]
valid_combos_of_reqs_of_playable_spaces = []
for combo in combos_of_reqs_of_playable_spaces:
# flatten out the list
flat_combo = [item for sublist in combo for item in sublist]
# check whether player has enough workers of each type to play that combination of action spaces
if check_valid(flat_combo, followers):
# if the player has enough workers add that combo of action spaces to the list of possibles
valid_combos_of_reqs_of_playable_spaces.append(combo)
valid_combos_of_reqs_of_playable_spaces = [tuple(c) for c in valid_combos_of_reqs_of_playable_spaces]
return convert_reqs_to_spaces(valid_combos_of_reqs_of_playable_spaces)
# function to convert from a list of requirements back to the name of the action space
def convert_reqs_to_spaces(reqs):
converter = {tuple(sorted(["boatman", "craftsman"])): 'village',
tuple(sorted(["boatman", "farmer", "trader"])): 'castle',
tuple(sorted(["farmer", "trader", "knight"])): 'wagon',
tuple(sorted(["boatman", "farmer", "knight"])): 'ship',
tuple(sorted(["farmer", "craftsman", "knight"])): 'guildhall',
tuple(sorted(["knight", "scholar"])): 'scriptorium',
tuple(sorted(["scholar", "trader"])): 'monastery',
tuple(sorted(["farmer", "craftsman", "trader"])): 'university',
tuple(sorted(["boatman", "craftsman"])): 'farmhouse'}
spaces = []
for s in reqs:
spaces.append([converter[tuple(sorted(req))] for req in s])
return spaces
# function to check to whether a player has enough of each type of worker to activate a given set of action space requirements
def check_valid(flat, followers):
c1, c2 = Counter(flat), Counter(followers)
for k, n in c1.items():
if n > c2[k]:
return False
return True
</code></pre>
<p>I don't like the way I am having to convert from lists to sets and back to lists again. It seems there should be a much cleaner way of doing things.</p>
| [] | [
{
"body": "<p>The way you explain it in plain english is similar to a simple, cleaner way to do it in the code :</p>\n\n<blockquote>\n <p>I want to develop a list of all the possible action spaces</p>\n</blockquote>\n\n<p>With some conditional restriction. This is a complete rewrite.\nEnumeration can be done t... | {
"AcceptedAnswerId": "207830",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T21:39:06.767",
"Id": "207682",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"game",
"combinatorics"
],
"Title": "Worker placement in Orleans board game/combinations"
} | 207682 |
<p>The up-to-date code, along some documentation, can be found <a href="https://github.com/plammens/Simplex" rel="nofollow noreferrer">here</a>.</p>
<hr>
<p>We've implemented a version of the <a href="https://en.wikipedia.org/wiki/Simplex_algorithm" rel="nofollow noreferrer">Simplex method</a> for solving linear programming problems. The concerns I have are with the design we adopted, and what would be some refactorings that would improve it overall.</p>
<p>We defined two important global functions, <code>simplex</code> and <code>simplex_core</code>. The former is a wrapper that does a bunch of error checking and then solves phase I and phase II of the simplex method by calling <code>simplex_core</code>. The latter is the actual bare-bones algorithm; it takes the problem data alongside an initial basic feasible solution and iterates until it fins an optimal solution or identifies the problem as unlimited.</p>
<pre><code>"""
~Mathematical Programming~
Simplex implementation.
"""
import numpy as np
from numpy.linalg import inv # Matrix inverse
from numpy.matlib import matrix # Matrix data type
np.set_printoptions(precision=3, threshold=10, edgeitems=4, linewidth=120) # Prettier array printing
epsilon = 10**(-10) # Global truncation threshold
def simplex(A: matrix, b: np.array, c: np.array, rule: int = 0) -> (int, np.array, float, np.array):
"""
Outer "wrapper" for executing the simplex method: phase I and phase II.
:param A: constraint matrix
:param b: independent terms in constraints
:param c: costs vector
:param rule: variable selection rule (e.g. Bland's)
This function prints the outcome of each step to stdout.
"""
m, n = A.shape[0], A.shape[1] # no. of rows, columns of A, respectively
"""Error-checking"""
if n < m:
raise ValueError("Incompatible dimensions "
"(no. of variables : {} > {} : no.of constraints".format(n, m))
if b.shape != (m,):
raise ValueError("Incompatible dimensions: c_j has shape {}, expected {}.".format(b.shape, (m,)))
if c.shape != (n,):
raise ValueError("Incompatible dimensions: c has shape {}, expected {}.".format(c.shape, (n,)))
"Check full rank matrix"
if not np.linalg.matrix_rank(A) == m:
# Remove ld rows:
A = A[[i for i in range(m) if not np.array_equal(np.linalg.qr(A)[1][i, :], np.zeros(n))], :]
m = A.shape[0] # Update no. of rows
"""Phase I setup"""
A[[i for i in range(m) if b[i] < 0]] *= -1 # Change sign of constraints
b = np.abs(b) # Idem
A_I = matrix(np.concatenate((A, np.identity(m)), axis=1)) # Phase I constraint matrix
x_I = np.concatenate((np.zeros(n), b)) # Phase I variable vector
c_I = np.concatenate((np.zeros(n), np.ones(m))) # Phase I c_j vector
basic_I = set(range(n, n + m)) # Phase I basic variable set
"""Phase I execution"""
print("Executing phase I...")
ext_I, x_init, basic_init, z_I, _, it_I = simplex_core(A_I, c_I, x_I, basic_I, rule)
# ^ Exit code, initial BFS, basis, z_I, d (not needed) and no. of iterations
print("Phase I terminated.")
assert ext_I == 0 # assert that phase I has an optimal solution (and is not unlimited)
if z_I > 0:
print("\n")
print_boxed("Unfeasible problem (z_I = {:.6g} > 0).".format(z_I))
print("{} iterations in phase I.".format(it_I), end='\n\n')
return 2, None, None, None
if any(j not in range(n) for j in basic_init):
# If some artificial variable is in the basis for the initial BFS, exit:
raise NotImplementedError("Artificial variables in basis")
x_init = x_init[:n] # Get initial BFS for original problem (without artificial vars.)
print("Found initial BFS at x = \n{}.\n".format(x_init))
"""Phase II execution"""
print("Executing phase II...")
ext, x, basic, z, d, it_II = simplex_core(A, c, x_init, basic_init, rule)
print("Phase II terminated.\n")
if ext == 0:
print_boxed("Found optimal solution at x =\n{}.\n\n".format(x) +
"Basic indexes: {}\n".format(basic) +
"Nonbasic indexes: {}\n\n".format(set(range(n)) - basic) +
"Optimal cost: {}.".format(z))
elif ext == 1:
print_boxed("Unlimited problem. Found feasible ray d =\n{}\nfrom x =\n{}.".format(d, x))
print("{} iterations in phase I, {} iterations in phase II ({} total).".format(it_I, it_II, it_I + it_II),
end='\n\n')
return ext, x, z, d
def simplex_core(A: matrix, c: np.array, x: np.array, basic: set, rule: int = 0) \
-> (int, np.array, set, float, np.array):
"""
This function executes the simplex algorithm iteratively until it
terminates. It is the core function of this project.
:param A: constraint matrix
:param c: costs vector
:param x: initial BFS
:param basic: initial basic index set
:param rule: variable selection rule (e.g. Bland's)
:return: a tuple consisting of the exit code, the value of x, basic index set,
optimal cost (if optimum has been found), and BFD corresponding to
feasible ray (if unlimited problem)
"""
m, n = A.shape[0], A.shape[1] # no. of rows, columns of A, respectively
assert c.shape == (n,) and x.shape == (n,) # Make sure dimensions match
assert isinstance(basic, set) and len(basic) == m and \
all(i in range(n) for i in basic) # Make sure that basic is a valid base
B, N = list(basic), set(range(n)) - basic # Basic /nonbasic index lists
del basic # Let's work in hygienic conditions
B_inv = inv(A[:, B]) # Calculate inverse of basic matrix (`A[:, B]`)
z = np.dot(c, x) # Value of obj. function
it = 1 # Iteration number
while it <= 500: # Ensure procedure terminates (for the min reduced cost rule)
r_q, q, p, theta, d = None, None, None, None, None # Some cleanup
print("\tIteration no. {}:".format(it), end='')
"""Optimality test"""
prices = c[B] * B_inv # Store product for efficiency
if rule == 0: # Bland rule
optimum = True
for q in N: # Read in lexicographical index order
r_q = np.asscalar(c[q] - prices * A[:, q])
if r_q < 0:
optimum = False
break # The loop is exited with the first negative r.c.
elif rule == 1: # Minimal reduced cost rule
r_q, q = min([(np.asscalar(c[q] - prices * A[:, q]), q) for q in N],
key=(lambda tup: tup[0]))
optimum = (r_q >= 0)
else:
raise ValueError("Invalid pivoting rule")
if optimum:
print("\tfound optimum")
return 0, x, set(B), z, None, it # Found optimal solution
"""Feasible basic direction"""
d = np.zeros(n)
for i in range(m):
d[B[i]] = trunc(np.asscalar(-B_inv[i, :] * A[:, q]))
d[q] = 1
"""Maximum step length"""
# List of tuples of "candidate" theta an corresponding index in basic list:
neg = [(-x[B[i]] / d[B[i]], i) for i in range(m) if d[B[i]] < 0]
if len(neg) == 0:
print("\tidentified unlimited problem")
return 1, x, set(B), None, d, it # Flag problem as unlimited and return ray
# Get theta and index (in basis) of exiting basic variable:
theta, p = min(neg, key=(lambda tup: tup[0]))
"""Variable updates"""
x = np.array([trunc(var) for var in (x + theta * d)]) # Update all variables
assert x[B[p]] == 0
z = trunc(z + theta * r_q) # Update obj. function value
# Update inverse:
for i in set(range(m)) - {p}:
B_inv[i, :] -= d[B[i]]/d[B[p]] * B_inv[p, :]
B_inv[p, :] /= -d[B[p]]
N = N - {q} | {B[p]} # Update nonbasic index set
B[p] = q # Update basic index list
"""Print status update"""
print(
"\tq = {:>2} \trq = {:>9.2f} \tB[p] = {:>2d} \ttheta* = {:>5.4f} \tz = {:<9.2f}"
.format(q + 1, r_q, B[p] + 1, theta, z)
)
it += 1
# If loop goes over max iterations (500):
raise TimeoutError("Iterations maxed out (probably due to an endless loop)")
def print_boxed(msg: str) -> None:
"""
Utility for printing pretty boxes.
:param msg: message to be printed
"""
lines = msg.splitlines()
max_len = max(len(line) for line in lines)
if max_len > 100:
raise ValueError("Overfull box")
print('-' * (max_len + 4))
for line in lines:
print('| ' + line + ' ' * (max_len - len(line)) + ' |')
print('-' * (max_len + 4))
def trunc(x: float) -> float:
"""
Returns 0 if x is smaller (in absolute value) than a certain global constant.
"""
return x if abs(x) >= epsilon else 0
</code></pre>
<p>My main concern is that the <code>simplex_core</code> function is a pretty large chunk of code, and most of it is just a big loop. So, would it be wiser to break it up in smaller methods? If so, should they be local or global? I don't see it as an obvious thing to do because each "part" is executed only once, so what would be the advantage of defining a local function?</p>
<p>On the other hand, should <code>simplex_core</code> be a local function of <code>simplex</code>? The main reason I made it global is because the name of the parameters would overshadow the parameters of <code>simplex</code>, and I need those parameters (instead of just using <code>nonlocal</code> variables) due to the distinctness of phase I and phase II.</p>
<p>Finally, my other concern is performance. Since I am a relative beginner, it is hard for me to spot any subtle (or not so subtle) bottlenecks in the code that could be avoided.</p>
<h2>Usage example</h2>
<p>Consider the following linear programming problem (in <a href="https://en.wikipedia.org/wiki/Linear_programming#Augmented_form_(slack_form)" rel="nofollow noreferrer">standard form</a>):</p>
<p><span class="math-container">$$
\begin{cases}\begin{aligned}\min &&&& -x_1 &&-x_2\\ \text{s.t.} &&&& 3x_1 &&+2x_2 &&+x_3 && && = 4\\ &&&& && x_2 && &&+x_4 && = 3\\ \\ &&&& x_1,&&x_2,&&x_3,&&x_4 &&\ge 0\\ \end{aligned}\end{cases}
$$</span></p>
<p>To solve this problem from the Python console, I would write</p>
<pre><code>>>> import numpy as np
>>> from simplex import simplex
>>> A = np.matrix([[3, 2, 1, 0], [0, 1, 0, 1]])
>>> b = np.array([4, 3])
>>> c = np.array([-1, -1, 0, 0])
>>> simplex(A, b, c)
</code></pre>
<p>The output would be:</p>
<pre class="lang-none prettyprint-override"><code>Executing phase I...
Iteration no. 1: q = 1 rq = -3.00 B[p] = 1 theta* = 1.3333 z = 3.00
Iteration no. 2: q = 2 rq = -1.00 B[p] = 2 theta* = 2.0000 z = 1.00
Iteration no. 3: q = 4 rq = -1.00 B[p] = 4 theta* = 1.0000 z = 0.00
Iteration no. 4: found optimum
Phase I terminated.
Found initial BFS at x =
[0. 2. 0. 1.].
Executing phase II...
Iteration no. 1: found optimum
Phase II terminated.
---------------------------------
| Found optimal solution at x = |
| [0. 2. 0. 1.]. |
| |
| Basic indices: {1, 3} |
| Nonbasic indices: {0, 2} |
| |
| Optimal cost: -2.0. |
---------------------------------
4 iterations in phase I, 1 iterations in phase II (5 total).
(0, array([0., 2., 0., 1.]), -2.0, None)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T23:35:51.367",
"Id": "400909",
"Score": "0",
"body": "To assist reviewers, could you include an example of how to call your code for a simple scenario with, say, three variables and a couple of constraints?"
}
] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Basically, wherever you have a comment you should consider renaming or encapsulating to avoid the need for that comment. For example:\n\n<ul>\n<li>Rename <code>A</code> to something like <code>constraint_matrix</code> or <code>constraints</code>.</li>\n<li>Rename... | {
"AcceptedAnswerId": "207684",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T22:12:47.620",
"Id": "207683",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"numpy"
],
"Title": "Simplex method (linear programming) implementation"
} | 207683 |
<p>I had searched for a solution to <code>mvn clean install</code> on my changed projects after a <code>git pull</code>. I even asked a question over at <a href="https://stackoverflow.com/questions/53291073/partial-clean-install-with-maven-after-git-merge-pull">SO</a> about the same thing. The answer I got pointed me into creating my own script to achieve what I wanted to accomplish. So I went, I saw, and I conquered the script that I wanted. However, it is probably not efficient, and could use refactoring. I am new to bash scripting and learned a bit while doing this.</p>
<p>The structure I was targeting is a Maven POM Project. That project contains several sub-POM Projects, which in turn contain Maven Java Projects.</p>
<p>Example Structure:</p>
<pre><code>-Parent
|-Sub_Parent_A
|-Child_1
|-Child_2
|-Sub_Parent_B
|-Child_3
|-Child_4
</code></pre>
<p>I wanted to only call <code>mvn clean install</code> if a project had files that changed in the child projects. This would reduce time on going to each project by hand and calling the command or by just calling the command on the parent project. </p>
<p>The code, along with revisions, can also be found on <a href="https://github.com/ProSpartan/BashScripts/tree/master/GitMavenCleanInstall" rel="nofollow noreferrer">GitHub</a></p>
<pre><code>################################################################################
#
# License:.....GNU General Public License v3.0
# Author:......CodeMonkey
# Date:........14 November 2018
# Title:.......GitMavenCleanInstall.sh
# Description: This script is designed to cd to a set Maven POM Project,
# perform a git remote update and pull, and clean install the changed
# files projects.
# Notice:......The project structure this script was originally set to target
# is structured as a Maven POM Project that contains several sub-POM Projects.
# The sub-POM Projects contain Maven Java Application projects. The targets
# should be easy to change, and allow for others to target other structures.
#
################################################################################
#
# Change History: N/A
#
################################################################################
#!/bin/bash
#Function to check if array has element
containsElement () {
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 0; done
return 1
}
#Navigate to the POM Project
cd PATH/TO/POM/PROJECT
#Remote update
git remote update -p
#Pull
git pull
#Get the current working branch
CURRENT_BRANCH="$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')"
#Get the output of the command git diff
GIT_DIFF_OUTPUT="$(git diff --name-status HEAD@{1} ${CURRENT_BRANCH})"
#Split the diff output into an array
read -a GIT_DIFF_OUTPUT_ARY <<< $GIT_DIF_OUTPUT
#Declare empty array for root path
declare -a GIT_DIFF_OUTPUT_ARY_ROOT_PATH=()
FORWARD='/'
#Loop diff output array
for i in "${GIT_DIFF_OUTPUT_ARY[@]}"
do
#Check that the string is not 1 Character
if [[ "$(echo -n $1 | wc -m)" != 1 ]]
then
#Split the file path by /
IFS='/' read -ra SPLIT <<< $i
#Concatenate first path + / + second path
path=${SPLIT[0]}$FORWARD${SPLIT[1]}
#Call function to see if it already exists in the root path array
containsElement "$path" "${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}"
if [[ $? != 0 ]]
then
#Add the path since it was not found
GIT_DIFF_OUTPUT_ARY_ROOT_PATH+=($path)
fi
fi
done
#Loop root path array
for val in ${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}
do
#CD into root path
cd $val
#Maven call to clean install
mvn -DskipTests=true --errors -T 8 -e clean install
#CD back up before next project
cd ../../
done
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T19:02:51.160",
"Id": "401637",
"Score": "0",
"body": "@janos I created the code on a standalone computer. I had to retype it, hence the typo. However, `git diff --name-status` does get that output, which is why the output is split i... | [
{
"body": "<h3>Take a cleaner approach if you can</h3>\n\n<p>The current approach is basically a dirty hack to work around Maven's inability to do incremental builds.\nI recommend to start looking into another more modern build system that is able to re-build just what needs to be rebuilt.\nSuch as Gradle.</p>\... | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T22:48:00.913",
"Id": "207685",
"Score": "2",
"Tags": [
"bash",
"git",
"installer"
],
"Title": "Partial Maven clean install after Git pull"
} | 207685 |
<p>This game is a variation of the <a href="http://janbroussard.com/Greedy.html" rel="nofollow noreferrer">Greed dice game</a>. Imagine we have 5 dice. We roll, them, and jot down the results. Then, based on this chart:</p>
<pre><code>Three 1's => 1000 points
Three 6's => 600 points
Three 5's => 500 points
Three 4's => 400 points
Three 3's => 300 points
Three 2's => 200 points
One 1 => 100 points
One 5 => 50 point
</code></pre>
<p>We calculate the score. This program exactly does that. It has two functions, one is <code>greed()</code> which takes a vector of 5 integers between 1 and 6 and calculates the score, and the other is <code>greed_rand()</code> which first generates the vector randomly, and then calculates the score.</p>
<pre><code>#include <iostream>
#include <vector>
#include <random>
#include <map>
std::random_device seeder;
std::mt19937 engine(seeder());
std::uniform_int_distribution<int> dist(1, 6);
typedef std::vector<int> list_type;
int greed(list_type die_rolls)
{
int ret = 0;
std::map<int, int> cnt;
for (int i = 1; i <= 6; ++i)
{
cnt[i] = 0;
}
for (auto &d : die_rolls)
{
++cnt[d];
}
if (cnt[1] == 3)
{
ret += 1000;
}
if (cnt[1] == 2)
{
ret += 200;
}
if (cnt[1] == 1)
{
ret += 100;
}
if (cnt[1] == 4)
{
ret += 1100;
}
if (cnt[1] == 5)
{
ret += 1200;
}
if (cnt[2] == 3)
{
ret += 200;
}
if (cnt[3] == 3)
{
ret += 300;
}
if (cnt[4] == 3)
{
ret += 400;
}
if (cnt[5] == 1)
{
ret += 50;
}
if (cnt[5] == 2)
{
ret += 100;
}
if (cnt[5] == 3)
{
ret += 500;
}
if (cnt[5] == 4)
{
ret += 550;
}
if (cnt[5] == 5)
{
ret += 600;
}
if (cnt[6] == 3)
{
ret += 600;
}
return ret;
}
int greed_rand()
{
list_type rolls_rand;
for (int i = 1; i <= 5; ++i)
{
rolls_rand.push_back(dist(engine));
}
return greed(rolls_rand);
}
int main() {
list_type rolls = {1, 1, 1, 5, 5};
std::cout << greed(rolls) << std::endl;
std::cout << greed_rand() << std::endl;
return 0;
}
</code></pre>
<p>The output of this program is:</p>
<pre><code>1100
150
</code></pre>
<p><strong>Note:</strong> If you're on Windows, change the random seeder to <code>time(NULL)</code>. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T08:23:38.907",
"Id": "400936",
"Score": "6",
"body": "Not enough to warrant an answer but I'm surprised the very good answers we have don't mentioned the function names. Though the game is called `greed`, wouldn't `calculate_score` ... | [
{
"body": "<p><strong>Style</strong><br>\nYou're not being charged by the character; there's no need to abbreviate \"count\", or \"ret\" (which I would call \"score\" instead). Also, main has inconsistent brackets with the rest of the program. Other than that, it looks good.</p>\n\n<p><strong>Globals</strong>... | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T00:23:33.730",
"Id": "207689",
"Score": "9",
"Tags": [
"c++",
"game",
"random",
"c++14",
"dice"
],
"Title": "A dice game called \"Greed\""
} | 207689 |
<p>TL;DR what should I do if I have too many methods in my parent component??</p>
<p>I'm making a card game (Pai Gow Tiles) using react and I am having trouble finding a way to format my parent component. I've always heard that you should keep your components small and mine is over 300 lines. Most of it are methods that I need for my logic to set my hand 'house-way'. Think of house way as a set of rules on how to play a hand depending on what cards you're dealt. I tried separating the methods into different files, but some methods use 'this' and it throws an error. </p>
<pre><code>export default class Layout extends Component {
constructor(props) {
console.log("starting up");
super(props);
//each hand holds a randomly generated tile object from { tilesSet }
this.state = {
//needs empty spots for when (mounting) <Hands hand1={this.state.hand[0].img} /> else error since hand[0] doesnt exist.
hand: ["", "", "", ""],
cards: false,
pairName: '',
rule: '',
show: false,
history: [],
input1: 'GJ3',
input2: 'GJ6',
input3: 'teen',
input4: 'teen'
};
//binding in the constructor is recommended for performance.
this.handleToggle = this.handleToggle.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleHW = this.handleHW.bind(this);
this.assignHands = this.assignHands.bind(this);
this.checkPair = this.checkPair.bind(this);
this.checkTeenDey = this.checkTeenDey.bind(this);
this.hiLowMiddle = this.hiLowMiddle.bind(this);
this.compare = this.compare.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.userInput1 = this.userInput1.bind(this);
this.userInput2 = this.userInput2.bind(this);
this.userInput3 = this.userInput3.bind(this);
this.userInput4 = this.userInput4.bind(this);
this.inputClick = this.inputClick.bind(this);
this.baccaratCount = this.baccaratCount.bind(this);
}
baccaratCount = (n, m) => {
//recognizing gong , wong , or pair...
let number = n.val + m.val;
if(n.rank === m.rank){
return 'Pair';
}
else if (n.val === 2 || m.val === 2){
if (number === 10){
return "Gong";
}
else if (number === 11){
return 'Wong';
}
}
//regular baccarat counting...
else if (number >= 10 && number < 20){
if (number >= 20) {
return number -= 20;
}
return number -= 10;
}
//value is under 10, return the sum.
return number;
}
//n = pairTL, n2 = otherTL
split(n, n2){
//Gee Joon
if (n[0].pair === 1) {
let combo1 = this.baccaratCount(n2[0], n[0]);
let combo2 = this.baccaratCount(n2[1], n[1]);
//if it meets the split requirements...
if((combo1 >= 7 && combo2 >= 9) || (combo1 >= 9 && combo2 >= 7)){
console.log('got em', combo1, combo2);
return true;
}
else {
return true;
}
}
}
//checks for pairs. takes an array as arg
checkPair(hand){
for(let i = 0; i < hand.length; i++) {
for (let ii = 0; ii < hand.length; ii++) {
// if there is a pair and it is not comparing to itself.
if (hand[i].pair === hand[ii].pair && i !== ii) {
let pairTL = hand.filter((x) => x.rank === hand[i].rank); //array of the pair tiles
let otherTL = hand.filter((x) => x.rank !== hand[i].rank); // array of the other 2 tiles. use these two to move tiles accordingly
//if pair has split rules...
if (hand[i].split !== false) {
//returns true if it split..
if(this.split(pairTL, otherTL)) {
let copyArr = [pairTL[0], otherTL[0], pairTL[1], otherTL[1]];
this.setState(() => ({hand: copyArr}));
}
else {
let copyArr = otherTL.concat(pairTL);
this.setState(() => ({hand: copyArr}));
return true;
}
}
//don't split
else {
let copyArr = otherTL.concat(pairTL); //concats the two small arrays together and renders.
this.setState(() => ({hand: copyArr, pairName: pairTL[0].name, rule: 'Don\'t Split'}))
return true;
}
}
}
}
return false; // no pairs
}
//will not execute if there is a pair...(checkPair returns true)
checkTeenDey(hand){
//true if we have teen or dey
let teenDey = hand.find((el) => el.val === 2) !== undefined;
//if true...
if(teenDey){
let tile = hand.find((el) => el.val === 2); // teen/ dey object
let tempArr = hand.filter((el) => el.name !== tile.name); //new arr without marked teen/dey. arr.length = 3
let secondTeenDey = tempArr.find((el) => el.val === 2); //second teen/dey (not pair)
let seven = tempArr.find((el) => el.val === 7);
let eight = tempArr.find((el) => el.val === 8);
let nine = tempArr.find((el) => el.val === 9);
//if there is a second teen/dey
if (secondTeenDey){
let twoArr = tempArr.filter((el) => el.name !== secondTeenDey.name);
console.log(tile, secondTeenDey, twoArr);
return true;
}
//look for 7,8,9
else if (seven){
let without7 = tempArr.filter((el) => el.name !== seven.name);
let sevenAndTeenOrDey = [tile, seven];
let newHand = sevenAndTeenOrDey.concat(without7);
this.setState(() => ({hand: newHand, rule: 'Teen/Dey'}));
return true;
}
else if(eight){
let without8 = tempArr.filter((el) => el.name !== eight.name);
let eightAndTeenOrDey = [tile, eight];
let newHand = eightAndTeenOrDey.concat(without8);
this.setState(() => ({hand: newHand, rule: 'Teen/Dey'}));
return true;
}
else if(nine){
let without9 = tempArr.filter((el) => el.name !== nine.name);
let nineAndTeenOrDey = [tile, nine];
let newHand = nineAndTeenOrDey.concat(without9);
this.setState(() => ({hand: newHand, rule: 'Teen/Dey'}));
return true;
}
}
// no teen or dey...
else{
return false;
}
}
//point system used for sort() in hiLowMiddle()
compare(a,b){
let comparison = 0;//no change
if(a.realValue < b.realValue){
comparison = -1;//a comes before b
}
else if(a.realValue > b.realValue){
comparison = 1;//b comes before a
}
return comparison;
}
//will not execute if there is a teen dey...
hiLowMiddle(hand){
//makes a new copy of hand and sorts it using sort()'s point system.
let sortedArr = hand.slice().sort(this.compare); //slice used, else mutates hand.
let tempHair = [sortedArr[0], sortedArr[3]];
let tempBack = [sortedArr[1], sortedArr[2]];
let hiLow = tempHair.concat(tempBack); //newly sorted arr
this.setState(() => ({hand: hiLow, rule: 'Hi-Low-Middle'}));
}
//generates new hand and updates them to state.
assignHands() {
let tempArr = [0, 0, 0, 0]; //filler array
let testArr = tilesSet.slice(); //filler array. tilesSet is untouched
//loops through and assigns random tile from deck
let newArr = tempArr.map((x) => {
let counter = Math.floor(Math.random()* (testArr.length - 1));
//used to hold the selected obj. needed since splice changes arr.length and we splice/display the different indexes.
let dummyArr = testArr[counter];
testArr.splice(counter, 1);
return dummyArr;
})
//updates state
this.setState({hand: [newArr[0], newArr[1], newArr[2], newArr[3]], show: true, history: [...this.state.history, [...newArr]]});
}
handleSubmit = (e) => {
e.preventDefault();
}
//toggle effect.
handleToggle = () => {
this.setState(() => ({cards: !this.state.cards}));
}
handleClick = () => {
this.assignHands();
//works, but not 100% properly. the changes are one step behind. fix async.
//check to see the history length. max set @ 10
if(this.state.history.length >= 10){
let temp = this.state.history.slice();
temp.shift();
this.setState(() => ({history: temp}))
}
}
//House Way
handleHW(){
if(!this.checkPair(this.state.hand)){
if(!this.checkTeenDey(this.state.hand)){
this.hiLowMiddle(this.state.hand);
}
}
}
//used for dropdown options. One per card.
userInput1(e){
this.setState({input1: e.target.value});
}
userInput2(e){
this.setState({input2: e.target.value})
}
userInput3(e){
this.setState({input3: e.target.value})
}
userInput4(e){
this.setState({input4: e.target.value})
}
//updates state and changes hands.
inputClick(){
let first = tilesSet.filter((x) => x.name === this.state.input1);
let second = tilesSet.filter((x) => x.name === this.state.input2);
let third = tilesSet.filter((x) => x.name === this.state.input3);
let fourth = tilesSet.filter((x) => x.name === this.state.input4);
let newArr = [first[0], second[0], third[0], fourth[0]];
this.setState(() => ({hand: newArr, history: [...this.state.history, [...newArr]]}));
}
render() {
return (
<div>
<Answer
show={this.state.show}
baccaratCount={this.baccaratCount}
hand={this.state.hand}
/>
<Hands
cards={this.state.cards}
hand1={this.state.hand[0].img}
hand2={this.state.hand[1].img}
hand3={this.state.hand[2].img}
hand4={this.state.hand[3].img}
/>
<Input
handleSubmit={this.handleSubmit}
userInput1={this.userInput1}
userInput2={this.userInput2}
userInput3={this.userInput3}
userInput4={this.userInput4}
inputClick={this.inputClick}
input1={this.state.input1}
input2={this.state.input2}
input3={this.state.input3}
input4={this.state.input4}
/>
<Buttons
type="button"
className="btn btn-dark"
handleClick={this.handleClick}
handleHW={this.handleHW}
hand={this.state.hand}
/>
<Features
hand={this.state.hand}
pairName={this.state.pairName}
rule={this.state.rule}
history={this.state.history}
/>
</div>
);
}
}
</code></pre>
| [] | [
{
"body": "<p>If you think you have too many methods you should first know, thats completely fine. Until you can accurately prove that all the extra methods are <em>hurting</em> performance in a measurable way there is no need to refactor. That being said, we can move some of these methods out.</p>\n\n<p><code>... | {
"AcceptedAnswerId": "208721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T04:11:32.333",
"Id": "207696",
"Score": "1",
"Tags": [
"playing-cards",
"react.js",
"jsx"
],
"Title": "React component for Pai Gow game"
} | 207696 |
<p>This class is used to make Excel Cells behave like Checkboxes. Clicking the cell raises a <code>CheckedRange_Clicked(Target as Range)</code> event and toggles it's value between 0 and -1. A combination of Fonts and Custom NumberFormats display the cell values as Checkboxes, Checkmarks, Yes/No, True/False or a custom format. </p>
<p><a href="https://i.stack.imgur.com/A8El0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A8El0.gif" alt="CheckedRange Demo"></a></p>
<h2>Class: CheckedRange</h2>
<pre><code>Attribute VB_Name = "CheckedRange"
Attribute VB_PredeclaredId = True
Option Explicit
Public Enum WingdingsCharCode
CheckBoxChecked = 254
CheckBoxUnchecked = 168
XMark = 251
CheckMark = 252
End Enum
Public Enum CheckedRangeTheme
ctCheckBoxes
ctCheckmarks
ctTrueFalse
ctYesNo
End Enum
Private Type Members
CheckedCode As Long
CheckedColor As String
CheckedString As String
EditMode As Boolean
FontName As String
PrevAddress As String
RangeFormula As String
Theme As CheckedRangeTheme
TrueFalse As Boolean
UnCheckedCode As Long
UnCheckedColor As String
UnCheckedString As String
YesNo As Boolean
End Type
Private this As Members
Public Event Clicked(Target As Range)
Public WithEvents Worksheet As Worksheet
Attribute Worksheet.VB_VarHelpID = -1
Private m_bUseYesNo As Boolean
Private m_sCheckedString As String
Private m_sUnCheckedString As String
Private m_bEditMode As Boolean
Private Sub Class_Initialize()
EditMode = True
Me.Theme = CheckedRangeTheme.ctCheckBoxes
EditMode = False
End Sub
Public Property Get CheckedCode() As WingdingsCharCode
CheckedCode = this.CheckedCode
End Property
Public Property Let CheckedCode(ByVal Value As WingdingsCharCode)
CheckedString = Chr(Value)
this.CheckedCode = Value
End Property
Public Property Get CheckedColor() As String
CheckedColor = this.CheckedColor
End Property
Public Property Let CheckedColor(ByVal Value As String)
this.CheckedColor = Value
End Property
Public Property Get CheckedString() As String
CheckedString = this.CheckedString
End Property
Public Property Let CheckedString(ByVal Value As String)
this.CheckedString = Value
End Property
Public Property Get FontName() As String
FontName = this.FontName
End Property
Public Property Let FontName(ByVal Value As String)
this.FontName = Value
End Property
Public Property Get NumberFormat() As String
Dim CheckedColor As String, UnCheckedColor As String
CheckedColor = IIf(Len(this.CheckedColor) > 0, "[" & this.CheckedColor & "]", "")
UnCheckedColor = IIf(Len(this.UnCheckedColor) > 0, "[" & this.UnCheckedColor & "]", "")
NumberFormat = ";" & CheckedColor & Chr(34) & this.CheckedString & Chr(34) & _
";" & UnCheckedColor & Chr(34) & this.UnCheckedString & Chr(34)
End Property
Public Property Get RangeFormula() As String
RangeFormula = this.RangeFormula
End Property
Public Property Let RangeFormula(ByVal Value As String)
this.RangeFormula = Value
End Property
Public Property Get Self() As CheckedRange
Set Self = Me
End Property
Public Property Get Theme() As CheckedRangeTheme
Theme = this.Theme
End Property
Public Property Let Theme(ByVal Value As CheckedRangeTheme)
this.Theme = Value
Select Case this.Theme
Case CheckedRangeTheme.ctCheckBoxes
this.FontName = "Wingdings"
CheckedCode = WingdingsCharCode.CheckBoxChecked
UnCheckedCode = WingdingsCharCode.CheckBoxUnchecked
Case CheckedRangeTheme.ctCheckmarks
this.FontName = "Wingdings"
CheckedCode = WingdingsCharCode.CheckMark
UnCheckedCode = WingdingsCharCode.XMark
Case CheckedRangeTheme.ctTrueFalse
TrueFalse = True
Case CheckedRangeTheme.ctYesNo
YesNo = True
End Select
Me.Apply
End Property
Public Property Get TrueFalse() As Boolean
TrueFalse = this.TrueFalse
End Property
Public Property Let TrueFalse(ByVal Value As Boolean)
CheckedString = "True"
UnCheckedString = "False"
Me.FontName = "Calibri"
this.TrueFalse = Value
Me.Apply
End Property
Public Property Get UnCheckedCode() As WingdingsCharCode
UnCheckedCode = this.UnCheckedCode
End Property
Public Property Let UnCheckedCode(ByVal Value As WingdingsCharCode)
UnCheckedString = Chr(Value)
this.UnCheckedCode = Value
Me.Apply
End Property
Public Property Get UnCheckedColor() As String
UnCheckedColor = this.UnCheckedColor
End Property
Public Property Let UnCheckedColor(ByVal Value As String)
this.UnCheckedColor = Value
Me.Apply
End Property
Public Property Get UnCheckedString() As String
UnCheckedString = this.UnCheckedString
End Property
Public Property Let UnCheckedString(ByVal Value As String)
this.UnCheckedString = Value
Me.Apply
End Property
Public Property Let YesNo(ByVal Value As Boolean)
CheckedString = "Yes"
UnCheckedString = "No"
Me.FontName = "Calibri"
this.YesNo = Value
Me.Apply
End Property
Public Property Get YesNo() As Boolean
YesNo = this.YesNo
End Property
Public Function Create(TargetWorksheet As Worksheet, RangeFormula As String, Optional Theme As CheckedRangeTheme = CheckedRangeTheme.ctCheckBoxes) As CheckedRange
With New CheckedRange
.EditMode = True
.Theme = Theme
.RangeFormula = RangeFormula
Set .Worksheet = TargetWorksheet
.EditMode = False
.Apply
Set Create = .Self
End With
End Function
Public Property Get EditMode() As Boolean
EditMode = this.EditMode
End Property
Public Property Let EditMode(ByVal Value As Boolean)
this.EditMode = Value
End Property
Public Sub Apply()
If Me.EditMode Then Exit Sub
Dim Target As Range
Set Target = Me.Range
If Target Is Nothing Then Exit Sub
this.PrevAddress = Target.Address
With Target
.Font.Name = FontName
.NumberFormat = NumberFormat
If .Count = 1 Then
If Len(.Value) = 0 Or .Value = 0 Then
.Value = 0
Else
.Value = -1
End If
Else
Dim result() As Variant
result = .Value
Dim r As Long, c As Long
For r = 1 To UBound(result)
For c = 1 To UBound(result, 2)
If Len(result(r, c)) = 0 Or result(r, c) = 0 Then
result(r, c) = 0
Else
result(r, c) = -1
End If
Next
Next
.Value = result
End If
End With
End Sub
Public Property Get Range() As Range
On Error Resume Next
Set Range = Worksheet.Range(this.RangeFormula)
End Property
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim MyRange As Range
Set MyRange = Me.Range
If MyRange Is Nothing Then Exit Sub
If Not Intersect(Target, MyRange) Is Nothing Then
Cancel = True
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim MyRange As Range
Set MyRange = Me.Range
If MyRange Is Nothing Then Exit Sub
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, MyRange) Is Nothing Then
Application.EnableEvents = False
Target.Value = IIf(Target.Value = -1, 0, -1)
Application.EnableEvents = True
RaiseEvent Clicked(Target)
End If
If MyRange.Address <> this.PrevAddress Then Me.Apply
End Sub
</code></pre>
<h2>Worksheet Module Test Code</h2>
<pre><code>Option Explicit
Private WithEvents CheckedRange1 As CheckedRange
Private WithEvents CheckedRange2 As CheckedRange
Private WithEvents CheckedRange3 As CheckedRange
Private WithEvents CheckedRange4 As CheckedRange
Private WithEvents CheckedRange5 As CheckedRange
Private Sub Worksheet_Activate()
Set CheckedRange1 = CheckedRange.Create(Me, "OFFSET(G1,1,-6,COUNTA(G:G)-1,1)")
Set CheckedRange2 = CheckedRange.Create(Me, "OFFSET(G1,1,-5,COUNTA(G:G)-1,1)", CheckedRangeTheme.ctCheckmarks)
Set CheckedRange3 = CheckedRange.Create(Me, "OFFSET(G1,1,-4,COUNTA(G:G)-1,1)", CheckedRangeTheme.ctTrueFalse)
Set CheckedRange4 = CheckedRange.Create(Me, "OFFSET(G1,1,-3,COUNTA(G:G)-1,1)", CheckedRangeTheme.ctYesNo)
Set CheckedRange5 = CheckedRange.Create(Me, "OFFSET(G1,1,-2,COUNTA(G:G)-1,2)")
With CheckedRange5
.EditMode = True
.CheckedCode = 253
.UnCheckedCode = 168
.CheckedColor = "Blue"
.UnCheckedColor = "Magenta"
.EditMode = False
.Apply
End With
End Sub
Private Sub CheckedRange1_Clicked(Target As Range)
setLabelCaption "CheckedRange1", Target
End Sub
Private Sub CheckedRange2_Clicked(Target As Range)
setLabelCaption "CheckedRange2", Target
End Sub
Private Sub CheckedRange3_Clicked(Target As Range)
setLabelCaption "CheckedRange3", Target
End Sub
Private Sub CheckedRange4_Clicked(Target As Range)
setLabelCaption "CheckedRange4", Target
End Sub
Private Sub CheckedRange5_Clicked(Target As Range)
setLabelCaption "CheckedRange5", Target
End Sub
Private Sub setLabelCaption(CheckedRangeName As String, Target As Range)
Me.Label1.Caption = CheckedRangeName & ": Clicked" & vbNewLine & _
"Range: " & Target.Address & vbNewLine & _
"Value: " & Target.Value
End Sub
</code></pre>
<p>I'm disappointed that the range filter does not use the same font as range causing symbols that require special fonts to display improperly(e.g. Chr(254) displays as <a href="https://i.stack.imgur.com/YCl1d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YCl1d.png" alt="checkbox"></a> in the cells using Wingdings but <code>þ</code> in the Filter). I don't think that there is a reasonable way to fix this but I am open to suggestions.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T05:04:33.940",
"Id": "207698",
"Score": "3",
"Tags": [
"vba",
"excel"
],
"Title": "CheckedRange Class"
} | 207698 |
<p>Using Laravel, I need to export some value from the DB in a CSV and then upload the CSV via sFTP or return it in a Response.</p>
<p>I'm trying to be use S.O.L.I.D. principles but with this scenario, I'm not sure how to proceed. As I understand I should have one class that handles the CSV, one that handles the sFTP, one for the Response, and one to handle the logic of the model (the mapping in my case). But I don't understand how I can separate them.</p>
<p>Later one, I will have more Model data to export.</p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\Services;
use App\Line;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Storage;
class LinesCsv
{
const DOCUMENT_TYPE = 20;
const DELIMITER = ';';
public function exportCSVFileToSftp($filename = 'export.csv')
{
$handle = fopen('php://temp', 'w');
$handle = $this->buildCsv($handle);
return Storage::disk('sftp')->put($filename, $handle);
}
public function exportCSVFileToResponse($filename = 'export.csv')
{
return new StreamedResponse(function () use ($filename) {
$handle = fopen('php://output', 'w');
$handle = $this->buildCsv($handle);
fclose($handle);
}, 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
public function buildCsv($handle, $header = false)
{
if ($header) {
fputcsv(
$handle,
array_keys($this->lineMapping(Line::first())),
self::DELIMITER
);
}
Line::with(['invoice', 'invoice.customer', 'item'])
->whereHas('invoice', function ($query) {
$query->where('is_exportable', 1);
})
->chunk(200, function ($lines) use ($handle) {
foreach ($lines as $line) {
fputcsv(
$handle,
$this->lineMapping($line),
self::DELIMITER
);
}
});
return $handle;
}
protected function lineMapping(Line $line)
{
return [
'Invoice number' => $line->invoice->id,
'Document type' => self::DOCUMENT_TYPE,
'Date' => $line->invoice->date,
];
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-20T13:01:42.127",
"Id": "401770",
"Score": "0",
"body": "What model are you using here, is it `Line`? I see it query the DB but the columns names doesn't seem to have anything to do with `Line`"
},
{
"ContentLicense": "CC BY-SA... | [
{
"body": "<p>Try to think about this in a more generic way, you basically have:</p>\n\n<ol>\n<li>Select data from DB</li>\n<li>Put that data in a CSV (will you in the future want to use other formats like XLSX, etc? If so, we should abstract this step too, but I wont do this right now)</li>\n<li>Return that CS... | {
"AcceptedAnswerId": "207876",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T07:54:27.603",
"Id": "207704",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"csv",
"laravel",
"network-file-transfer"
],
"Title": "Laravel: Export customer record as CSV"
} | 207704 |
<p>I'm quite new to Swift, and although I've been programming as a hobby for many years, I'm still not very confident about my code.</p>
<p>I'm currently rewriting an old library of mine, an NMEA parser. NMEA is a standard for GPS sentences containing position, time, satellites signal power and so on. </p>
<p>Basically this code receives a string and extracts values from it. For example:</p>
<pre><code>$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
</code></pre>
<p>Where "123519" is current time, "4807.038,N,01131.000,E" are latitude/longitude and so on. There are many, many types of NMEA sentences; see <a href="https://www.gpsinformation.org/dale/nmea.htm" rel="nofollow noreferrer">NMEA reference</a>.</p>
<pre><code>import Foundation
typealias Byte = UInt8
extension UInt8 {
var hexValue:String {
return (self < 16 ? "0":"") + String(self, radix:16, uppercase:true)
}
}
/*
Allows to test against nil multiple variables aton once.
*/
extension Collection where Element == Optional<Any> {
func allNotNil() -> Bool {
return self.compactMap { $0 }.count > self.count
}
func atleastOneNotNil() -> Bool {
return self.compactMap { $0 }.count > 0
}
func allNil() -> Bool {
return self.compactMap { $0 }.count == 0
}
func atleastOneIsNil() -> Bool {
return self.contains { $0 == nil }
}
}
class NMEASentenceParser {
static let shared = NMEASentenceParser()
private init() {}
func parse(_ nmeaSentence:String) -> Any? {
if nmeaSentence.isEmpty {
return nil
}
if nmeaSentence.hasPrefix("$GPGGA") {
return GPGGA(nmeaSentence)
} else if nmeaSentence.hasPrefix("$GPGSA") {
return GPGSA(nmeaSentence)
}
return nil
}
//Generic class
class NMEASentence {
private var sentence:String
var trimmedSentence:String
var isValid:Bool {
get {
return sentence.suffix(2) == checksum().hexValue
}
}
func checksum() -> UInt8 {
var xor:UInt8 = 0
for i in 0..<trimmedSentence.utf8.count {
xor = xor ^ Array(trimmedSentence.utf8)[i]
}
return xor
}
init?(_ nmeaSentence:String) {
sentence = nmeaSentence
//duplicate sentence trimmed from its "$" and checksum
let start = sentence.index(sentence.startIndex, offsetBy: 1)
let end = sentence.index(sentence.endIndex, offsetBy: -3)
trimmedSentence = String(sentence[start..<end])
if isValid == false {
return nil
}
}
}
/*
Source: https://www.gpsinformation.org/dale/nmea.htm
GGA - essential fix data which provide 3D location and accuracy data.
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
Where:
GGA Global Positioning System Fix Data
123519 Fix taken at 12:35:19 UTC
4807.038,N Latitude 48 deg 07.038' N
01131.000,E Longitude 11 deg 31.000' E
1 Fix quality:
0 = invalid
1 = GPS fix (SPS)
2 = DGPS fix
3 = PPS fix
4 = Real Time Kinematic
5 = Float RTK
6 = estimated (dead reckoning) (2.3 feature)
7 = Manual input mode
8 = Simulation mode
08 Number of satellites being tracked
0.9 Horizontal dilution of position
545.4,M Altitude, Meters, above mean sea level
46.9,M Height of geoid (mean sea level) above WGS84
ellipsoid
(empty field) time in seconds since last DGPS update
(empty field) DGPS station ID number
*47 the checksum data, always begins with *
*/
class GPGGA:NMEASentence {
override init?(_ nmeaSentence:String) {
//init will fail if
super.init(nmeaSentence)
let splittedSentence = trimmedSentence.split(separator: ",", maxSplits: Int.max, omittingEmptySubsequences: false)
utcTime = Float(splittedSentence[1])
latitude = Coordinate(splittedSentence[2], splittedSentence[3])
longitude = Coordinate(splittedSentence[4], splittedSentence[5])
fixQuality = FixQuality(rawValue: Int(splittedSentence[6]) ?? -1)
numberOfSatellites = Int(splittedSentence[7])
horizontalDilutionOfPosition = Float(splittedSentence[8])
mslAltitude = Float(splittedSentence[9])
mslAltitudeUnit = String(splittedSentence[10])
heightOfGeoid = Float(splittedSentence[11])
heightOfGeoidUnit = String(splittedSentence[10])
if [utcTime,latitude,longitude,fixQuality,numberOfSatellites,horizontalDilutionOfPosition,mslAltitude,mslAltitudeUnit,heightOfGeoid,heightOfGeoidUnit].atleastOneIsNil() == true {
return nil
}
}
var utcTime:Float?
var latitude:Coordinate?
var longitude:Coordinate?
var fixQuality:FixQuality?
var numberOfSatellites:Int?
var horizontalDilutionOfPosition:Float?
var mslAltitude:Float?
var mslAltitudeUnit:String?
var heightOfGeoid:Float?
var heightOfGeoidUnit:String?
}
/*
$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
Where:
GSA Satellite status
A Auto selection of 2D or 3D fix (M = manual)
3 3D fix - values include: 1 = no fix
2 = 2D fix
3 = 3D fix
04,05... PRNs of satellites used for fix (space for 12)
2.5 PDOP (dilution of precision)
1.3 Horizontal dilution of precision (HDOP)
2.1 Vertical dilution of precision (VDOP)
*39 the checksum data, always begins with *
*/
class GPGSA:NMEASentence {
override init?(_ nmeaSentence:String) {
super.init(nmeaSentence)
let splittedSentence = trimmedSentence.split(separator: ",", maxSplits: Int.max, omittingEmptySubsequences: false)
fixSelectionMode = FixSelectionMode(rawValue: Character(String(splittedSentence[1])))
threeDFixMode = FixMode(rawValue: Int(splittedSentence[2]) ?? 0)
for i in 0..<12 {
prn.append(Int(splittedSentence[3+i]))
}
pdop = Float(splittedSentence[15])
hdop = Float(splittedSentence[16])
vdop = Float(splittedSentence[17])
//prn can definitely contail nil values, as less than 12 GPS can be in sight
if [fixSelectionMode, threeDFixMode, hdop, vdop, pdop].atleastOneIsNil() == true {
return nil
}
}
var fixSelectionMode:FixSelectionMode?
var threeDFixMode:FixMode?
var prn = [Int?]()
var pdop:Float?
var hdop:Float?
var vdop:Float?
}
struct Coordinate {
var coordinate:Float?
var direction:Direction?
init?(_ coordinate:Substring, _ direction:Substring) {
self.coordinate = Float(coordinate)
guard self.coordinate != nil else {
return nil
}
self.direction = Direction(String(direction))
guard self.direction != nil else {
return nil
}
}
}
enum FixSelectionMode:Character {
case manual = "M"
case auto = "A"
}
enum FixMode:Int {
case nofix = 1
case twod = 2
case threed = 3
}
enum Direction:Character {
case north = "N"
case south = "S"
case east = "E"
case west = "W"
init?(_ direction:String) {
switch String(direction) {
case "N":
self = .north
case "S":
self = .south
case "E":
self = .east
case "W":
self = .west
default:
return nil
}
}
}
enum FixQuality:Int {
case Invalid = 0
case GPSFixSPS = 1
case DGPSFix = 2
case PPSFix = 3
case RealTimeKinematic = 4
case FloatRTK = 5
case Estimated = 6
case ManualInputMode = 7
case SimulationMode = 8
}
}
</code></pre>
<p>Code doesn't cover full NMEA standard yet, but the most important parts are there.</p>
<p>How to use it:</p>
<pre><code>let gpgga = NMEASentenceParser.shared.parse(correctGPGGASentence) as! NMEASentenceParser.GPGGA
</code></pre>
<p>BTW: full code lies <a href="https://gitlab.com/X99/swiftnmeaparser" rel="nofollow noreferrer">on GitLab</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-21T15:24:36.740",
"Id": "401979",
"Score": "0",
"body": "NMEA is more than just GPS, course - echo sounders, gyroscopes, and all kinds of other sensor communicate in NMEA sentences."
},
{
"ContentLicense": "CC BY-SA 4.0",
"... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T09:00:01.587",
"Id": "207706",
"Score": "1",
"Tags": [
"parsing",
"swift"
],
"Title": "Swift NMEA parser"
} | 207706 |
<p>The problem with the original Lazy in C# is that you <strong>have</strong> to put the initialization in the constructor if you want to refer to <code>this</code>.</p>
<p>For me that is 95% of the cases. Meaning that I have to put half of my logic concerning the lazy property in the constructor, and having more boilerplate code.</p>
<p>See this question: <a href="https://stackoverflow.com/questions/53271662/concise-way-to-writy-lazy-loaded-properties-in-c-sharp/53316998#53316998">https://stackoverflow.com/questions/53271662/concise-way-to-writy-lazy-loaded-properties-in-c-sharp/53316998#53316998</a></p>
<p>Now I made a new version where I actually move the initialization part to the 'Get' moment. This saves boilerplate code and I can group everything about this property together.</p>
<p>But:</p>
<ul>
<li>is the current implementation 'safe'?</li>
<li>are there any important performance considerations vs the original one?</li>
<li>is there anything else I'm missing that I should be concerned about in a high traffic application?</li>
</ul>
<p>Class:</p>
<pre><code>public class MyLazy
{
private object _Value;
private bool _Loaded;
private object _Lock = new object();
public T Get<T>(Func<T> create)
{
if ( _Loaded )
return (T)_Value;
lock (_Lock)
{
if ( _Loaded ) // double checked lock
return (T)_Value;
_Value = create();
_Loaded = true;
}
return (T)_Value;
}
public void Invalidate()
{
lock ( _Lock )
_Loaded = false;
}
}
</code></pre>
<p>Use:</p>
<pre><code>MyLazy _SubEvents = new MyLazy();
public SubEvents SubEvents => _SubEvents.Get(() =>
{
// [....]
return x;
});
</code></pre>
<p>Or like:</p>
<pre><code>MyLazy _SubEvents = new MyLazy();
public SubEvents SubEvents => _SubEvents.Get(LoadSubEvents);
public void LoadSubEvents()
{
// [....]
return x;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T10:44:25.203",
"Id": "400955",
"Score": "0",
"body": "@AdrianoRepetti this would make a great answer ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T18:57:44.173",
"Id": "401013",
"Score":... | [
{
"body": "<blockquote>\n <p>is there anything else I'm missing that I should be concerned about in a <strong>high traffic</strong> application?</p>\n</blockquote>\n\n<p>Yes, your <code>Lazy<T>.Value</code> isn't generic anymore but an <code>object</code> and if <code>Func<T></code> returns a value... | {
"AcceptedAnswerId": "207904",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T10:15:19.213",
"Id": "207708",
"Score": "26",
"Tags": [
"c#",
"generics",
"lazy"
],
"Title": "Own implementation of Lazy<T> object"
} | 207708 |
<p>Given positive integers a,b,c and limit, I want to generate all products having the form
<span class="math-container">$$p^aq^br^c \leq limit$$</span> less than limit (where p,q,r are distinct primes). a,b and c are not necessary distinct.</p>
<p>I tried something like:</p>
<pre><code>primes= [ 2,3,5,...] # primes up to 10**8
[ (p**a)*(q**b)*(r**c) for p in primes for q in primes for r in primes if (p**a)*(q**b)*(r**c) <= limit ]
</code></pre>
<p>But it is very slow because len(primes)(=5761455) is high.</p>
<p>Then I tried a very ugly code for printing values.
It generates all values for p < q < r (p, q, r primes)</p>
<pre><code>def generate3(a,b,c,limit):
global primes
i1 = 0
i2 = 1
i3 = 2
while i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and (primes[i1]**a)*(primes[i2]**b)*primes[i3]**c < limit:
print(str(i1)+" "+str(i2)+str(i3))
while i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and (primes[i1]**a)*(primes[i2]**b)*primes[i3]**c< limit:
while i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and (primes[i1]**a)*(primes[i2]**b)*primes[i3]**c< limit:
print(str(primes[i1])+" "+str(primes[i2])+" "+str(primes[i3])+" "+str((primes[i1]**a)*(primes[i2]**b)*(primes[i3]**c)))
i3 = i3 + 1
i2 = i2 +1
i3 = i2 +1
i1 = i1 + 1
i2 = i1 + 1
i3 = i2 + 1
</code></pre>
<p>Is there a more pythonic way to do this?
Is there a better method for generating these products of powers quickly?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-16T14:49:24.210",
"Id": "401198",
"Score": "0",
"body": "Is the constraint `p < q < r ` a coincidence, or one of the do they just need to be distinct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-16T16:1... | [
{
"body": "<h1>global</h1>\n\n<p>there is no need to make <code>primes</code> a <code>global</code>. You only read from it, but don't assign to it, you can use it as is. It will be even faster if you make <code>primes</code> a local variable by passing it in as a parameter, so Python uses the <code>LOAD_FAST</... | {
"AcceptedAnswerId": "207795",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T10:37:40.897",
"Id": "207711",
"Score": "2",
"Tags": [
"python",
"performance",
"primes"
],
"Title": "Generation of products of power"
} | 207711 |
<p>I made a quiz programme for my GCSE Computer Science NEA. I just want to make sure it is OK to submit.</p>
<p>There are also 5 files:
Usernames,
Passwords,
Song Names,
Artist Names and
High Scores.</p>
<p>Any feedback is appreciated, positive or negative!</p>
<pre><code>import random # Imports the random module
def readData(): # Load Files and Log In
with open("Song Names.txt", "r") as f:# Opens the song file
songNames = [line.rstrip('\n') for line in f]# Puts the song file into a list
f.close()
with open("Artist Names.txt", "r") as f:# Opens the artists file
artistNames = [line.rstrip('\n') for line in f]# Puts the artists file into a list
f.close()
with open("Usernames.txt", "r") as f:# Opens the username file
usernames = [line.rstrip('\n') for line in f]# Puts the username file into a list
f.close()
with open("Passwords.txt", "r") as f:# Opens the username file
passwords = [line.rstrip('\n') for line in f]# Puts the username file into a list
f.close()
return songNames, artistNames, usernames, passwords # Returns the newly created list
def login(usernames, passwords):
global enterUsername
enterUsername = input("Enter username\n> ")# Prompts the user to enter their username
if enterUsername in usernames: # If the username is in usernames...
enterPassword = str(input("Enter password\n> ")) # Prompts the user to enter their password
usernamePos = usernames.index(enterUsername) # Finds the position ofthe username
if enterPassword in passwords: # If the password is in passwords...
passwordPos = passwords.index(enterPassword) # Finds the position of the entered password
if usernamePos == passwordPos: # If the password and the username is in the same position
print ("You are logged in", enterUsername) # Log in!
return True
else: # If the password is not in the same position
print("You entered the wrong password...") # Inform the user about their mistake
else: # If the password is not in passwords...
print("That password is not in the file...")# Inform the user about their mistake
else: # If the username is not in usernames
print("You're not allowed to play the game...") # Inform the user about their mistake
return False # Tell the programme that the user did not log in
def chooseSong(songNames, artistNames): # Sets up the song requirew
secretSong = random.choice(songNames) # Generates a random song
sSP = songNames.index(secretSong) # Finds the position of the secret song
secretArtist = artistNames[sSP] # Gets the correct artist from the song
return secretSong, secretArtist # Returns the song or artist
def loadGame(secretSong, secretArtist): # Loads the game
word_guessed = [] # return secretSong
print ("The artist is ", secretArtist, "and the song is", secretSong) # Print the artists nam
for letter in secretSong: # Prints the song name (censored, of course)
if letter == " ": # If the ltetter is a space...
word_guessed.append(" / ") # Print a dash
else: # Otherwise...
word_guessed.append("-") # Print a line
for letter in word_guessed:
print (letter, end = " ")
return secretSong # Returns the secret song
def playGame(secretSong, score): # Plays the game
tries = 0 # Sets the amount of tries to 0
while True:
userGuess = str(input("\nWhat is the song name?\n> ")) # Gives the user the oppertunity to guess the song name
if userGuess == secretSong: # If the user guesses correctly...
print("Correct!") # Prints that they are correct
if tries == 0: # If they got the song name correct on their first try
score = score + 3 # Add 3 points to thesongNames = [line.rstrip('\n') for line in f] score
print("You earnt 3 points! You have", score, "points in total.") # States that the user has got 3 points, and states the amount of points the user has in total
time.sleep(1) # Wait a second
return score, True # Return the score and True, to run the game again
elif tries == 1: # If they got the song name correct on their second try
score = score + 1 # Add 1 point to the score
print("You earnt 1 point! You have", score, "points in total.") # States that the user has got 1 point, and states the amount of points the user has in total
time.sleep(1) # Wait a second
return score, True # Return the score and True, to run the game again
else: # If the user guessed the song wrong
tries = tries + 1 # You add a try to the programme
if tries == 2: # while the tries are equal to 2
print ("Game over! You got", score, "points!") # Prints the game over screen, showing the points they earned in the game (if any)
time.sleep(3) # Waits three seconds
return score, False # Returns False, to display the high scores
break # Breaks from the while True loop
print("You have 1 try left.") # Prints that the user has 1 try left
else:
print("Incorrect!") # Tells the user that they were wrong
time.sleep(0.5) # Wait half a second
print("You have 1 try left.") # Prints that the user has 1 try left
def highScore(score, enterUsername):
sTF1 = (enterUsername + " scored ") # Save To File part 1
sTF2 = (str(score + " points.")) # Save To File part 2
sTF = str("\n" + sTF1 + sTF2) # Save To File
with open("Scores.txt", "r") as f: # Opens the score file
highScores = [line.rstrip('\n') for line in f]
f.close()# Writes the score to the high score file
with open("Scores.txt", "a") as f:
f.write(sTF)
f.close()
openScores = input("Would you like to see the score? Y/N\n> ") # Gives the user the option to view the scores
if openScores.lower() == ("y" or "yes"):
print (highScores)
time.sleep(5)
quit()
else:
quit()
def main():
songNames, artistNames, usernames, passwords = readData()# Reads the data from text files
score = 0 # Set the score to 0
success = login(usernames, passwords)# prompts the user to login
if success == True: # If they log in successfully
while True:
print ('''Rules of the game!
1) The name of the song is in all capitals
2) There must be no space after your entry
3) Have fun!''')
secretSong, artist = chooseSong(songNames, artistNames) # Chooses a random song
loadGame(secretSong, artist) # Creates the censored song name
score, win = playGame(secretSong, score) # Plays the game
if win == False: # If you lose the game
highScore(score, enterUsername)
break
main() #Plays the game!
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T11:20:24.190",
"Id": "400962",
"Score": "3",
"body": "As this is for an assignment, don't forget that when you submit it, you must acknowledge any help received."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2... | [
{
"body": "<p>When you are using <code>with</code> statement call to <code>close</code> is redundant. Once the flow comes out of <code>with</code> expression, closing the file is taken care. Check out the <a href=\"https://docs.python.org/2.5/whatsnew/pep-343.html\" rel=\"nofollow noreferrer\">pep</a> for more ... | {
"AcceptedAnswerId": "207729",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T10:53:11.677",
"Id": "207713",
"Score": "5",
"Tags": [
"python",
"homework",
"quiz"
],
"Title": "Quiz programme for GCSE"
} | 207713 |
<p>The code below is for a board game program, which works by placing the user on a grid which then tasks the user with finding all the treasure chests. Each chest landed on gives 10 gold however landing on a bandit means all your gold is taken. The end score should be given once the user has found all the chests.</p>
<p>A few features including the end game, score board, timer and more are still required to be added. For now I just want feedback on how to improve the code at its current state (the code could very well be simplified).</p>
<pre><code>import random
import sys
import time
boardeasy=[]
boardmed=[]
boardhard=[]
current=[0,0]
Treasure1_Row = random.randint(0,8)
Treasure1_Col = random.randint(0,8)
Treasure2_Row = random.randint(0,8)
Treasure2_Col = random.randint(0,8)
Treasure3_Row = random.randint(0,8)
Treasure3_Col = random.randint(0,8)
Treasure4_Row = random.randint(0,8)
Treasure4_Col = random.randint(0,8)
Treasure5_Row = random.randint(0,8)
Treasure5_Col = random.randint(0,8)
Treasure6_Row = random.randint(0,8)
Treasure6_Col = random.randint(0,8)
Treasure7_Row = random.randint(0,8)
Treasure7_Col = random.randint(0,8)
Treasure8_Row = random.randint(0,8)
Treasure8_Col = random.randint(0,8)
Treasure9_Row = random.randint(0,8)
Treasure9_Col = random.randint(0,8)
Treasure10_Row = random.randint(0,8)
Treasure10_Col = random.randint(0,8)
Treasure11_Row = random.randint(0,8)
Treasure11_Col = random.randint(0,8)
Treasure12_Row = random.randint(0,8)
Treasure12_Col = random.randint(0,8)
Bandit1_Row = random.randint(0,8)
Bandit1_Col = random.randint(0,8)
Bandit2_Row = random.randint(0,8)
Bandit2_Col = random.randint(0,8)
Bandit3_Row = random.randint(0,8)
Bandit3_Col = random.randint(0,8)
Bandit4_Row = random.randint(0,8)
Bandit4_Col = random.randint(0,8)
Bandit5_Row = random.randint(0,8)
Bandit5_Col = random.randint(0,8)
Bandit6_Row = random.randint(0,8)
Bandit6_Col = random.randint(0,8)
Bandit7_Row = random.randint(0,8)
Bandit7_Col = random.randint(0,8)
Bandit8_Row = random.randint(0,8)
Bandit8_Col = random.randint(0,8)
Bandit9_Row = random.randint(0,8)
Bandit9_Col = random.randint(0,8)
Bandit10_Row = random.randint(0,8)
Bandit10_Col = random.randint(0,8)
Bandit11_Row = random.randint(0,8)
Bandit11_Col = random.randint(0,8)
Bandit12_Row = random.randint(0,8)
Bandit12_Col = random.randint(0,8)
Coins = 0
class user():
def __init__(self, username, userscore, usertime):
self.username = username
self.userscore = userscore
self.usertime = usertime
#For loop prints a new 8*8 grid after every move
for i in range(8):
b=[]
for j in range(8):
b.append(' ')
boardeasy.append(b)
def table_game_easy():
print(" 1 2 3 4 5 6 7 8")
print("---------------------------------")
print ('| ' + boardeasy[0][0] + '| ' + boardeasy[0][1] + ' | ' + boardeasy[0][2] + ' | ' + boardeasy[0][3] + ' | ' + boardeasy[0][4] + ' | ' + boardeasy[0][5] + ' | ' + boardeasy[0][6] + ' | ' + boardeasy[0][7] + ' | ' + '1')
print("---------------------------------")
print ('| ' + boardeasy[1][0] + '| ' + boardeasy[1][1] + ' | ' + boardeasy[1][2] + ' | ' + boardeasy[1][3] + ' | ' + boardeasy[1][4] + ' | ' + boardeasy[1][5] + ' | ' + boardeasy[1][6] + ' | ' + boardeasy[1][7] + ' | ' + '2')
print("---------------------------------")
print ('| ' + boardeasy[2][0] + '| ' + boardeasy[2][1] + ' | ' + boardeasy[2][2] + ' | ' + boardeasy[2][3] + ' | ' + boardeasy[2][4] + ' | ' + boardeasy[2][5] + ' | ' + boardeasy[2][6] + ' | ' + boardeasy[2][7] + ' | ' + '3')
print("---------------------------------")
print ('| ' + boardeasy[3][0] + '| ' + boardeasy[3][1] + ' | ' + boardeasy[3][2] + ' | ' + boardeasy[3][3] + ' | ' + boardeasy[3][4] + ' | ' + boardeasy[3][5] + ' | ' + boardeasy[3][6] + ' | ' + boardeasy[3][7] + ' | ' + '4')
print("---------------------------------")
print ('| ' + boardeasy[4][0] + '| ' + boardeasy[4][1] + ' | ' + boardeasy[4][2] + ' | ' + boardeasy[4][3] + ' | ' + boardeasy[4][4] + ' | ' + boardeasy[4][5] + ' | ' + boardeasy[4][6] + ' | ' + boardeasy[4][7] + ' | ' + '5')
print("---------------------------------")
print ('| ' + boardeasy[5][0] + '| ' + boardeasy[5][1] + ' | ' + boardeasy[4][2] + ' | ' + boardeasy[5][3] + ' | ' + boardeasy[5][4] + ' | ' + boardeasy[5][5] + ' | ' + boardeasy[5][6] + ' | ' + boardeasy[5][7] + ' | ' + '6')
print("---------------------------------")
print ('| ' + boardeasy[6][0] + '| ' + boardeasy[6][1] + ' | ' + boardeasy[5][2] + ' | ' + boardeasy[6][3] + ' | ' + boardeasy[6][4] + ' | ' + boardeasy[6][5] + ' | ' + boardeasy[6][6] + ' | ' + boardeasy[6][7] + ' | ' + '7')
print("---------------------------------")
print ('| ' + boardeasy[7][0] + '| ' + boardeasy[7][1] + ' | ' + boardeasy[7][2] + ' | ' + boardeasy[7][3] + ' | ' + boardeasy[7][4] + ' | ' + boardeasy[7][5] + ' | ' + boardeasy[7][6] + ' | ' + boardeasy[7][7] + ' | ' + '8')
print("---------------------------------")
#Variables which will store a certain range
Treasure1_Row = random.randint(0,8)
Treasure1_Col = random.randint(0,8)
Treasure2_Row = random.randint(0,8)
Treasure2_Col = random.randint(0,8)
Treasure3_Row = random.randint(0,8)
Treasure3_Col = random.randint(0,8)
Treasure4_Row = random.randint(0,8)
Treasure4_Col = random.randint(0,8)
Treasure5_Row = random.randint(0,8)
Treasure5_Col = random.randint(0,8)
Treasure6_Row = random.randint(0,8)
Treasure6_Col = random.randint(0,8)
Treasure7_Row = random.randint(0,8)
Treasure7_Col = random.randint(0,8)
Treasure8_Row = random.randint(0,8)
Treasure8_Col = random.randint(0,8)
Treasure9_Row = random.randint(0,8)
Treasure9_Col = random.randint(0,8)
Treasure10_Row = random.randint(0,8)
Treasure10_Col = random.randint(0,8)
Bandit1_Row = random.randint(0,8)
Bandit1_Col = random.randint(0,8)
Bandit2_Row = random.randint(0,8)
Bandit2_Col = random.randint(0,8)
Bandit3_Row = random.randint(0,8)
Bandit3_Col = random.randint(0,8)
Bandit4_Row = random.randint(0,8)
Bandit4_Col = random.randint(0,8)
Bandit5_Row = random.randint(0,8)
Bandit5_Col = random.randint(0,8)
# For loop prints a new 10*10 grid after every move
for i in range(10):
b=[]
for j in range(10):
b.append(' ')
boardmed.append(b)
def table_game_meduim():
print(" 1 2 3 4 5 6 7 8 9 10")
print("-----------------------------------------")
print ('| ' + boardmed[0][0] + '| ' + boardmed[0][1] + ' | ' + boardmed[0][2] + ' | ' + boardmed[0][3] + ' | ' + boardmed[0][4] + ' | ' + boardmed[0][5] + ' | ' + boardmed[0][6] + ' | ' + boardmed[0][7] + ' | ' + boardmed[0][8] + ' | ' + boardmed[0][9] + ' | ' + '1')
print("-----------------------------------------")
print ('| ' + boardmed[1][0] + '| ' + boardmed[1][1] + ' | ' + boardmed[1][2] + ' | ' + boardmed[1][3] + ' | ' + boardmed[1][4] + ' | ' + boardmed[1][5] + ' | ' + boardmed[1][6] + ' | ' + boardmed[1][7] + ' | ' + boardmed[1][8] + ' | ' + boardmed[1][9] + ' | ' + '2')
print("-----------------------------------------")
print ('| ' + boardmed[2][0] + '| ' + boardmed[2][1] + ' | ' + boardmed[2][2] + ' | ' + boardmed[2][3] + ' | ' + boardmed[2][4] + ' | ' + boardmed[2][5] + ' | ' + boardmed[2][6] + ' | ' + boardmed[2][7] + ' | ' + boardmed[2][8] + ' | ' + boardmed[2][9] + ' | ' + '3')
print("-----------------------------------------")
print ('| ' + boardmed[3][0] + '| ' + boardmed[3][1] + ' | ' + boardmed[3][2] + ' | ' + boardmed[3][3] + ' | ' + boardmed[3][4] + ' | ' + boardmed[3][5] + ' | ' + boardmed[3][6] + ' | ' + boardmed[3][7] + ' | ' + boardmed[3][8] + ' | ' + boardmed[3][9] + ' | ' + '4')
print("-----------------------------------------")
print ('| ' + boardmed[4][0] + '| ' + boardmed[4][1] + ' | ' + boardmed[4][2] + ' | ' + boardmed[4][3] + ' | ' + boardmed[4][4] + ' | ' + boardmed[4][5] + ' | ' + boardmed[4][6] + ' | ' + boardmed[4][7] + ' | ' + boardmed[4][8] + ' | ' + boardmed[4][9] + ' | ' + '5')
print("-----------------------------------------")
print ('| ' + boardmed[5][0] + '| ' + boardmed[5][1] + ' | ' + boardmed[5][2] + ' | ' + boardmed[5][3] + ' | ' + boardmed[5][4] + ' | ' + boardmed[5][5] + ' | ' + boardmed[5][6] + ' | ' + boardmed[5][7] + ' | ' + boardmed[5][8] + ' | ' + boardmed[5][9] + ' | ' + '6')
print("-----------------------------------------")
print ('| ' + boardmed[6][0] + '| ' + boardmed[6][1] + ' | ' + boardmed[6][2] + ' | ' + boardmed[6][3] + ' | ' + boardmed[6][4] + ' | ' + boardmed[6][5] + ' | ' + boardmed[6][6] + ' | ' + boardmed[6][7] + ' | ' + boardmed[6][8] + ' | ' + boardmed[6][9] + ' | ' + '7')
print("-----------------------------------------")
print ('| ' + boardmed[7][0] + '| ' + boardmed[7][1] + ' | ' + boardmed[7][2] + ' | ' + boardmed[7][3] + ' | ' + boardmed[7][4] + ' | ' + boardmed[7][5] + ' | ' + boardmed[7][6] + ' | ' + boardmed[7][7] + ' | ' + boardmed[7][8] + ' | ' + boardmed[7][9] + ' | ' + '8')
print("-----------------------------------------")
print ('| ' + boardmed[8][0] + '| ' + boardmed[8][1] + ' | ' + boardmed[8][2] + ' | ' + boardmed[8][3] + ' | ' + boardmed[8][4] + ' | ' + boardmed[8][5] + ' | ' + boardmed[8][6] + ' | ' + boardmed[8][7] + ' | ' + boardmed[8][8] + ' | ' + boardmed[8][9] + ' | ' + '9')
print("-----------------------------------------")
print ('| ' + boardmed[9][0] + '| ' + boardmed[9][1] + ' | ' + boardmed[9][2] + ' | ' + boardmed[9][3] + ' | ' + boardmed[9][4] + ' | ' + boardmed[9][5] + ' | ' + boardmed[9][6] + ' | ' + boardmed[9][7] + ' | ' + boardmed[9][8] + ' | ' + boardmed[9][9] + ' | ' + '10')
print("-----------------------------------------")
Treasure1_Row = random.randint(0,10)
Treasure1_Col = random.randint(0,10)
Treasure2_Row = random.randint(0,10)
Treasure2_Col = random.randint(0,10)
Treasure3_Row = random.randint(0,10)
Treasure3_Col = random.randint(0,10)
Treasure4_Row = random.randint(0,10)
Treasure4_Col = random.randint(0,10)
Treasure5_Row = random.randint(0,10)
Treasure5_Col = random.randint(0,10)
Treasure6_Row = random.randint(0,10)
Treasure6_Col = random.randint(0,10)
Treasure7_Row = random.randint(0,10)
Treasure7_Col = random.randint(0,10)
Treasure8_Row = random.randint(0,10)
Treasure8_Col = random.randint(0,10)
Treasure9_Row = random.randint(0,10)
Treasure9_Col = random.randint(0,10)
Treasure10_Row = random.randint(0,10)
Treasure10_Col = random.randint(0,10)
Bandit1_Row = random.randint(0,10)
Bandit1_Col = random.randint(0,10)
Bandit2_Row = random.randint(0,10)
Bandit2_Col = random.randint(0,10)
Bandit3_Row = random.randint(0,10)
Bandit3_Col = random.randint(0,10)
Bandit4_Row = random.randint(0,10)
Bandit4_Col = random.randint(0,10)
Bandit5_Row = random.randint(0,10)
Bandit5_Col = random.randint(0,10)
Bandit6_Row = random.randint(0,10)
Bandit6_Col = random.randint(0,10)
Bandit7_Row = random.randint(0,10)
Bandit7_Col = random.randint(0,10)
# For loop prints a new 12*12 grid after every move
for i in range(12):
b=[]
for j in range(12):
b.append(' ')
boardhard.append(b)
def table_game_hard():
print(" 1 2 3 4 5 6 7 8 9 10 11 12")
print("-------------------------------------------------")
print ('| ' + boardhard[0][0] + '| ' + boardhard[0][1] + ' | ' + boardhard[0][2] + ' | ' + boardhard[0][3] + ' | ' + boardhard[0][4] + ' | ' + boardhard[0][5] + ' | ' + boardhard[0][6] + ' | ' + boardhard[0][7] + ' | ' + boardhard[0][8] + ' | ' + boardhard[0][9] + ' | '+ boardhard[0][10] + ' | ' + boardhard[0][11] + ' | ' + '1')
print("-------------------------------------------------")
print ('| ' + boardhard[1][0] + '| ' + boardhard[1][1] + ' | ' + boardhard[1][2] + ' | ' + boardhard[1][3] + ' | ' + boardhard[1][4] + ' | ' + boardhard[1][5] + ' | ' + boardhard[1][6] + ' | ' + boardhard[1][7] + ' | ' + boardhard[1][8] + ' | ' + boardhard[1][9] + ' | '+ boardhard[1][10] + ' | ' + boardhard[1][11] + ' | ' + '2')
print("-------------------------------------------------")
print ('| ' + boardhard[2][0] + '| ' + boardhard[2][1] + ' | ' + boardhard[2][2] + ' | ' + boardhard[2][3] + ' | ' + boardhard[2][4] + ' | ' + boardhard[2][5] + ' | ' + boardhard[2][6] + ' | ' + boardhard[2][7] + ' | ' + boardhard[2][8] + ' | ' + boardhard[2][9] + ' | '+ boardhard[2][10] + ' | ' + boardhard[2][11] + ' | ' + '3')
print("-------------------------------------------------")
print ('| ' + boardhard[3][0] + '| ' + boardhard[3][1] + ' | ' + boardhard[3][2] + ' | ' + boardhard[3][3] + ' | ' + boardhard[3][4] + ' | ' + boardhard[3][5] + ' | ' + boardhard[3][6] + ' | ' + boardhard[3][7] + ' | ' + boardhard[3][8] + ' | ' + boardhard[3][9] + ' | '+ boardhard[3][10] + ' | ' + boardhard[3][11] + ' | ' + '4')
print("-------------------------------------------------")
print ('| ' + boardhard[4][0] + '| ' + boardhard[4][1] + ' | ' + boardhard[4][2] + ' | ' + boardhard[4][3] + ' | ' + boardhard[4][4] + ' | ' + boardhard[4][5] + ' | ' + boardhard[4][6] + ' | ' + boardhard[4][7] + ' | ' + boardhard[4][8] + ' | ' + boardhard[4][9] + ' | '+ boardhard[4][10] + ' | ' + boardhard[4][11] + ' | ' + '5')
print("-------------------------------------------------")
print ('| ' + boardhard[5][0] + '| ' + boardhard[5][1] + ' | ' + boardhard[5][2] + ' | ' + boardhard[5][3] + ' | ' + boardhard[5][4] + ' | ' + boardhard[5][5] + ' | ' + boardhard[5][6] + ' | ' + boardhard[5][7] + ' | ' + boardhard[5][8] + ' | ' + boardhard[5][9] + ' | '+ boardhard[5][10] + ' | ' + boardhard[5][11] + ' | ' + '6')
print("-------------------------------------------------")
print ('| ' + boardhard[6][0] + '| ' + boardhard[6][1] + ' | ' + boardhard[6][2] + ' | ' + boardhard[6][3] + ' | ' + boardhard[6][4] + ' | ' + boardhard[6][5] + ' | ' + boardhard[6][6] + ' | ' + boardhard[6][7] + ' | ' + boardhard[6][8] + ' | ' + boardhard[6][9] + ' | '+ boardhard[6][10] + ' | ' + boardhard[6][11] + ' | ' + '7')
print("-------------------------------------------------")
print ('| ' + boardhard[7][0] + '| ' + boardhard[7][1] + ' | ' + boardhard[7][2] + ' | ' + boardhard[7][3] + ' | ' + boardhard[7][4] + ' | ' + boardhard[7][5] + ' | ' + boardhard[7][6] + ' | ' + boardhard[7][7] + ' | ' + boardhard[7][8] + ' | ' + boardhard[7][9] + ' | '+ boardhard[7][10] + ' | ' + boardhard[7][11] + ' | ' + '8')
print("-------------------------------------------------")
print ('| ' + boardhard[8][0] + '| ' + boardhard[8][1] + ' | ' + boardhard[8][2] + ' | ' + boardhard[8][3] + ' | ' + boardhard[8][4] + ' | ' + boardhard[8][5] + ' | ' + boardhard[8][6] + ' | ' + boardhard[8][7] + ' | ' + boardhard[8][8] + ' | ' + boardhard[8][9] + ' | '+ boardhard[8][10] + ' | ' + boardhard[8][11] + ' | ' + '9')
print("-------------------------------------------------")
print ('| ' + boardhard[9][0] + '| ' + boardhard[9][1] + ' | ' + boardhard[9][2] + ' | ' + boardhard[9][3] + ' | ' + boardhard[9][4] + ' | ' + boardhard[9][5] + ' | ' + boardhard[9][6] + ' | ' + boardhard[9][7] + ' | ' + boardhard[9][8] + ' | ' + boardhard[9][9] + ' | '+ boardhard[9][10] + ' | ' + boardhard[9][11] + ' | ' + '10')
print("-------------------------------------------------")
print ('| ' + boardhard[10][0] + '| ' + boardhard[10][1] + ' | ' + boardhard[10][2] + ' | ' + boardhard[10][3] + ' | ' + boardhard[10][4] + ' | ' + boardhard[10][5] + ' | ' + boardhard[10][6] + ' | ' + boardhard[10][7] + ' | ' + boardhard[10][8] + ' | ' + boardhard[10][9] + ' | ' + boardhard[10][10] + ' | ' + boardhard[10][11] + ' | ' + '11')
print("-------------------------------------------------")
print ('| ' + boardhard[11][0] + '| ' + boardhard[11][1] + ' | ' + boardhard[11][2] + ' | ' + boardhard[11][3] + ' | ' + boardhard[11][4] + ' | ' + boardhard[11][5] + ' | ' + boardhard[11][6] + ' | ' + boardhard[11][7] + ' | ' + boardhard[11][8] + ' | ' + boardhard[11][9] + ' | ' + boardhard[11][11] + ' | ' + boardhard[11][11] + ' | ' + '12')
print("-------------------------------------------------")
Treasure1_Row = random.randint(0,12)
Treasure1_Col = random.randint(0,12)
Treasure2_Row = random.randint(0,12)
Treasure2_Col = random.randint(0,12)
Treasure3_Row = random.randint(0,12)
Treasure3_Col = random.randint(0,12)
Treasure4_Row = random.randint(0,12)
Treasure4_Col = random.randint(0,12)
Treasure5_Row = random.randint(0,12)
Treasure5_Col = random.randint(0,12)
Treasure6_Row = random.randint(0,12)
Treasure6_Col = random.randint(0,12)
Treasure7_Row = random.randint(0,12)
Treasure7_Col = random.randint(0,12)
Treasure8_Row = random.randint(0,12)
Treasure8_Col = random.randint(0,12)
Treasure9_Row = random.randint(0,12)
Treasure9_Col = random.randint(0,12)
Treasure10_Row = random.randint(0,12)
Treasure10_Col = random.randint(0,12)
Bandit1_Row = random.randint(0,12)
Bandit1_Col = random.randint(0,12)
Bandit2_Row = random.randint(0,12)
Bandit2_Col = random.randint(0,12)
Bandit3_Row = random.randint(0,12)
Bandit3_Col = random.randint(0,12)
Bandit4_Row = random.randint(0,12)
Bandit4_Col = random.randint(0,12)
Bandit5_Row = random.randint(0,12)
Bandit5_Col = random.randint(0,12)
Bandit6_Row = random.randint(0,12)
Bandit6_Col = random.randint(0,12)
Bandit7_Row = random.randint(0,12)
Bandit7_Col = random.randint(0,12)
Bandit8_Row = random.randint(0,12)
Bandit8_Col = random.randint(0,12)
Bandit9_Row = random.randint(0,12)
Bandit9_Col = random.randint(0,12)
#this function is in charge of downwards movement
def down(num,lev):
num=(num+current[0])%lev#The % formats this equation
current[0]=num
#this function is in charge of downwards movement
def right(num,lev):
num=(num+current[1])%lev #The % formats this equation
current[1]=num
#this function is in charge of downwards movement
def left(num,lev):
if current[1]-num>=0:
current[1]=current[1]-num
else:
current[1]=current[1]-num+lev
#this function is in charge of downwards movement
def up(num,lev):
if current[0]-num>=0:
current[0]=current[0]-num
else:
current[0]=current[0]-num+lev
def easy_level(Coins):
#This function is for the movement of the game in easy difficulty
while True:
oldcurrent=current
boardeasy[oldcurrent[0]][oldcurrent[1]]='*'
table_game_easy()
boardeasy[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 8 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:#Validates input
print('Wrong command, please input again')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),8)#Boundary is set to 8 as the 'easy' grid is a 8^8
elif n[0].lower()=='down':
down(int(n[1].lower()),8)
elif n[0].lower()=='left':
left(int(n[1].lower()),8)
elif n[0].lower()=='right':
right(int(n[1].lower()),8)
print("8 chests left")
print("8 bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if current[0] == Treasure1_Row and current[1] == Treasure1_Col\
or current[0] == Treasure2_Row and current[1] == Treasure2_Col\
or current[0] == Treasure3_Row and current[1] == Treasure3_Col\
or current[0] == Treasure4_Row and current[1] == Treasure4_Col\
or current[0] == Treasure5_Row and current[1] == Treasure5_Col\
or current[0] == Treasure6_Row and current[1] == Treasure6_Col\
or current[0] == Treasure7_Row and current[1] == Treasure7_Col\
or current[0] == Treasure8_Row and current[1] == Treasure8_Col:
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if current[0] == Bandit1_Row and current[1] == Bandit1_Col\
or current[0] == Bandit2_Row and current[1] == Bandit2_Col\
or current[0] == Bandit3_Row and current[1] == Bandit3_Col\
or current[0] == Bandit4_Row and current[1] == Bandit4_Col\
or current[0] == Bandit5_Row and current[1] == Bandit5_Col\
or current[0] == Bandit6_Row and current[1] == Bandit6_Col\
or current[0] == Bandit7_Row and current[1] == Bandit7_Col\
or current[0] == Bandit8_Row and current[1] == Bandit8_Col:
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardeasy[current[0]][current[1]]='*'#sets value to players position
def med_level(Coins):
#This function is for the movement of the game in medium difficulty
while True:
oldcurrent=current
boardmed[oldcurrent[0]][oldcurrent[1]]='*'
table_game_meduim()
boardmed[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 10 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:
print('wrong command')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),10)#Boundary is set to 10 as the 'easy' grid is a 10^10
elif n[0].lower()=='down':
down(int(n[1].lower()),10)
elif n[0].lower()=='left':
left(int(n[1].lower()),10)
elif n[0].lower()=='right':
right(int(n[1].lower()),10)
print("10 chests left")
print("10 bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if current[0] == Treasure1_Row and current[1] == Treasure1_Col\
or current[0] == Treasure2_Row and current[1] == Treasure2_Col\
or current[0] == Treasure3_Row and current[1] == Treasure3_Col\
or current[0] == Treasure4_Row and current[1] == Treasure4_Col\
or current[0] == Treasure5_Row and current[1] == Treasure5_Col\
or current[0] == Treasure6_Row and current[1] == Treasure6_Col\
or current[0] == Treasure7_Row and current[1] == Treasure7_Col\
or current[0] == Treasure8_Row and current[1] == Treasure8_Col\
or current[0] == Treasure9_Row and current[1] == Treasure9_Col\
or current[0] == Treasure10_Row and current[1] == Treasure10_Col:
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if current[0] == Bandit1_Row and current[1] == Bandit1_Col\
or current[0] == Bandit2_Row and current[1] == Bandit2_Col\
or current[0] == Bandit3_Row and current[1] == Bandit3_Col\
or current[0] == Bandit4_Row and current[1] == Bandit4_Col\
or current[0] == Bandit5_Row and current[1] == Bandit5_Col\
or current[0] == Bandit6_Row and current[1] == Bandit6_Col\
or current[0] == Bandit7_Row and current[1] == Bandit7_Col\
or current[0] == Bandit8_Row and current[1] == Bandit8_Col\
or current[0] == Bandit9_Row and current[1] == Bandit9_Col\
or current[0] == Bandit10_Row and current[1] == Bandit10_Col:
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardmed[current[0]][current[1]]='*'
def hard_level(Coins):
#This function is for the movement of the game in hard difficulty
while True:
oldcurrent=current
boardhard[oldcurrent[0]][oldcurrent[1]]='*'
table_game_hard()
boardhard[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 12 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:
print('wrong command')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),12)#Boundary is set to 12 as the 'hard' grid is a 12^12
elif n[0].lower()=='down':
down(int(n[1].lower()),12)
elif n[0].lower()=='left':
left(int(n[1].lower()),12)
elif n[0].lower()=='right':
right(int(n[1].lower()),12)
print("12 chests left")
print("12 bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if current[0] == Treasure1_Row and current[1] == Treasure1_Col\
or current[0] == Treasure2_Row and current[1] == Treasure2_Col\
or current[0] == Treasure3_Row and current[1] == Treasure3_Col\
or current[0] == Treasure4_Row and current[1] == Treasure4_Col\
or current[0] == Treasure5_Row and current[1] == Treasure5_Col\
or current[0] == Treasure6_Row and current[1] == Treasure6_Col\
or current[0] == Treasure7_Row and current[1] == Treasure7_Col\
or current[0] == Treasure8_Row and current[1] == Treasure8_Col\
or current[0] == Treasure9_Row and current[1] == Treasure9_Col\
or current[0] == Treasure10_Row and current[1] == Treasure10_Col\
or current[0] == Treasure11_Row and current[1] == Treasure11_Col\
or current[0] == Treasure12_Row and current[1] == Treasure12_Col:
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if current[0] == Bandit1_Row and current[1] == Bandit1_Col\
or current[0] == Bandit2_Row and current[1] == Bandit2_Col\
or current[0] == Bandit3_Row and current[1] == Bandit3_Col\
or current[0] == Bandit4_Row and current[1] == Bandit4_Col\
or current[0] == Bandit5_Row and current[1] == Bandit5_Col\
or current[0] == Bandit6_Row and current[1] == Bandit6_Col\
or current[0] == Bandit7_Row and current[1] == Bandit7_Col\
or current[0] == Bandit8_Row and current[1] == Bandit8_Col\
or current[0] == Bandit9_Row and current[1] == Bandit9_Col\
or current[0] == Bandit10_Row and current[1] == Bandit10_Col\
or current[0] == Bandit11_Row and current[1] == Bandit11_Col\
or current[0] == Bandit12_Row and current[1] == Bandit12_Col:
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardhard[current[0]][current[1]]='*'
def instruct():
difficulty = input("""Before the game starts, please consider what difficulty
would you like to play in, easy, medium or (if you're brave) hard.
""")
if difficulty == "easy":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
easy_level(Coins)
elif difficulty == "medium":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
med_level(Coins)
elif difficulty == "hard":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
hard_level(Coins)
else:
print("Sorry, that is an invalid answer. Please restart the programme")
def menu():
#This function lets the user quit the application or progress to playing.
print("")
print ("Are you sure you wish to play this game? Please answer either yes or no.")
choice1 = input() # Sets variable to user input
if choice1.lower().startswith('y'):
print("Okay lets continue then!")
elif choice1.lower().startswith('n'):
print("Thank you, I hope you will play next time!")
print("")
quit("Thank you for playing!")#Terminates the programme
else:
print("Sorry, that is an invalid answer. Please restart the programme")
print("")
quit()
instruct()
def showInstructions():
time.sleep(1.0)
print("Instructions of the game:")
time.sleep(1.0)
print("""
You are a treasure hunter, your goal is to collect atleast 100 gold by the end
of the game from treasure chests randomly scattered across the grid. There are
10 chests within a grid (this can be changed based on difficulty) and each
treasure chest is worth 10 gold but can only be reclaimed 3 times before it is
replaced by a bandit. Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then
100 gold this means you lose!
Press enter to continue...""")
input()
print("""
At the start of the game, you always begin at the top right of the grid.
Below is a representation of the game:
* 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Press enter to continue...""")
input()
print("""
When deciding where to move, you should input the direct co-ordinates of your
desired location. For instance:
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
right 3
0 0 0 * 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Unlucky move! You have found nothing!
If nothing on the grid changes , this means that your move was a bust! Landing
on nothing isn't displayed on the grid.
Press enter to continue...""")
input()
print("""
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
down 4
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Hooray! You have found booty! +10 gold
Here you can see that the use has landed on a chest!
As you land on chest, they get replaced by bandits. Be sure to remember the
previous locations so you don't accidently land on a bandit and lose all
your gold!
Press enter to continue...""")
input()
#Introduces the user
print('Welcome to the Treasure hunt!')
time.sleep(0.3)
print()
time.sleep(0.3)
print('Would you like to see the instructions? (yes/no)')
if input().lower().startswith('y'):#If function checks for the first letter
showInstructions()
elif input == 'no' or 'No':
print("Lets continue then!")#Calls the function which displays instructions
else:
print("Please check your input and try again.")
menu()
</code></pre>
| [] | [
{
"body": "<p>Generally, when reading your code, I think you need to consider the <a href=\"https://en.wikipedia.org/wiki/Don't_repeat_yourself\" rel=\"nofollow noreferrer\">DRY principle</a>. I will elaborate on this through several specific examples, but it's generally a good thing to keep in mind and und... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T12:43:23.040",
"Id": "207718",
"Score": "1",
"Tags": [
"python",
"game"
],
"Title": "Python Treasure hunt board game"
} | 207718 |
<p>The scenario is the following. I get the string from an HTML element via outerHTML and I need to convert the 'rgb(r, g, b)' part into the hexadecimal representation. I tried this with regex and it seems to work but I have a feeling there are better ways to deal with this. </p>
<p>One particular thing I don't like is where I directly access <code>color[1]</code> from my regex match. I'm open to any feedback.</p>
<pre><code>private cleanupRichText(richText: string) {
const rx = /rgb\((.+?)\)/ig
const color = rx.exec(richText)
if (color !== null) {
const hexparts = color[1].split(',').map(str => parseInt(str.trim(), 10).toString(16))
let hexString = '#'
hexparts.forEach(element => {
hexString += element.length === 1 ? '0' + element : element })
text = text.replace(/rgb\(.+?\)/ig, hexString)
}
}
</code></pre>
<p>To give an example input:</p>
<pre><code>'rgb(234, 112, 30)'
</code></pre>
<p>Expected output:</p>
<pre><code>'#ea701e'
</code></pre>
| [] | [
{
"body": "<p>While the given function does work for simple cases, it will <em>not</em> perform as expected if there are multiple colors within <code>richText</code>. The first color will override all other colors.</p>\n\n<p>First, a look at your implementation:</p>\n\n<ol>\n<li><p>Why is <code>richText</code> ... | {
"AcceptedAnswerId": "207846",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T12:55:53.243",
"Id": "207721",
"Score": "2",
"Tags": [
"typescript"
],
"Title": "Convert 'rgb()' string to hex string"
} | 207721 |
<p>I'm trying to make a carousel with jQuery and I want to know, how to simplify the code further? so... this is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
$(".cont-btn button").click(function (event) {
var detectId = event.target.id;
$(".cont-btn button").removeClass("active");
$(this).addClass("active");
for (i = 1; i <= 4; i++) {
if (detectId === ("btn" + i) && i === 1) {
$(".cont-img div").css("left", "0%");
} else if (detectId === ("btn" + i)) {
$(".cont-img div").css("left", "-" + (i - 1) + "00%");
}
}
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
width: 100%;
margin: 0;
padding: 0;
}
.carousel {
width: 100%;
height: 150px;
position: relative;
overflow: hidden;
}
.carousel .cont-img {
width: 100%;
height: 100%;
}
.carousel .cont-img div {
width: 100%;
height: 100%;
position: absolute;
left: 0;
background-color: aqua;
transition: left .75s ease-in-out;
}
.carousel .cont-img div:nth-of-type(2) {
background-color: aquamarine;
margin-left: 100%;
}
.carousel .cont-img div:nth-of-type(3) {
background-color: blueviolet;
margin-left: 200%;
}
.carousel .cont-img div:nth-of-type(4) {
background-color: cornflowerblue;
margin-left: 300%;
}
.carousel .cont-btn {
position: absolute;
bottom: 18px;
left: 50%;
transform: translateX(-50%);
cursor: default;
}
.carousel .cont-btn button {
width: 18px;
height: 18px;
background-color: transparent;
border: 2px solid #000;
border-radius: 100%;
margin: 0 5px;
padding: 0;
outline: none;
transition: background-color .25s ease-in-out;
cursor: pointer;
}
.carousel .cont-btn .active {
background-color: #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="carousel">
<div class="cont-img">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="cont-btn">
<button type="button" id="btn1" class="active"></button>
<button type="button" id="btn2"></button>
<button type="button" id="btn3"></button>
<button type="button" id="btn4"></button>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Thank you very much in advance to anyone who can help me.</p>
| [] | [
{
"body": "<p>I like it.</p>\n\n<p>There are only a few things I would reconsider:</p>\n\n<ol>\n<li><code>detectedId</code> is a clunky name, <code>clickedId</code> or <code>selectedId</code> seems better</li>\n<li>You hardcode <code>4</code>, at least use a constant, ideally detect how many buttons there dynam... | {
"AcceptedAnswerId": "207793",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T15:32:00.990",
"Id": "207727",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Image carousel with jQuery 3.3.1"
} | 207727 |
<p>The Microsoft OCR API returns json, and if I want to extact the text data from this json:</p>
<pre><code>response = \
{
"language": "en",
"textAngle": -2.0000000000000338,
"orientation": "Up",
"regions": [
{
"boundingBox": "462,379,497,258",
"lines": [
{
"boundingBox": "462,379,497,74",
"words": [
{
"boundingBox": "462,379,41,73",
"text": "A"
},
{
"boundingBox": "523,379,153,73",
"text": "GOAL"
},
{
"boundingBox": "694,379,265,74",
"text": "WITHOUT"
}
]
},
{
"boundingBox": "565,471,289,74",
"words": [
{
"boundingBox": "565,471,41,73",
"text": "A"
},
{
"boundingBox": "626,471,150,73",
"text": "PLAN"
},
{
"boundingBox": "801,472,53,73",
"text": "IS"
}
]
},
{
"boundingBox": "519,563,375,74",
"words": [
{
"boundingBox": "519,563,149,74",
"text": "JUST"
},
{
"boundingBox": "683,564,41,72",
"text": "A"
},
{
"boundingBox": "741,564,153,73",
"text": "WISH"
}
]
}
]
}
]
}
</code></pre>
<pre><code>def check_for_word(ocr):
# Initialise our subject to None
print("OCR: {}".format(ocr))
subject = None
for region in ocr["regions"]:
if "lines" in region:
for lines in region["lines"]:
if "words" in lines:
for word in lines["words"]:
if "text" in word:
subject = word["text"].lower()
break
print("OCR word is {}".format(subject))
return subject
print(response["regions"][0]["lines"][0]["words"][0]["text"]) # Should return this
print(check_for_word(response))
</code></pre>
<ul>
<li>Each dictionary has arrays and we are unsure if the array contains any element</li>
<li>Also not sure if the dictionary has key</li>
</ul>
<p>Let's say we just wish to return the first text it matched from the image file. </p>
<p>This code works but it has a deep nested structure that has bad smell. Is there a better practice to write this in a cleaner way?</p>
| [] | [
{
"body": "<p>One way to almost halve the number of lines (and levels of indentation) needed is to use <code>dict.get</code> with <code>[]</code> as the optional default option:</p>\n\n<pre><code>def check_for_word(ocr):\n for region in ocr[\"regions\"]:\n for lines in region.get(\"lines\", []):\n ... | {
"AcceptedAnswerId": "207740",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T16:19:00.473",
"Id": "207733",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Retrieve recognised text from JSON returned by Microsoft OCR"
} | 207733 |
<p>I am pretty much a python newbie and was looking at this <a href="https://stackoverflow.com/questions/53320572/scrapy-to-get-into-next-page-and-download-all-files">question</a> on StackOverflow.</p>
<p>Whereas the OP was interested in downloading the <code>.htm |.txt</code> files, I was simply interested in using <code>Beautiful Soup</code> and <code>requests</code> to gather all the links, to those files, into one structure. Ideally, it would have been a single list but I have a list of lists.</p>
<p>The process is: </p>
<ol>
<li><p>Start with the <a href="https://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK=&filenum=&State=&Country=&SIC=2834&owner=exclude&Find=Find+Companies&action=getcompany" rel="nofollow noreferrer">landing page</a> and grab all the links in the leftmost column which has the header <code>CIK</code>. </p>
<p><sub><strong>CIK column sample with single link selected on right</strong></sub></p>
<p><img src="https://i.stack.imgur.com/arBIg.png" width="500"></p></li>
</ol>
<p><br></p>
<ol start="2">
<li><p>Navigate to each of those links and grab the document button links in the <code>Format</code> column:</p>
<p><sub><strong>Format column sample with single link selected on right</strong></sub></p>
<p><img src="https://i.stack.imgur.com/a5hgH.png" width="500"></p></li>
</ol>
<p><br></p>
<ol start="3">
<li><p>Navigate to each of those document button links and grab the document links in the <code>Document Format Files</code> section, if the file mask is <code>.htm | .txt</code>.</p>
<p><sub><strong>Document Format Files sample with single link selected on right</strong></sub></p>
<p><img src="https://i.stack.imgur.com/qmVey.png" width="500"></p></li>
</ol>
<p><br></p>
<ol start="4">
<li>Print the list of links (which is a list of lists)</li>
</ol>
<hr>
<p><strong>Other info:</strong></p>
<p>I use CSS selectors throughout to target the links.</p>
<p>What particularly concerns me, given my limited Python experience, is the fact I have a list of lists rather than a single list, whether my re-use of variable names is confusing and potentially bug prone, and I guess whether what I am doing is particularly pythonic and efficient.</p>
<p>In languages I am more familiar with, I might attempt to create a class and provide the class with methods; which in effect are my current functions. </p>
<hr>
<p><strong>Set-up info:</strong></p>
<p>The version of the jupyter notebook server is: 5.5.0</p>
<p>The server is running on this version of Python:</p>
<p>Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]</p>
<hr>
<p><strong>Python code:</strong></p>
<pre><code>from bs4 import BeautifulSoup
import requests
from urllib.parse import urljoin
base = 'https://www.sec.gov'
start_urls = ["https://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK=&filenum=&State=&Country=&SIC=2834&owner=exclude&Find=Find+Companies&action=getcompany"]
def makeSoup(url):
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
return soup
def getLinks(pattern):
links = soup.select(pattern)
return links
def getFullLink(links):
outputLinks = []
for link in links:
outputLinks.append(urljoin(base, link.get("href")))
return outputLinks
soup = makeSoup(start_urls[0])
links = getLinks("#seriesDiv [href*='&CIK']")
firstLinks = getFullLink(links)
penultimateLinks = []
for link in firstLinks:
soup = makeSoup(link)
links = getLinks('[id=documentsbutton]')
nextLinks = getFullLink(links)
penultimateLinks.append(nextLinks)
finalLinks = []
for link in penultimateLinks:
for nextLink in link:
soup = makeSoup(nextLink)
links = getLinks("[summary='Document Format Files'] td:nth-of-type(3) [href$='.htm'],td:nth-of-type(3) [href$='.txt']")
nextLinks = getFullLink(links)
finalLinks.append(nextLinks)
print(finalLinks)
</code></pre>
| [] | [
{
"body": "<p>Since you never use <code>getLinks</code> without a call to <code>getFullLink</code> afterwards, I would merge these two functions. I would also make it a generator:</p>\n\n<pre><code>def get_links(soup, pattern):\n for link in soup.select(pattern):\n yield urljoin(base, link.get(\"href\... | {
"AcceptedAnswerId": "207747",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T16:22:13.083",
"Id": "207734",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Crawling pages to obtain .htm and .txt files from sec.gov"
} | 207734 |
<p>I have a project where I work with digital addresses for a Programmable Logic Controller (PLC). The requirement is that the user gives a start address e.g. 1000.0 and then for example the next 20 things are numbered in increasing order.</p>
<p>In this example this would mean:</p>
<p>1000.0 <br>
1000.1 <br>
1000.2 <br>
1000.3 <br>
1000.4 <br>
1000.5 <br>
1000.6 <br>
1000.7 <br>
1001.0 <br>
1001.1 <br>
1001.2 <br>
1001.3 <br>
1001.4 <br>
1001.5 <br>
1001.6 <br>
1001.7 <br>
1002.0 <br>
1002.1 <br>
1002.2 <br>
1002.3 <br></p>
<p>Also I want to prevent that invalid addresses can be created at the start like 1000.8</p>
<p>To accomplish this behaviour I created a class <code>Digital_plc_address</code>. I would like to know what can be improved. Are there any bad styles in it?</p>
<p>Is it good practice to make a class to report invalid_input errors when the class cannot be created?</p>
<p>I did some quick checks of the class in main. I know I could have done better with unit tests but I thought for this small class it's okay to check it like this.</p>
<p><b> digital_plc_adress.h </b></p>
<pre><code>#ifndef DIGITAL_PLC_ADDRESS_GUARD151120181614
#define DIGITAL_PLC_ADDRESS_GUARD151120181614
#include <string>
namespace digital_plc_address {
class Digital_plc_address {
/*
Class representing a digital plc address.
Each address is represented by a byte address and the digits of the
bytes from 0-7. e.g 100.6 , 5.2
Creating invalid addresses like 100.8 is not allowed by the class.
*/
public:
Digital_plc_address(int byte, char digit = 0);
explicit Digital_plc_address(const std::string& Digital_plc_address);
class Invalid_format {};
std::string as_string() const;
Digital_plc_address& operator++();
private:
int m_byte;
char m_digit;
};
}
#endif
</code></pre>
<p><b> digital_plc_address.cpp </b></p>
<pre><code>#include "digital_plc_address.h"
#include <regex>
#include <sstream>
#include <cctype>
#include <limits>
namespace digital_plc_address {
Digital_plc_address::Digital_plc_address(int byte, char digit)
:m_byte{ byte }, m_digit{ digit }
{
if (m_byte < 0 || m_byte > std::numeric_limits<decltype(m_byte)>::max()
|| m_digit < 0 || m_digit > 7) {
throw Invalid_format{};
}
}
Digital_plc_address::Digital_plc_address(const std::string& Digital_plc_address)
{
std::regex valid_format(R"(\d+\.[0-7]{1})");
if (!std::regex_match(Digital_plc_address, valid_format)) {
throw Invalid_format{};
}
std::istringstream ist{ Digital_plc_address };
std::string byte_str;
std::getline(ist, byte_str, '.');
m_byte = std::stoi(byte_str);
m_digit = Digital_plc_address.back() - '0';
}
std::string Digital_plc_address::as_string() const
{
return std::to_string(m_byte) + '.' + std::to_string(m_digit);
}
Digital_plc_address& Digital_plc_address::operator++()
{
if (m_digit == 7) {
m_digit = 0;
++m_byte;
}
else {
++m_digit;
}
return *this;
}
}
</code></pre>
<p><b> main.cpp </b></p>
<pre><code>#include "digital_plc_address.h"
#include <iostream>
void print_io(int a)
{
try {
digital_plc_address::Digital_plc_address t{ a };
std::cout << t.as_string() << '\n';
}
catch (digital_plc_address::Digital_plc_address::Invalid_format) {
std::cout << "Invalid input: " << a << '\n';
}
}
void print_io(int a, char b)
{
try {
digital_plc_address::Digital_plc_address t{ a,b };
std::cout << t.as_string() << '\n';
}
catch (digital_plc_address::Digital_plc_address::Invalid_format) {
std::cout << "Invalid input: " << a << '\t' << b <<'\n';
}
}
void print_io(const std::string& s)
{
try {
digital_plc_address::Digital_plc_address t{ s };
std::cout << t.as_string() << '\n';
}
catch (digital_plc_address::Digital_plc_address::Invalid_format) {
std::cout << "Invalid input: " << s << '\n';
}
}
int main()
try{
digital_plc_address::Digital_plc_address inc{ 10 };
for (int i = 0; i < 20; ++i) {
++inc;
std::cout << inc.as_string() << '\n';
}
print_io(100);
print_io(100, 1);
print_io(50, 7);
print_io("100");
print_io("100.1");
print_io("50.7");
print_io("-50.7");
print_io("50.-7");
print_io("50.8");
std::getchar();
}
catch (digital_plc_address::Digital_plc_address::Invalid_format) {
std::cout << "error";
std::getchar();
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Obviously, negative (sub-) addresses are invalid - so I would prefer unsigned types for, and you can spare the checks for negative range as well.</p></li>\n<li><p><code>std::numeric_limits<decltype(m_byte)>::max()</code> might exceed the range of addresses of your PLC (or not cover... | {
"AcceptedAnswerId": "207782",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T16:39:56.040",
"Id": "207737",
"Score": "2",
"Tags": [
"c++",
"iterator",
"c++17"
],
"Title": "Class representing digital PLC address"
} | 207737 |
<p>I have this array <code>const idArray = ["12", "231", "73", "4"]</code> and an object</p>
<pre><code>const blueprints = {
12: {color: red, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
231: {color: white, views: [{name: "front}, {name: "back}]},
73: {color: black, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
4: {color: silver, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
}
</code></pre>
<p>How can I return an array of the following objects that have all front, back, top, and bottom using ES6 map/filter/some and etc?:</p>
<pre><code>result =[
{colorId: "12", views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]}
{colorId: "73", views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]}
{colorId: "4", views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]}
]
</code></pre>
<p>I did it here but I feel like it is too messy and hard to read. Anybody could recommend on how to shorten it and make it easier to read using the ES6 functions (map, filter ...)?</p>
<pre><code>const result = idArray.map(id => {
const bluePrint = bluePrints[id];
const exists = bluePrint.views.some(view => view.name === 'top' || view.name === 'bottom');
if (exists) {
return {
colorId: id,
views: bluePrint.views
}
}
}).filter(bluePrint => bluePrint);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T18:49:31.350",
"Id": "401010",
"Score": "2",
"body": "You have some mismatched quotes in your JSON?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T19:30:11.770",
"Id": "401029",
"Score": "1",... | [
{
"body": "<p>The initial data is not formatted as proper JSON. There appear to be mismatched quotes around values like <code>front</code>, <code>back</code>, etc... try running the snippet below to see the error that is caused by this.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-co... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T18:42:58.377",
"Id": "207744",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"iteration"
],
"Title": "Extracting data in ES6"
} | 207744 |
<p>I'm building an app where the user can press play and then the app will scroll through some musical notes (like sheet music). I use a timer and counter to move the view along. The code works ok, except that every time I press play to start the view scrolls at a different speed. The first time is very slow but it gets to the speed I want after playing through a few times. I assume this is because as I repeat the action, iOS loads things into memory and is able to run things faster and smoother. </p>
<p>Is there some way to speed things up, or perhaps there is a different approach than using a UIScrollView for something it wasn't really designed for? Any ideas are much appreciated!</p>
<pre><code>import UIKit
class TimelineViewController: UIViewController {
var screenHeight = UIScreen.main.bounds.height
var screenWidth = UIScreen.main.bounds.width
var scrollView = UIScrollView()
let canvasWidth = 7204
var counter = 0
var timer = Timer()
func setupScrollView() {
scrollView.frame = self.view.bounds
let scrollImageView = UIView()
scrollImageView.frame = CGRect(x: 0, y: 0, width: canvasWidth, height: Int(screenHeight))
scrollView.contentSize = scrollImageView.bounds.size
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.backgroundColor = .black
scrollView.addSubview(scrollImageView)
self.view.addSubview(scrollView)
}
@objc func updateTime() {
DispatchQueue.global(qos: .default).async {
let counterStop = self.canvasWidth-(Int(self.screenWidth))
guard self.counter < counterStop else {return}
self.counter += 1
}
UIView.animate(withDuration: 0.1, animations: {
self.scrollView.setContentOffset(CGPoint(x: self.counter, y: 0), animated: false)
})}
@IBAction func startPlayhead(_ sender: Any) {
print("Play pressed")
counter = 0
let tempoSetter = 0.03
timer = Timer.scheduledTimer(timeInterval: tempoSetter, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
override func viewDidLoad() {
super.viewDidLoad()
setupScrollView()
var measureMarkerCoords: [Int] = [600,1200,1800,2400,3000,3600,4200, 4800, 5400, 6000, 6600,7200]
var colourOrder: [UIColor] = [UIColor.red,UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple, UIColor.red,UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple]
for i in 0...11 {
let measureMarker = UIView(frame:CGRect(x:measureMarkerCoords[i],y:0,width:4,height:Int(screenHeight)))
measureMarker.backgroundColor = colourOrder[i]
self.scrollView.addSubview(measureMarker)
}
let playButton = UIButton(frame: CGRect(x: 10, y: 5, width: 44, height: 44))
playButton.setTitle("Play", for: .normal)
playButton.addTarget(self, action: #selector(startPlayhead(_:)), for: .touchUpInside)
view.addSubview(playButton)
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T19:51:05.383",
"Id": "207750",
"Score": "1",
"Tags": [
"performance",
"swift",
"ios"
],
"Title": "Side Scrolling App Too Slow (using UIScrollView)"
} | 207750 |
<p>I've been practicing recursion lately and wrote this code to get <a href="https://en.wikipedia.org/wiki/Pascal%27s_triangle" rel="nofollow noreferrer">Pascal's triangle</a> recursively.</p>
<p>How would you guys improve it ?</p>
<p>I don't really like the fact that the recursion goes for <code>n+1</code> steps.</p>
<pre><code>def RecPascal(n, m=1, prev=[]):
if m > n+1:
return []
elif m == 1:
return RecPascal(n, m+1 , [1])
else:
return [prev] + RecPascal(n, m+1, calculate(prev))
def calculate(prev):
res = [0]*(len(prev)+1)
res[0], res[-1] = 1, 1
for i in range(0,len(res)):
if res[i] == 0:
res[i] = prev[i-1] + prev[i]
return res
for line in RecPascal(10):
print(line)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-16T12:28:11.850",
"Id": "401174",
"Score": "0",
"body": "I would recommend reading [accepted answers](https://codereview.stackexchange.com/help/accepted-answer) and accepting an answer. It's not required, but it's a nice way to show ap... | [
{
"body": "<p>Similar to your <a href=\"https://codereview.stackexchange.com/questions/207416/pouring-water-between-two-jugs-to-get-a-certain-amount-in-one-of-the-jugs-2\">Water Jug</a> solution, this is still not a good recursive algorithm/implementation. But we can still critic it, and provide useful feedbac... | {
"AcceptedAnswerId": "207776",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T21:40:37.710",
"Id": "207757",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"recursion"
],
"Title": "Getting Pascal's triangle recursively in Python"
} | 207757 |
<h1>Introduction</h1>
<p>This question was asked in a technical interview, I am looking for some feedback on my solution.</p>
<p>Given a list of integers and a number K, return which contiguous
elements of the list sum to K. For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it
should return [2, 3, 4].</p>
<h1>The Ask</h1>
<p>My solution works with my test cases, but I would like feedback on <em>how others would approach the problem</em> and where my code could be altered to improve efficiency and runtime. Currently, I have a nested for loop and I believe my solution is <strong>O(n<sup>2</sup>)</strong>.</p>
<h1>Solution</h1>
<pre><code>def contigSum(nums, k):
for i, num in enumerate(nums):
accum = 0
result = []
# print(f'Current index = {i}')
# print(f'Starting value = {num}')
for val in nums[i:len(nums)]:
# print(f'accum = {accum}')
result.append(val)
# print(f'accum = {accum} + {val}')
accum += val
if accum == k:
print(f'{result} = {k}')
return 0
# else:
# print(f'accum = {accum}')
print('No match found')
return 1
</code></pre>
<h1>Test Cases</h1>
<pre><code>nums0 = []
k0 = None
contigSum(nums0, k0)
nums6 = [1, 2, 3]
k6 = 99
contigSum(nums6, k6)
nums1 = [1, 2, 3, 4, 5]
k1 = 9
contigSum(nums1, k1)
nums2 = [-1, -2, -3]
k2 = -6
contigSum(nums2, k2)
nums4 = [5, 2, 6, 11, 284, -25, -2, 11]
k4 = 9
contigSum(nums4, k4)
nums5 = [10, 9, 7, 6, 5, 4, 3, 2 ,1]
k5 = 20
contigSum(nums5, k5)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T21:44:42.143",
"Id": "401073",
"Score": "1",
"body": "Why is *Lyft* part of your title as it's mentioned nowhere in the question? Also, why isn't [4,5] a valid answer if K is 9?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"C... | [
{
"body": "<h2>Unused code</h2>\n<p><code> for i, num in enumerate(nums):</code>, the <code>i</code> variable is used in your commented code, but commented code shouldn't exist, so <code>i</code> shouldn't exist either.</p>\n<p>To come back on the commented code, I hope you didn't submit your solution with thes... | {
"AcceptedAnswerId": "207760",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T21:43:42.953",
"Id": "207758",
"Score": "3",
"Tags": [
"python",
"algorithm",
"interview-questions"
],
"Title": "Find contiguous integers with a given sum"
} | 207758 |
<p>After understanding HashMaps, I decided to implement my own using 3 classes HashMap, LinkedList, and Node. I knew how to implement LinkedList from before.</p>
<p>Can you please give me feedback on this. Will this be an acceptable implementation for a technical interview?</p>
<p>Also do we actually need to implement the data structure needed to solve the problem or use the language library?</p>
<pre><code>public class HashMap<K, V> {
LinkedList<K, V>[] buckets;
HashMap(int size) {
buckets = new LinkedList[size];
}
public void insert(K key, V value) {
Node<K, V> newNode = new Node<>(key, value);
int bucket = getIndex(key);
//Create bucket if it does not exist.
if(buckets[bucket] == null) {
buckets[bucket] = new LinkedList<>();
}
buckets[bucket].insert(newNode);
}
public void delete(K key) {
int bucket = getIndex(key);
if(buckets[bucket] == null) {
System.out.println("Hashmap is empty.");
return;
}
buckets[bucket].delete(key);
}
public Node find(K key) {
int bucket = getIndex(key);
return buckets[bucket].find(key);
}
public int getIndex(K key) {
return key.hashCode() % buckets.length;
}
@Override
public String toString() {
String data = "";
for(int i = 0; i < buckets.length; i++) {
if(buckets[i] != null) {
data += "[" + i + "]" + " = " + buckets[i].toString() + " null";
data += "\n";
}
}
return data;
}
}
public class LinkedList<K, V> {
Node<K, V> head;
public void insert(Node<K, V> newNode) {
if(head == null) {
head = newNode;
return;
}
Node<K, V> current = head;
while(current.getNext() != null)
current = current.getNext();
current.setNext(newNode);
}
public void delete(K key) {
if(head == null)
return;
//If head to be deleted.
if(head.getKey() == key) {
head = head.getNext();
return;
}
Node current = head;
while(current.getNext().getKey() != key)
current = current.getNext();
current.setNext(current.getNext().getNext());
}
public Node find(K key) {
Node current = head;
//While not reached end or not found keep going.
while(current != null && current.getKey() != key) {
current = current.getNext();
}
//Returns null if not found.
return current;
}
@Override
public String toString() {
String data = "";
Node current = head;
while(current != null) {
data += "(" + current.getKey() + ", " + current.getValue() + ")" + " -> ";
current = current.getNext();
}
return data;
}
}
public class Node<K, V> {
private K key;
private V value;
private Node<K, V> next;
Node(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class HashMapTesting {
public static void main(String[] args) {
HashMap<String, Integer> ages = new HashMap<>(5);
//Testing insertion
ages.insert("Reda", 22);
ages.insert("Mike", 34);
ages.insert("Tom", 55);
ages.insert("Daniel", 32);
ages.insert("Leonardo", 42);
System.out.println(ages.toString());
//Testing search
System.out.println(ages.find("Daniel").getValue() + "\n");
//Testing deletion
ages.delete("Mike");
System.out.println(ages.toString());
}
}
</code></pre>
<p>Output:</p>
<pre><code>[0] = (Reda, 22) -> (Mike, 34) -> null
[2] = (Leonardo, 42) -> null
[4] = (Tom, 55) -> (Daniel, 32) -> null
32
[0] = (Reda, 22) -> null
[2] = (Leonardo, 42) -> null
[4] = (Tom, 55) -> (Daniel, 32) -> null
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T23:24:36.793",
"Id": "401096",
"Score": "1",
"body": "The moment an interviewee would proudly tell me how they implemented their own `HashMap`, I'd extend my hand, wish them all the best and say goodbye."
},
{
"ContentLicens... | [
{
"body": "<ul>\n<li><p><code>LikedList::insert</code> is suboptimal. It requires an entire list to be traversed. Since you don't case about the order it is much simpler to always prepend a new node:</p>\n\n<pre><code> newNode.setNext(head);\n head = newNode;\n</code></pre>\n\n<p>If you for some reason <e... | {
"AcceptedAnswerId": "207882",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T23:09:48.527",
"Id": "207763",
"Score": "1",
"Tags": [
"java",
"linked-list",
"interview-questions",
"reinventing-the-wheel",
"hash-map"
],
"Title": "HashMap implementation, is this good enough for interviews?"
} | 207763 |
<p>Here is my code for implementing Graph using adjacency matrix. The code should be Object-oriented and there is a method <code>isPath()</code> checking if there is a connection between two nodes. Some advice?</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
class Graph
{
protected:
int value;
int **graphm;
public:
Graph(int value)
{
this->value = value;
graphm = new int*[value];
int k, j;
for (k = 0; k < value; k++)
{
graphm[k] = new int[value];
for (j = 0; j < value; j++)
{
graphm[k][j] = 0;
}
}
}
void newEdge(int head, int end)
{
if (head > value || end > value || head < 0 || end < 0)
{
cout << "Invalid edge!\n";
}
else
{
graphm[head - 1][end - 1] = 1;
graphm[end - 1][head - 1] = 1;
}
}
void display()
{
int i, p;
for (i = 0; i < value; i++)
{
for (p = 0; p < value; p++)
{
cout << graphm[i][p] << " ";
}
cout << endl;
}
}
void isPath(int head, int end)
{
int k, o;
ofstream fullstore("Test.txt");
cout << graphm[head - 1][end - 1];
cout << endl;
if (!fullstore.is_open())
{
cout << "File can't be open";
}
if (graphm[head - 1][end - 1] == 1)
{
cout << "There is an edge between " << head << " and " << end << "\n";
fullstore << head << ", " << end;
fullstore.close();
}
else
{
cout << "Edge not found\n";
}
}
};
int main()
{
int vertex, numberOfEdges, i, head, end;
cout << "Enter number of nodes: ";
cin >> vertex;
numberOfEdges = vertex * (vertex - 1);
Graph g1(vertex);
for (int i = 0; i < numberOfEdges; i++)
{
cout << "Enter edge ex.1 2 (-1 -1 to exit): \n";
cin >> head >> end;
if ((head == -1) && (end == -1))
{
break;
}
g1.newEdge(head, end);
}
g1.display();
cout << endl;
g1.isPath(1, 3);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice?s=1|1164.7147\">Avoid</a> <code>using namespace std;</code>.</p>\n\n<p>Why are you using raw pointers? Use smart pointers, or (better yet) standard containers like <code>std::vector</code>. S... | {
"AcceptedAnswerId": "207771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T23:38:36.083",
"Id": "207766",
"Score": "5",
"Tags": [
"c++",
"graph"
],
"Title": "Graph implementation in c++ using adjacency matrix"
} | 207766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.