How to write Junit for java - junit4

I am very new to junit and java. kindly let me know how write the junit for this code.
void Abc(Objsect o) {
Attr[] attrd= o.changeAttr();
if (attrd.length > 0) {
for (int i = 0; i < attrd.length; i++) {
if (attrd[i].toString().contains(PropertyMessage.fsc_pra)) {
ifModified = true;
}
}
}
}

Related

Convert DEC to IP dart

I get a int32 : -1407942911 that I need to convert to a ip
I used this function:
_setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip >> 8;
}
return _strData.toString();
}
but I get the ip backwards: 1.127.20.172 instead of 172.20.127.1
I was trying to replicate this java code
public String longToIp(long ip) {
StringBuilder result = new StringBuilder(15);
for (int i = 0; i < 4; i++) {
result.insert(0,Long.toString(ip & 0xff));
if (i < 3) {
sb.insert(0,'.');
}
ip = ip >> 8;
}
return result.toString();
}
Update
I solved the error
static setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip >> 24 &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip << 8;
}
return _strData.toString();
}
You can do something like this:
import 'dart:io';
import 'dart:typed_data';
void main() {
print(getIpFromInt32Value(-1407942911)); // 172.20.127.1
}
String getIpFromInt32Value(int value) => InternetAddress.fromRawAddress(
(ByteData(4)..setInt32(0, value)).buffer.asUint8List())
.address;
This solved the error:
static setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip >> 24 &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip << 8;
}
return _strData.toString();
}

IndexOutOfRangeException: Can't figure out why index out of bound

So, I have a list of Upgrade systems for my game but it has a bug on it when I press upgrade for a second time the index out of range then pressed for the third times the index out of range gone. this whole script.
void Start()
{
newSelectedIndex = previousSelectedIndex = PlayerPrefs.GetInt("currentPlayer");
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
Coins = M_CoinManager.instance.Coins;
for (int i = 0; i < Select_Player.Length; i++)
{
priceText[i].text = Cost_Player[i].ToString();
value_player[i] = "" + i;
Select_Player[i].SetActive(false);
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
}
//if(PlayerPrefs.HasKey("currentPlayer")){
selectedVehicleIndex = PlayerPrefs.GetInt("currentPlayer");
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < Select_Player.Length; i++)
{
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
if (i == buyPlayer[i])
{
Select_Player[i].SetActive(true);
upgradeBtn[i].interactable = true;
UpgradeButtonStatus();
}
else
{
upgradeBtn[i].interactable = false;
}
}
}
public void BuyCharact(int id)
{
M_SoundManager.instance.playUIsfx();
if (Cost_Player[id] <= Coins)
{
M_CoinManager.instance.AddCoins(-Cost_Player[id]);
PlayerPrefs.SetInt(value_player[id], id);
}
else
{
_CoinShake.DoShake();
Debug.Log("Does have enough coin");
}
}
public void Reset()
{
for (int i = 0; i < Select_Player.Length; i++)
{
PlayerPrefs.SetInt(value_player[i], 0);
}
}
public void Select(int id)
{
previousSelectedIndex = newSelectedIndex;
newSelectedIndex = id;
newSelectedIndex = selectedVehicleIndex;
PlayerPrefs.SetInt("currentPlayer", newSelectedIndex);
Button newbtn = Select_Player[previousSelectedIndex].GetComponent<Button>();
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
newbtn.interactable = true;
M_SoundManager.instance.playUIsfx();
Debug.Log("Selected TypeCar" + newSelectedIndex);
}
public void nextVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex = (selectedVehicleIndex + 1) % theVehicles.Length;
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void PreviousVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex--;
if (selectedVehicleIndex < 0)
{
selectedVehicleIndex += theVehicles.Length;
}
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void VehicleInfo()
{
currLevel = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel;
levelText[selectedVehicleIndex].text = "Level: " + (currLevel + 1);
powerText[selectedVehicleIndex].text = "Power: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].motorPower;
brakeText[selectedVehicleIndex].text = "Brake: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].brakePower;
Debug.Log(selectedVehicleIndex);
}
public void upgradeMethod()
{
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
if (Coins >= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost)
{
Coins -= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost;
_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel++;
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
VehicleInfo();
}
}
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
and the error reference to this method :
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
as you can see on the update that's what I mean. after i press upgrade for third times the error stopped.
and this for the inpector
Arrays length is one higher than their highest index, but last iteration of "for" loops goes to array.length.
You need to make "for" loops to array.length-1.
I see you do "for" loops of up to array.length.
I haven't truly read thru your whole script so there might be more, but it's a typical error in my "for" loops so I think that is causing your error.

