## javascript – This code renders a time dilation calculator. Am I abusing React state? Can I reorganize my components so that this scales better?

I’ve been learning React for about a month now. I wrote a small (interactive calculator)(1) to show the effects of time dilation under special relativity. It’s Node/React/Razzle(for SSR)/Typescript/Javascript.

Here are the issues I’ve run into and would like help with:

1. I feel like I’m abusing state. You change one parameter and it cascades through other dependent values which then trigger a recalculation; but because state updates are asynchronous, I have to set awkward artificial callbacks to force a timely update.

2. Bootstrap prepend and append on input forms take up a lot of space and cause certain calculators to render poorly on mobile… Should I consider using Material UI, or can I “prettify” and resize the input fields appropriately with custom CSS / bootstrap?

3. Scalability – Currently there are only ~13 components but intend to make a lot more pages and calculators, and I’m wondering if there’s any room for refactoring to take advantage of recurring patterns: it feels like I could be writing a lot less code. Also, routes – the file containing routes could get huge – will that become a problem in the future?

``````import { ThreeColumnContainer } from "../Layout/ThreeColumnContainer";
import { TextControl } from "../controls/Input";
import { Helmet } from "react-helmet";

const c = 299792.458; //km/s

export class TwinParadoxUnderSpecialRelativity extends Component<{}, { (key: string): number }> {

constructor(props) {
super(props);
this.state = {
velocityAsPercentageOfC: 0,
lorentzFactor: 1,
velocityInKph: 0,
velocityInMph: 0,
contractedElapsedTime: 1,
dilatedElapsedTime: 1
};

this.calculateLorentzFactor = this.calculateLorentzFactor.bind(this);
this.updateVelocity = this.updateVelocity.bind(this);
this.updateLorentzFactor = this.updateLorentzFactor.bind(this);
this.calculateVelocityAsPercentageOfC = this.calculateVelocityAsPercentageOfC.bind(this);
this.calculateTimeDilation = this.calculateTimeDilation.bind(this);
this.updateElapsedTime = this.updateElapsedTime.bind(this);
this.updateTravelerElapsedTime = this.updateTravelerElapsedTime.bind(this);
this.calculateTimeContraction = this.calculateTimeContraction.bind(this);
}

updateVelocity(e) {
var velocityAsPctOfC = e.target.value;
var lorentzF = this.calculateLorentzFactor(velocityAsPctOfC);
var kph = this.convertToKmh(velocityAsPctOfC);
var mph = this.convertToMph(kph)
//var dilatedTime =
this.setState({ velocityAsPercentageOfC: velocityAsPctOfC, lorentzFactor: lorentzF, velocityInKph: kph, velocityInMph: mph},
() => this.setState({dilatedElapsedTime: this.calculateTimeDilation(this.state.contractedElapsedTime, lorentzF)}));
}

updateLorentzFactor(e) {
var lorentzF = e.target.value;
var velocityAsPctOfC = this.calculateVelocityAsPercentageOfC(lorentzF);
var kph = this.convertToKmh(velocityAsPctOfC);
var mph = this.convertToMph(kph)
//var dilatedTime = this.calculateTimeDilation(this.state.elapsedTime);
this.setState({ velocityAsPercentageOfC: velocityAsPctOfC, lorentzFactor: lorentzF, velocityInKph: kph, velocityInMph: mph},
() => this.setState({dilatedElapsedTime: this.calculateTimeDilation(this.state.contractedElapsedTime, lorentzF)}));
}

updateTravelerElapsedTime(e) {
var elapsed = e.target.value;
this.setState({contractedElapsedTime: elapsed},
() => this.setState({dilatedElapsedTime: this.calculateTimeDilation(this.state.contractedElapsedTime, this.state.lorentzFactor)}));
}

updateElapsedTime(e) {
var dilatedTime = e.target.value;
this.setState({ dilatedElapsedTime: dilatedTime },
() => this.setState({contractedElapsedTime: this.calculateTimeContraction(this.state.dilatedElapsedTime, this.state.lorentzFactor)}));
}

calculateLorentzFactor(velocityAsPercentageOfC: number) {
return 1 / Math.sqrt( 1 - ( Math.pow( velocityAsPercentageOfC / 100, 2) ) );
}

calculateVelocityAsPercentageOfC(lorentzFactor: number) {
return Math.sqrt(-1 * (Math.pow(1/lorentzFactor, 2) -1)) * 100;
}

convertToKmh(velocityAsPercentageOfC: number){
return velocityAsPercentageOfC * c;
}

convertToMph(kilometersPerHour: number)
{
return kilometersPerHour * 0.621371;
}

calculateTimeContraction(contractedElapsedTime: number, lorentzFactor: number)
{
return contractedElapsedTime / lorentzFactor;
}

calculateTimeDilation(dilatedElapsedTime: number, lorentzFactor: number)
{
return dilatedElapsedTime * lorentzFactor;
}

roundNumber = (num: number, dec: number) => {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

renderLeft() {
return (
<div>
<h1>Twin Paradox (Time Dilation under SR) Calculator</h1>
<p/>
<TextControl prepend="Relative velocity as % of c" type="number" value={this.state.velocityAsPercentageOfC} append="v" onChange={this.updateVelocity} />
<TextControl prepend="Lorentz Factor" type="number" value={this.state.lorentzFactor} append="gamma" onChange={this.updateLorentzFactor} />
<TextControl prepend="Velocity in kph" type="number" value={this.state.velocityInKph} append="kph" readonly="true" />
<TextControl prepend="Velocity in mph" type="number" value={this.state.velocityInMph} append="mph" readonly="true" />
<TextControl prepend="Earth Observer Elapsed Time" type="number" value={this.state.dilatedElapsedTime} append="Tb" onChange={this.updateElapsedTime} />
<TextControl prepend="Spaceship Traveler Elapsed Time" type="number" value={this.state.contractedElapsedTime} append="Ta" onChange={this.updateTravelerElapsedTime}/>
<p></p>
<h4>Explanation</h4>
<p>At {this.roundNumber(this.state.velocityAsPercentageOfC,0)}% of the speed of light (c), the lorentz factor or gamma is {this.roundNumber(this.state.lorentzFactor,4)}. That means a twin traveling through space will age at {this.roundNumber(1 / this.state.lorentzFactor * 100,4)}% the rate of its twin at relative rest on earth. If {this.roundNumber(this.state.dilatedElapsedTime,4)} units of time have passed on earth, {this.roundNumber(this.state.contractedElapsedTime,2)} units of time will pass for the space twin. For this to be realistic, the space twin needs to travel at {this.roundNumber(this.state.velocityInMph/1000,0)}K miles per hour ({this.roundNumber(this.state.velocityInKph/1000,0)}K kilometers per hour).</p>
<p>Interestingly, the spaceship - and everything in it - will also contract in length to {this.roundNumber(1 / this.state.lorentzFactor * 100,2)}% of its original length.</p>
</div >
);
}

renderMiddle() {
return (
<div>
<Helmet>
<meta name='description' content='Calculate the Lorenz factor based on given velocity or percentage of the speed of light to measure time dilation in special relativity.' />
</Helmet>
<h3>Calculate Time Dilation (SR)</h3>
<p>Time Dilation is the time difference between two clocks or observers moving relative to each other. Time Dilation has practical consequences at very fast relative speeds, in particular for GPS and other satelites. The formula to calculate time dilation is Sqrt(1 - v^2 / c^2) where v is relative velocity and c is the speed of light. The result is called the Lorenz factor.</p>
<p>Time Dilation means that someone traveling at very high speeds will "experience" time at a slower rate than someone in a frame at rest. So at speeds approaching the speed of light a traveler will age more slowly than someone observing from earth. The closer the traveler gets to the speed of light, the more dramatic the effect, so the traveler could experience and age only a year while everyone on earth ages and experiences eight years.</p>
</div>
);
}

render() {

return (
<div>
<ThreeColumnContainer
left={this.renderLeft()} middle={this.renderMiddle()}></ThreeColumnContainer>
</div >
);
}
}```

``````

## magento2 – Magento 2 how to use many components inside a component knockout js?

I wan’t to import components and use them just like in Vue or ReactJs. Where you can

``````export default component
``````

And import it by using

``````import Name from './path/to/component';
``````

and finally use it

How can I do this same thing but on Magento 2? I know that on top I can use require or define, but when I import the component can’t use it’s template or functions just like in React the functional components.

For example:

``````define(('jquery', 'uiComponent', 'ko', 'Vendor_Module/js/component'), function (\$, Component, ko, customComponent) {

customComponent //here I expect to use it's template and also send props o get data from it
}
``````

Greetings!

## How to organize common android UI components such as comment section?

I’m developing a social media app. One of the common components is the comment section. I’m wondering how I can organize my code better to reduce redundancy, because I think it doesn’t make sense if I created the same XML file for every screen that uses the comment section and all the logics needed. But if I make a reusable component will there be any drawbacks, in terms of flexibility and maintainability? I wanted to know what’s the best approach on this.

## Does a player character automatically know the cost of their spell components?

I have seen powerful spells that require a material component that costs a fair number of gold pieces. If a character chooses one of these spells, do they know what the cost is?

## C# Events in Unity to separate GameObject features into Components

Broadly speaking, this is a question about how to separate my game object’s code into distinct feature components that can be added and removed as needed.

More specifically, I am trying to achieve this using C# events in Unity. But I am open to other solutions.

Scenario: We have enemies that have health. When their health reaches zero, they die. Some enemies (think asteroids) may spawn a number of child enemies (think smaller astroid pieces) when they die. Others however, just die.

I want to have two scripts:

• EnemyHealth: Tracks the enemy’s health and kills the enemy when its health reaches zero.
• EnemyChildrenSpawner: Spawns child enemies after the enemy’s death

This way, all enemies will have the EnemyHealth script, and some enemies will have the EnemyChildrenSpawner script in addition.

My idea is to have the EnemyHealth script raise an event when the enemy dies, and have EnemyChildrenSpawner subscribe to said event to spawn the children.

What would be the best way of achieving this?

Here’s my attempt. It works. Just not sure if this is good practice, especially using the GetComponent in the second script?

EnemyHealth.cs

``````public class EnemyHealth : MonoBehaviour
{
// The event to invoke when this enemy died
public event EventHandler OnDied;

// Gets called when this enemy's health reached zero
private void Die()
{
// Invoke the died event
OnDied?.Invoke(this, EventArgs.Empty);

// Destroy this enemy
}
}
``````

EnemyChildrenSpawner.cs

``````public class EnemyChildrenSpawner : MonoBehaviour
{
private void OnEnable()
{
GetComponent<EnemyHealth>().OnDied += SpawnChildren;
}

private void OnDisable()
{
GetComponent<EnemyHealth>().OnDied -= SpawnChildren;
}

private void SpawnChildren(object sender, EventArgs e)
{
// Spawn children
}
}

$$```$$
``````

## networking – What is the principal components of a cellular network?

networking – What is the principal components of a cellular network? – Super User

## ag.algebraic geometry – Irreducible components of spaces of morphisms

Consider a family $$X$$ of surfaces $$mathbb{P}^1timesmathbb{P}^1$$ parametrized by $$mathbb{C}$$. We may assume that $$Xcong mathbb{P}^1timesmathbb{P}^1timesmathbb{C}$$.

Fix an irreducible $$2$$-section $$Gammasubset X$$. So $$Gamma_tsubsetmathbb{P}^1timesmathbb{P}^1$$ is a curve projecting $$2$$ to $$1$$ say onto the first copy of $$mathbb{P}^1$$ for all $$tinmathbb{C}$$. Take $$p_1(t),dots,p_k(t)inmathbb{P}^1$$ distinct points depending on $$t$$. We can think of these points as curves in $$mathbb{P}^1timesmathbb{C}$$.

Then fix $$x_1,y_1,dots,x_k,y_kinmathbb{P}^1$$ distinct points. Let $$Y_{2,d}$$ be the space of morphisms $$f:mathbb{P}^1rightarrowmathbb{P}^1timesmathbb{P}^1$$ of bidegree $$(2,d)$$ such that $$f(x_i),f(y_{i})inGamma$$ for all $$i = 1,dots k$$, and $$f(x_i),f(y_i)$$ get mapped to $$p_i(t)$$, by the projection onto the first copy of $$mathbb{P}^1$$, for all $$i = 1,dots, k$$.

We can look at $$Y_{2,d}$$ inside the product $$Mor_2(mathbb{P}^1,mathbb{P}^1)times Mor_d(mathbb{P}^1,mathbb{P}^1)subsetmathbb{P}^5times mathbb{P}^{2d+1}$$. My question is the following: could $$Y_{2,d}$$ be irreducible or does it always have at least two irreducible components one parametrizing morphisms mapping $$x_i$$ “above” and $$y_i$$ “below” and the other one switching $$x_i$$ and $$y_i$$?

Thank you.

## Magento 2 reutilize components and template.html

I have been searching how can I use ko component inside another ko component and extend in order to create complex forms.

I just don’t get it how it works.

Whit this I was successfully tu extend a component:

``````define(('jquery', 'uiComponent', 'ko', 'Vendor_Application/js/general-form'), function (\$, Component, ko, Form {
'use strict';
return Form.extend({
defaults: {
template: 'Vendor_Application/portability-form'
},
initialize: function (config) {
this._super();
var self = this;

console.log("Hello from the port form");
},

});
}
);
``````

I was able to extend all my genera-form js functions without the need to write them again, but now, how can I add some fiels that are unique of this port-form to general-form template?

I know there is some data-bind = scope: component, but if I do this, won’t I lose some functionality on js methods?

Or if I add 2 templates from 2 different component (one extending other) will I be able to have share variables?

Greetings!

## A c++ program to take the size and components of an Array from user and return the reversed Array

I have written this code that should take the size and components of the array from the user and then return the reverse of the Array but not able to identify and fix the error.
My best guess is that the while loop is causing trouble, but I am not sure.

``````#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

// function to reverse given array
void reverseArray(int arr(), int start, int end){

while (start<=end){
int temp = arr(start);
arr(start) = arr(end);
arr(end) = temp;
start++;
end--;

}

}

// function to print given array
void printArray(int arr(), int size){
for (int i = 0; i < size; i++)
cout << arr(i) << " ";
}

int main() {
int n;
cin >> n;
int mainarray() = {n} ;
n = sizeof(mainarray);

for (int i=0; i<n; i++) {
cin >> mainarray(i);
}

reverseArray(mainarray , 0, n-1);
printArray(mainarray ,n);

return 0;
}
``````

## blocks – Adding section components with populated fields to a node

I’m working on migrating content from fieldable panels panes in D7 to Layout Builder in D8. So far, I’ve managed to extract the content I need from my D7 database, but I’ve been unable to add that content to layout builder section components. Backing up a bit, I’m currently trying to just add some inline blocks with sample content to a layout builder section in an attempt to determine how to populate the fields, as follows:

``````    /*
Add an inline block of 'basic' type to a section
'basic' blocks only have a field called "body" of type "Text (formatted, long, with summary)"
*/
\$section = new Section('two_column');

\$testcomponent = new SectionComponent(\$this->uuid->generate(), 'first', (
'id' => 'inline_block:basic',
'label' => 'Test component label',
'label_display' => 'visible',
'body',(
'value'=>'Test',
'format'=>'limited_html_text',
)
));
\$section->appendComponent(\$testcomponent);

``````

After I run my migration, I end up with a node with a inline block of “basic” type in the “first” region, as expected, but it’s empty aside from the label. Could someone advise me on how to set field values for section components?