Unity Destroy() doesn't delete script

Noob mistake I was only referencing the parents brain from the child's instead of copying it directly. It's a neural network that can grow in size (or shrink) through genetics. I was going to post it but it doesn't fit on this without me having to type a larger ratio of words to code oh look it works now
public class Animal1 : MonoBehaviour
{
public class Neuron1
{
public int[] children;
public float[] weights;
public float bias;
public float value;
public Neuron1()
{
children = new int[10];
for (int i = 0; i < 10; i++)
{
children[i] = -1;
}
weights = new float[10];
for (int i = 0; i < 10; i++)
{
weights[i] = 1;
}
bias = 0;
value = 0;
}
}
float sightRange = 2;
Vector2 left = new Vector2(-.4f,.6f);
Vector2 right = new Vector2(.4f, .6f);
RaycastHit2D hitLeft;
RaycastHit2D hitForward;
RaycastHit2D hitRight;
public LayerMask animalLayerMask;
[System.NonSerialized]
public int food = 0;
int foodCounter = 0;
int foodForReproduction = 3;
float noFoodCounter = 0;
int lifeWithoutFood = 20;
int maxBrainSize = 100;
[System.NonSerialized]
public Neuron1[] brain1 = new Neuron1[100]; //first three and last three are inputs and outputs and are never mutated
int childrenMaxAmount = 5;
float biasInitRange = 2;
float weightInitRange = 2;
int outputSize = 2;
int inputSize = 3;
GameObject manager;
[System.NonSerialized]
public bool firstGen = false;
[System.NonSerialized]
public GameObject parent1;
[System.NonSerialized]
public bool directCopy = false;
float maxTravelRange = 5;
Color color;
float colorMutationRate = .1f;
public GameObject animal1Prefab1;
bool debugBool = false;
void Start()
{
manager = GameObject.Find("Manager Object");
if (firstGen == true)
{
InitializeBrain(3, 2, 20);
firstGen = false;
transform.GetComponent<SpriteRenderer>().color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
}
else
{
if (parent1.GetComponent<Animal1>().brain1[0].bias == 1234)
{
Debug.Log("parent passing brain after deletion");
}
Mutate(parent1, 5, 1f, .5f);
transform.GetComponent<SpriteRenderer>().color = color;
}
}
void Update()
{
if (brain1[0].bias == 1234)
{
GetComponent<SpriteRenderer>().color = Color.black;
}
//teleportation
if (transform.position.x > maxTravelRange)
{
Vector2 newPosition = new Vector2(-maxTravelRange, transform.position.y);
transform.position = newPosition;
}
if (transform.position.x < -maxTravelRange)
{
Vector2 newPosition = new Vector2(maxTravelRange, transform.position.y);
transform.position = newPosition;
}
if (transform.position.y > maxTravelRange)
{
Vector2 newPosition = new Vector2(transform.position.x, -maxTravelRange);
transform.position = newPosition;
}
if (transform.position.y < -maxTravelRange)
{
Vector2 newPosition = new Vector2(transform.position.x, maxTravelRange);
transform.position = newPosition;
}
//input
hitLeft = Physics2D.Raycast(transform.position, transform.TransformDirection(left), sightRange, ~animalLayerMask); //left
hitForward = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), sightRange, ~animalLayerMask); //forward
hitRight = Physics2D.Raycast(transform.position, transform.TransformDirection(right), sightRange, ~animalLayerMask); //right
if (hitLeft)
{
brain1[0].value = 1;
}
if (hitForward)
{
brain1[1].value = 1;
}
if (hitRight)
{
brain1[2].value = 1;
}
//output
Think();
// one output for speed, another for turning
int rotDir = 1;
if (brain1[maxBrainSize - 1].value < 0)
{
rotDir = -1;
}
Vector3 eulerRotation = new Vector3(0, 0, (45 * rotDir + (transform.rotation.eulerAngles.z % 360)) % 360);
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(eulerRotation), Mathf.Abs(brain1[maxBrainSize - 1].value) * 25 * Time.deltaTime);
if (brain1[maxBrainSize - 2].value > 0) // so they can't go backwards
{
transform.Translate(Vector2.up * (brain1[maxBrainSize - 2].value * .1f) * Time.deltaTime);
}
//reset outputs
brain1[maxBrainSize - 2].value = 0;
brain1[maxBrainSize - 1].value = 0;
// reset inputs
brain1[0].value = 0;
brain1[1].value = 0;
brain1[2].value = 0;
noFoodCounter += Time.deltaTime;
if (food > 0)
{
foodCounter++;
food = 0;
noFoodCounter = 0;
}
if (foodCounter > foodForReproduction)
{
foodCounter = 0;
Reproduce();
}
if (noFoodCounter > lifeWithoutFood/2)
{
foodCounter = 0;
}
if (noFoodCounter > lifeWithoutFood)
{
Destroy(gameObject);
}
}
void InitializeBrain(int inputs, int outputs, int sizeExcludingInputsAndOutputs)
{
for (int i = 0; i < sizeExcludingInputsAndOutputs + inputs; i++)
{
brain1[i] = new Neuron1();
}
for (int i = maxBrainSize - outputs; i < maxBrainSize; i++) // outputs
{
brain1[i] = new Neuron1();
}
// all neurons in between the inputs and outputs
for (int i = inputs; i < sizeExcludingInputsAndOutputs + inputs; i++)
{
brain1[i].bias = Random.Range(-biasInitRange, biasInitRange);
for (short j = 0; j < childrenMaxAmount -1; j++) // -1 so there is always at least one free space for a child
{
int rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains) // making sure none are children of themselves, and that it doesn't already have this child
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[i].children[h] == rnd1) // if it already has this child
{
alreadyContains = true;
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
while (rnd1 == i) // and its not itself
{
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
}
break;
}
}
errorCounter++;
if (errorCounter > 100) // so we don't get stuck in small network sizes
{
goto outside2;
}
}
brain1[i].children[j] = rnd1;
brain1[i].weights[j] = Random.Range(-weightInitRange, weightInitRange);
if (Random.Range(1, 10) > 8)
{
break; // so not every neuron has the same amount of children
}
}
outside2:
{
}
}
// assign children of inputs
for (int i = 0; i < inputs; i++)
{
for (int j = 0; j < childrenMaxAmount; j++) // assigning all max children (sometimes) to inputs, their amounts of children will never change
{
int rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains)
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[i].children[h] == rnd1)
{
alreadyContains = true;
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
}
}
errorCounter++;
if (errorCounter > 1000) // so we don't get stuck in small network sizes
{
goto outside1;
}
}
brain1[i].children[j] = rnd1;
//brain1[i].weights[j] = 100; // input weight
}
outside1:
{
}
}
RemoveDeadNeurons();
// assign parents of outputs
int brainEnd = maxBrainSize - outputs;
for (int i = brainEnd; i < maxBrainSize; i++)
{
for (short j = 0; j < childrenMaxAmount; j++) // same amount of parents as inputs have children
{
int rnd1 = Random.Range(inputs, brainEnd);
while (brain1[rnd1] == null)
{
rnd1 = Random.Range(inputs, brainEnd);
}
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains) //making sure we dont already have this parent
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[rnd1].children[h] == i)
{
alreadyContains = true;
rnd1 = Random.Range(inputs, brainEnd);
while (brain1[rnd1] == null)
{
rnd1 = Random.Range(inputs, brainEnd);
}
}
}
errorCounter++;
if (errorCounter > 1000) // so we don't get stuck
{
goto outside3;
}
}
for (int h = 0; h < childrenMaxAmount; h++) //adding to next available child space of the parent
{
if (brain1[rnd1].children[h] == -1)
{
brain1[rnd1].children[h] = i;
brain1[rnd1].weights[h] = Random.Range(-weightInitRange, weightInitRange);
break;
}
}
}
outside3:
{
}
}
}
void Think()
{
int[] activatedChildrenIndexes = new int[500];
int[] workingArray = new int[500];
int workingArrayCounter = 0;
short layerCounter = 0;
for (int i = 0; i < 500; i++)
{
activatedChildrenIndexes[i] = -1;
}
//initializing inputs as first activated children layer to be calculated
activatedChildrenIndexes[0] = 0;
activatedChildrenIndexes[1] = 1;
activatedChildrenIndexes[2] = 2;
int thoughtDepth = 6; //keep this as low as possible, will change to make it a percent of the amount of neurons that already exist
for (int x = 0; x < thoughtDepth; x++)
{
for (int i = 0; i < 500; i++) // cycle through activated children and add their activated children to a list
{
int currentNodeIndex = activatedChildrenIndexes[i];
if (currentNodeIndex == -1)
{
layerCounter++;
break;
}
//activation function
if (brain1[currentNodeIndex].value <= 0)
{
brain1[currentNodeIndex].value = 0;
}
else
{
brain1[currentNodeIndex].value = 1;
}
for (int j = 0; j < childrenMaxAmount; j++)
{
if (brain1[currentNodeIndex].children[j] == -1)
{
break;
}
brain1[brain1[currentNodeIndex].children[j]].value
+= (brain1[currentNodeIndex].value * brain1[currentNodeIndex].weights[j]) + brain1[currentNodeIndex].bias;
bool activatedChildIsInNextLayer = false;
for (int h = 0; h < 500; h++)
{
if (brain1[currentNodeIndex].children[j] == activatedChildrenIndexes[h])
{
activatedChildIsInNextLayer = true;
}
}
if (brain1[brain1[currentNodeIndex].children[j]].value > 0
|| layerCounter == 0
|| brain1[currentNodeIndex].children[j] > maxBrainSize - outputSize)
{
if (!activatedChildIsInNextLayer)
{
workingArray[workingArrayCounter] = brain1[currentNodeIndex].children[j];
if (workingArrayCounter < 499)//to prevent out of bounds indexing
{
workingArrayCounter++;
}
}
}
if (brain1[brain1[currentNodeIndex].children[j]].value < 0 && brain1[currentNodeIndex].children[j] < maxBrainSize - outputSize)
{
brain1[brain1[currentNodeIndex].children[j]].value = 0; //resetting negative nodes that didn't get added to next layer
}
}
brain1[currentNodeIndex].value = 0; // resetting value after passing to children
}
for (int i = workingArrayCounter; i < 500; i++)
{
workingArray[i] = -1;
}
workingArrayCounter = 0;
for (int i = 0; i < 500; i++)
{
activatedChildrenIndexes[i] = workingArray[i];
}
}
}
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
for (int i = 0; i < maxBrainSize; i++) // initialized to its parent's brain
{
if (parent.GetComponent<Animal1>().brain1[i] != null)
{
brain1[i] = new Neuron1();
brain1[i].bias = parent.GetComponent<Animal1>().brain1[i].bias;
for (int j = 0; j < childrenMaxAmount; j++)
{
brain1[i].children[j] = parent.GetComponent<Animal1>().brain1[i].children[j];
brain1[i].weights[j] = parent.GetComponent<Animal1>().brain1[i].weights[j];
}
}
}
for (int i = inputSize; i < maxBrainSize - outputSize; i++)
{
if (brain1[i] != null)
{
if (Random.Range(0, 100) < mutationRate) // it will be mutated
{
switch (Random.Range(1, 5))
{
case 1: //change one of its weights
int weightCounter = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its weights
{
if (brain1[i].children[k] != -1)
{
weightCounter++;
}
else
{
break;
}
}
brain1[i].weights[Random.Range(0, weightCounter)] += Random.Range(-weightsMutate, weightsMutate);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 2: //change its bias
brain1[i].bias += Random.Range(-biasMutate, biasMutate);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 3: //break a connection/ remove neuron
int childrenCounter = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[i].children[k] != -1)
{
childrenCounter++;
}
else
{
break;
}
}
int rndChild = Random.Range(0, childrenCounter);
for (int s = rndChild; s < childrenMaxAmount - 1; s++) // shift children list down starting from rndChild and to the second to last element
{
brain1[i].children[s] = brain1[i].children[s + 1];
brain1[i].weights[s] = brain1[i].weights[s + 1];
}
brain1[i].children[childrenMaxAmount - 1] = -1; // removing the last child after shifting the list down one
brain1[i].weights[childrenMaxAmount - 1] = 0;
RemoveDeadNeurons();
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 4: //add a new child if possible
int childrenCounter2 = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[i].children[k] != -1)
{
childrenCounter2++;
}
else
{
break;
}
}
if (childrenCounter2 < childrenMaxAmount) // if we have room for another child
{
int newChild = Random.Range(inputSize, maxBrainSize);
while (brain1[newChild] == null)
{
newChild = Random.Range(inputSize, maxBrainSize);
}
brain1[i].children[childrenCounter2] = newChild;
brain1[i].weights[childrenCounter2] = Random.Range(-weightInitRange, weightInitRange);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
}
break;
}
}
}
}
if (Random.Range(0, 100) < 10) // create a new neuron if space is available for one
{
for (int i = inputSize; i < maxBrainSize - outputSize; i++)
{
if (brain1[i] == null) // the first available neuron
{
brain1[i] = new Neuron1();
int rndParent = Random.Range(0, maxBrainSize - outputSize);
int childrenCounter3 = 0;
if (brain1[rndParent] != null)
{
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[rndParent].children[k] != -1)
{
childrenCounter3++;
}
else
{
break;
}
}
}
while (brain1[rndParent] == null || childrenCounter3 == childrenMaxAmount) // making sure it is both an existing neuron and that it has room for another child
{
childrenCounter3 = 0;
rndParent = Random.Range(0, maxBrainSize - outputSize);
if (brain1[rndParent] != null)
{
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[rndParent].children[k] != -1)
{
childrenCounter3++;
}
else
{
break;
}
}
}
}
brain1[rndParent].children[childrenCounter3] = i; //giving the neuron a parent
brain1[rndParent].weights[childrenCounter3] = Random.Range(-weightInitRange, weightInitRange);
int rndChild = Random.Range(inputSize, maxBrainSize);
while(brain1[rndChild] == null)
{
rndChild = Random.Range(inputSize, maxBrainSize);
}
brain1[i].children[0] = rndChild; // giving the new neuron a child, a weight, and its bias
brain1[i].weights[0] = Random.Range(-weightInitRange, weightInitRange);
brain1[i].bias = Random.Range(-biasInitRange, biasInitRange);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
}
}
}
}
void RemoveDeadNeurons()
{
bool allGood = false;
while (!allGood)
{
for (int i = inputSize; i < maxBrainSize - outputSize; i++) // for every hidden layer neuron
{
if (brain1[i] != null) // if it's a neuron
{
if (brain1[i].children[0] == -1) // if it has no children
{
brain1[i] = null; // deleting neuron
for (int h = 0; h < maxBrainSize - outputSize; h++) //remove from other neurons children list, including from the input layer
{
if (brain1[h] != null)
{
for (int g = 0; g < childrenMaxAmount; g++)
{
if (brain1[h].children[g] == i) // if brain[h] has the removed neuron as a child
{
for (int s = g; s < childrenMaxAmount - 1; s++) // shift children list down
{
brain1[h].children[s] = brain1[h].children[s + 1];
brain1[h].weights[s] = brain1[h].weights[s + 1];
}
brain1[h].children[childrenMaxAmount - 1] = -1; // removing the last child in the list after shifting it down one
brain1[h].weights[childrenMaxAmount - 1] = 0;
}
}
}
}
goto outsideRDNLoop; // break out of for loop and recheck the brain
}
bool parentless = true;
for (int h = 0; h < maxBrainSize - outputSize; h++) // check if it is parentless
{
if (brain1[h] != null)
{
for (int g = 0; g < childrenMaxAmount; g++)
{
if (brain1[h].children[g] == i) // if it is a child of brain[h]
{
parentless = false;
}
}
}
}
if (parentless)
{
brain1[i] = null; //deleting neuron
goto outsideRDNLoop;
}
}
if (i == (maxBrainSize - outputSize) - 1) // if we reached the end of the for loop and this line, we know the brain was allGood
{
allGood = true;
}
}
outsideRDNLoop:
{
}
}
}
void Reproduce()
{
GameObject offspring = Instantiate(animal1Prefab1, new Vector2(transform.position.x + 1, transform.position.y + 1), Quaternion.identity);
offspring.GetComponent<Animal1>().parent1 = gameObject;
offspring.name = "animal1";
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, transform.TransformDirection(left) * sightRange);
Gizmos.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * sightRange);
Gizmos.DrawRay(transform.position, transform.TransformDirection(right) * sightRange);
}
}
I've not run your code, just looked at it, but this looks suspicious if you are having problems with the contents of brain1 being overwritten elsewhere:
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
// This line here is suspicious:
brain1 = parent.GetComponent<Animal1>().brain1; // initialized to its parent's brain
What you are doing here is replacing the reference to the child's brain with the parent's - so if you are starting with just one parent initially, every single entity will be sharing the same brain.
I think perhaps you meant to deep copy the contents from parent's brain into the child's brain? What your assignment here is doing is just taking the reference to the parent's brain and using it as the child brain as well.
Example Deep copy:
Updated Neuron1 class:
public class Neuron1
{
public int[] children;
public float[] weights;
public float bias;
public float value;
public Neuron1()
{
children = new int[10];
for (int i = 0; i < 10; i++)
{
children[i] = -1; // to stop looping when reaching -1
}
weights = new float[10];
for (int i = 0; i < 10; i++)
{
weights[i] = 1;
}
bias = 0;
value = 0;
}
// Added clone function:
public Neuron1 Clone()
{
Neuron1 clone = new Neuron1();
for (int i = 0; i < clone.children.Length; i++)
{
clone.children[i] = this.children[i];
}
for (int i = 0; i < clone.weights.Length; i++)
{
clone.weights[i] = this.weights[i];
}
clone.bias = this.bias;
clone.value = this.value;
return clone;
}
}
Updated start of Mutate function.
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
Neuron1[] parentBrain = parent.GetComponent<Animal1>().brain1; // initialized to its parent's brain
for (int i = 0; i < brain1.Length; ++i)
{
brain1[i] = parentBrain[i].Clone();
}
Well, I have a demo scene here. In it I created an empty game object. It has a script attached to it (CSharp.cs), like this:
In my Update method I wrote
And as soon as I start the game, the game object including the script is deleted.
But if I replace transform.gameObject wit just this then only the script disappears and the game object remains.
DestoryImmediate() is not recommended to be used, instead use Destory()
Destroy() will set the object to null at the end of the frame and whereas DestroyImmediate() function immediately set object reference to null.
DestoryImmediate can also delete prefabs/scenes/art in your project outside of playmode which is another reason you should not use it.

UI Freeze in SWT

I am new to SWT. I am trying to create a small application. Basically it has two screens. In the first screen I have to take user credentials. It has to be validated. If its successful I have to query a table and build a tree structure. Both validation and building the tree freezes my UI. I searched stackoverflow and google. I got the below options.
Display.getDefault().asyncExec() and starting long running process as separate thread from UI thread.
But still my UI freezes.
When the user clicks on Logon button. I created a thread. As a first step I tried to show a indefinite progress bar using asyncExec. Since I have to access the Uname and Password I have to trigger another asyncexec and perform the login. If its successful populated the tree.
I triggered another asyncExec to close the progress bar.
My UI freezes from Logon click till Tree population completion. Where am I going wrong.
new Thread(new Runnable()
{
private int progress = 0;
private static final int INCREMENT = 10;
#Override
public void run()
{
while (!progressBar.isDisposed())
{
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
if (!progressBar.isDisposed())
progressBar.setVisible(true);
}
});
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
String sAuth = null;
switch(tAuth.getText()){
case "Enterprise": sAuth = "secEnterprise"; break;
case "LDAP": sAuth = "secLDAP"; break;
case "Windows AD": sAuth = "secWinAD"; break;
case "SAP": sAuth = "secSAPR3"; break;
}
try {
log.info("Attempting to create enterprise session");
CoreLogic.logonEnterprise(tUSR.getText().trim(),tPWD.getText().trim(),sAuth,tCMS.getText());
if(CommonVariables.entsession){
log.info("Enterprise session created.");
CoreLogic.getUniverse();
log.info("Populating universe tree");
String[] temp;
for (Entry<Integer, UnvObj> entry : CommonVariables.unvlst.entrySet()) {
UnvObj t = entry.getValue();
temp = t.getPath().split("/");
if (temp[0].equals("Universes")){
int max = temp.length;
int i =0 ;
boolean flag = false;
TreeItem trItem = null;
do{
if(i == 0) {
if(tree.getItemCount() == 0){
flag = false;
}
else
{
for(int k = 0; k < tree.getItemCount(); k++){
if(temp[i].equals(tree.getItem(k).getText())){
i++;
trItem = tree.getItem(k);
flag =true;
break;
}
else
{
flag = false;
}
}
}
}
else{
if(trItem.getItemCount() == 0){
flag = false;
}
else
{
for(int k = 0; k < trItem.getItemCount(); k++){
if(temp[i].equals(trItem.getItem(k).getText())){
i++;
trItem = trItem.getItem(k);
flag =true;
break;
}
else
{
flag = false;
}
}
}
}
}while (flag == true && i < max);
TreeItem Item = null;
if (i == 0){
for (int k = 0; k < max; k++){
if(k == 0) {
Item = new TreeItem(tree,SWT.NONE);
Item.setText(temp[k]);
Item.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
Item.setImage(image);
}else
{
Item = new TreeItem(Item,SWT.NONE);
Item.setText(temp[k]);
Item.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
Item.setImage(image);
}
}
} else if( i < max){
for (int k = i; k < max; k++){
trItem = new TreeItem(trItem,SWT.NONE);
trItem.setText(temp[k]);
trItem.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
trItem.setImage(image);
}
}
if (i == 0){
Item = new TreeItem(Item,SWT.NONE);
Item.setText(t.getName());
Item.setData("Type",t.getKind());
Item.setData("Mapkey",entry.getKey());
if(t.getKind().equals("Universe")){
Image image = new Image(display,ResourceLoader.load("/images/Unv.ico"));
Item.setImage(image);
}
else{
Image image = new Image(display,ResourceLoader.load("/images/Unx.ico"));
Item.setImage(image);
}
} else
{
trItem = new TreeItem(trItem,SWT.NONE);
trItem.setText(t.getName());
trItem.setData("Type",t.getKind());
trItem.setData("Mapkey",entry.getKey());
if(t.getKind().equals("Universe")){
Image image = new Image(display,ResourceLoader.load("/images/Unv.ico"));
trItem.setImage(image);
}
else{
Image image = new Image(display,ResourceLoader.load("/images/Unx.ico"));
trItem.setImage(image);
}
}
}
}
log.info("Universe Tree Populated.");
sl.topControl =Universe;
Main.layout();
}else
{
log.info("Unable to create enterprise session");
MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
messageBox.setText("Report Extractor");
messageBox.setMessage("Unable to create the enterprise session with the provided credentials. Please verify it.");
messageBox.open();
}
}
catch(Exception exp)
{
log.error("Fail to create enterprise session",exp);
}
}
});
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
if (!progressBar.isDisposed())
progressBar.setVisible(false);
}
});
}
}
}).start();

Calling Method by using String instead of ObjectName - Processing in Eclipse

I am trying to combine multiple sketches I had, by having them as classes in a single sketch and go through them by pressing keys.
I'm not sure I'm following the right method but I'm basically turning them on and off by using a boolean for each. I have something like:
package combiner;
public class Combiner extends PApplet {
//...
ClassNameOne s1;
ClassNameTwo s2;
//...
ClassNameNine s9;
// AllSketches //
boolean[] sketches;
int totalSketches = 9;
String str_ts = String.valueOf(totalSketches);
char char_ts = str_ts.charAt(0);
public void setup() {
size(1920, 1080);
sketches = new boolean[totalSketches];
for (int i = 0; i < sketches.length; i++) {
sketches[i] = false;
}
s1 = new ClassNameOne(this);
s2 = new ClassNameTwo(this);
//...
s9 = new ClassNameNine(this);
}
public void draw() {
//drawingEachSketchIfItsBoolean==True
if (sketches[0] == true) {
s1.run();
} else if (sketches[1] == true) {
s2.run();
//....
}
}
public void keyPressed() {
if (key >= '1' && key <= char_ts) {
String str_key = Character.toString(key);
int KEY = Integer.parseInt(str_key);
for (int i = 0; i < sketches.length; i++) {
sketches[i] = false;
}
sketches[KEY - 1] = true;
//initializingEachClassIfKeyPressed
if (KEY == 0) {
s1.init();
} else if (KEY == 1) {
s2.init();
}
//....
}
}
As you can see each Class has an .init and a .run method (used to be my setup + draw).
I was wandering if somehow I can loop to .init or .run them without having to write it once for each, something like:
for(int i=0;i<sketches.length;i++){
if(sketches[i]==true){
String str = String.valueOf(i+1);
str="s"+str; //str becomes the Object's name
??? str.run(); ???
}
}
The cleanest solution would be to create an interface Sketch, which must be implemented in your sketch classes then:
Sketch[] sketches;
int activeSketch = 0;
void setup(){
sketches = new Sketch[2];
sketches[0] = new SketchRed();
sketches[1] = new SketchGreen();
sketches[activeSketch].init();
}
void draw(){
sketches[activeSketch].draw();
}
interface Sketch{
void init();
void draw();
}
class SketchRed implements Sketch{
void init(){}
void draw(){
fill(255, 0, 0);
ellipse(width/2, height/2, 30, 30);
}
}
class SketchGreen implements Sketch{
void init(){}
void draw(){
fill(0, 255, 0);
ellipse(width/2, height/2, 30, 30);
}
}
void keyPressed(){
activeSketch++;
if(activeSketch >= sketches.length){
activeSketch = 0;
}
sketches[activeSketch].init();
}
I am not sure if the whole idea of representing different sketches as classes in a new sketch is really that good, but in any case there seems to be a possibilty in Java for obtaining a class from a String! Look for Class.forName() as described here: http://docs.oracle.com/javase/tutorial/reflect/class/classNew.htm
Keep in mind that you will obtain a class from this and not an instance yet!