what is switch in javascript
tried using it but did not work
switch(){
case 1:
color="blue";
case 2:
color="pink";
case 3:
color="orange";
case 4:
color="black";
case 5:
color="white"
case 6:
case 7
case 8:
case 9:
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
what is switch in javascript
tried using it but did not work
switch(){
case 1:
color="blue";
case 2:
color="pink";
case 3:
color="orange";
case 4:
color="black";
case 5:
color="white"
case 6:
case 7
case 8:
case 9:
I’m building an URL validator right now and now I want to check every part of the URL.hostname. I also want to make sure that it still works with more than one tld for example: co.uk. Or more than one subdomain like: careers.jobs.
This is my code for now but I just can’t think of a way to dynamically make it work with slices and splits.
Maybe one of you used a different and especially optimized approach for this.
const urlOptions = {
requireHost: true,
}
const URL_HOSTNAME = /^[a-zA-Z0-9.-]+$/;
function isValidUrl(url, options = urlOptions) {
try {
const urlObject = new URL(url);
const urlHostname = urlObject.hostname;
if (options.requireHost && !urlHostname) {
throw new Error('Hostname is required.');
}
let hostnameParts = urlHostname.split('.');
let dots = hostnameParts.length - 1;
// URL_HOSTNAME is a basic regexp
if (!URL_HOSTNAME.test(urlHostname) || dots < 1) {
throw new Error('Invalid hostname. A valid hostname should contain at least one dot with a valid TLD.');
}
if (dots == 1) {
let fld = hostnameParts[0];
let tld = hostnameParts[1];
console.log("fld: ", fld);
console.log("tld: ", tld);
} else if (dots == 2) {
let sld = hostnameParts[0];
let fld = hostnameParts[1];
let tld = hostnameParts[2];
console.log("sld: ", sld);
console.log("fld: ", fld);
console.log("tld: ", tld);
}
return true;
} catch (error) {
return false;
}
}
const url = "https://example.co.uk";
isValidUrl(url, urlOptions);
I’m new in react router and react testing and i keep getting error as in title.
I think problem lies in NavLinks in Header.
main.jsx:
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Router />
</React.StrictMode>,
);
Router.jsx:
const Router = () => {
const router = createBrowserRouter([
{
path: '/',
element: <App />,
children: [
{
index: true,
element: <MainPage />,
},
{
path: '/shop',
element: <Shop />,
},
],
},
]);
return <RouterProvider router={router} />;
};
app.jsx:
import Header from '../components/Header/Header';
const App = () => {
return (
<div>
<Header />
<Outlet />
</div>
);
};
Header.jsx:
const Header = () => {
return (
<header className={styles.header}>
<img src="https://www.kadencewp.com/wp-content/uploads/2020/10/alogo-4.png" alt="logo" />
<nav>
<NavLink to="/" className={({ isActive }) => (isActive ? styles.active : styles.inactive)}>
Main page
</NavLink>
<NavLink to="/shop" className={({ isActive }) => (isActive ? styles.active : styles.inactive)}>
Shop
</NavLink>
</nav>
</header>
);
};
test:
describe('test', () => {
it('test', () => {
render(<App />);
expect(true).toBeTruthy();
});
});
I tried solutions from other questions but they are using other syntax and I can’t get them to work. From other posts I understand that Header is outside of router but nothing that I tried to do with it works.
I want to make interactive board like on video but I don’t know how to start. Board with coords from like -10 to 10 and with draggable point. Maybe someone has some idea:)
preview and origin of video.
Im looking for some code snippet.
Seems like it should be easy
I would like to assign the value of p.message to a class variable.
export class Person {
id: number;
fName: string;
message: string;
}
Service:
personById(id: number): Observable<Person> {
let params = new HttpParams();
params = params.append("id", id);
return this.http.get(this.url + 'person', {
params: params,
observe: 'response'
}).pipe(
map(r => {
return r.body as Person;
})
);
}
component:
onSubmit(): void {
this.personService.personById(this.fg.controls['id'].value).subscribe(p => {
const x = p.message;
console.log("x=", x);
console.log("p=", p);
this.message = p.message;
console.log("message=", this.message);
this.myPerson = p;
console.log("myPerson=", this.myPerson);
this.message = this.myPerson.message;
console.log("message=", this.message);
console.log("message x=", p['message']);
console.log("here");
});
}
in chrome devtools I can see the value of p.message by highlighting and this.myPerson obtains all the properties and values of p. need to know how to set the value of some variable with the value of p.message.
The problem i have is just how to send formdata with react hook form to the api end point
I tried to append the data from react hook form to formdata but when i console.log, it returns undefined.I also tried the using the onchange method with out the {..field} input of react hook form it still same result
const onSubmit = async (data: Inputs) => {
console.log("data", data)
const formData = new FormData();
const port = formData.append("media", data.media); // Assuming 'media' is a property in 'data' and it's a file input
const portt = formData.append("description", data.description);
console.log(port)
console.log(portt)
try {
setSubmitted(true);
if (porfolio) {
await fetch(`/api/portfolio/${porfolio.id}`, {
method: "PATCH",
body: formData,
});
setOpen(false);
toast.success("Update Sucessful.");
} else {
const port = await fetch("/api/portfolio", {
method: "POST",
body: formData,
});
console.log("port", port)
setOpen(false);
toast.success("Created portfolio.Check /portfolio for changes.");
form.reset();
await port.json();
}
router.refresh();
} catch (error) {
setSubmitted(false);
setError("error occured during the process. Report back to developer.");
}
};
//the input file field
<FormField
control={form.control}
name="media"
render={({ field }) => (
<FormItem>
<FormControl>
<Input type="file" placeholder="media" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
/another example with route handler
export async function POST(request: NextRequest) {
const body = await request.formData();
const file = body.get("media") as File;
console.log("file:", file)
const arrayBuffer = await file.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer);
it gives the following error: ⨯ TypeError: file.arrayBuffer is not a function
My code has a component that displays the names of devices (available in the database). Here’s an example
https://codesandbox.io/p/sandbox/dreamy-firefly-7xqypj
As you can see from the example above, when you click on any of the devices (within divs), the border color changes from green to red. Everything seems simple here and everything works well.
But I need to make sure that the color of the border does not change (remains green) when the “submenu” button is pressed (In the original code, when this button is clicked, a modal window opens). That is, if the user clicks anywhere on the div (except for the “submenu” button) -> the border color changes from green to red; but clicking on the “submenu” button should not affect the border color change
const data = [
{ id: "1", title: "Samsung" },
{ id: "2", title: "Iphone" },
{ id: "3", title: "LG" },
];
export default function App() {
const [active, setActive] = useState(null);
return (
<span id="main">
{data.map((item) => (
<div
onClick={() => setActive(item.id)}
className={item.id === active ? "active" : "App"}
>
<p>{item.title}</p>
<button>submenu</button>
</div>
))}
</span>
);
}
I made two pie charts using chart.js. Both graphs have two data. I am having a problem with the width increase or decrease one of the data of my pie graph. Also I want to change the angle of that 30% and 70% as my design. I want to change the angle also as my design, i don’t know is that even possible to do that with chart js. This is current output – 
// Donut Graph
// Get the canvas element
var canvas = document.getElementById('donutGraph');
// Create the donut chart
var donutChart = new Chart(canvas, {
type: 'doughnut',
data: {
datasets: [{
data: [70, 30],
backgroundColor: ['#E1EFFE', '#1C64F2'],
borderWidth: 0
}]
},
options: {
responsive: true, // Enable responsiveness
maintainAspectRatio: false,
cutout: '40%', // Creates a donut chart
legend: {
display: false
},
plugins: {
datalabels: {
display: true,
color: '#fff',
formatter: (value, ctx) => {
let sum = ctx.dataset.data.reduce((a, b) => a + b, 0);
let percentage = (value * 100 / sum).toFixed(0);
return percentage + "%";
}
}
}
}
});
// Donut Graph Two
// Get the canvas element
var canvastwo = document.getElementById('donutGraphtwo');
// Create the donut chart
var donutCharttwo = new Chart(canvastwo, {
type: 'doughnut',
data: {
datasets: [{
data: [70, 30],
backgroundColor: ['#0E9F6E', '#DEF7EC'],
borderWidth: 0
}]
},
options: {
responsive: true, // Enable responsiveness
maintainAspectRatio: false,
cutout: '40%', // Creates a donut chart
legend: {
display: false
},
plugins: {
datalabels: {
display: true,
color: '#fff',
formatter: (value, ctx) => {
let sum = ctx.dataset.data.reduce((a, b) => a + b, 0);
let percentage = (value * 100 / sum).toFixed(0);
return percentage + "%";
}
}
}
}
});
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700;800;900&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.graph-two {
max-width: 498px;
background-color: #fff;
border: 1px solid #E5E7EB;
padding: 24px;
border-radius: var(--16, 16px);
}
.donut-main {
padding: 10px;
}
/* Donut Head */
.overall_text {
position: absolute;
top: 92px;
left: 82px;
text-align: center;
font-family: Inter;
font-size: 24px;
font-style: normal;
font-weight: 700;
line-height: 150%;
/* 36px */
letter-spacing: -0.24px;
}
.graph-two h3 {
color: #000;
font-family: Inter;
font-size: 18px;
font-style: normal;
font-weight: 500;
line-height: 18px;
text-align: center;
}
.donut-result {
display: flex;
align-items: center;
}
.donut-result span:first-child {
display: inline-block;
width: var(--4, 16px);
height: var(--4, 16px);
border-radius: 999px;
background-color: #1C64F2;
margin-right: 8px;
}
.donut-result span:nth-child(2) {
color: #31374A;
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 120%;
margin-right: 8px;
}
.donut-result span:last-child {
color: #000;
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 700;
line-height: 120%;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="graph-two">
<div class="row">
<div class="col-lg-6 ">
<h3>Listings Limit</h3>
<div class="donut-main position-relative">
<div style="max-width: 100%; overflow: auto;">
<canvas id="donutGraph" style="max-width: 100%;"></canvas>
</div>
<div class="overall_text">30%</div>
</div>
<div class="donut-result mt-3 mb-3">
<span></span>
<span>Your Listings</span>
<span>2929</span>
</div>
<div class="donut-result">
<span style="background-color: #E1EFFE;"></span>
<span>Max Listings</span>
<span>10,000</span>
</div>
</div>
<div class="col-lg-6 ">
<h3>Gross Revenue</h3>
<div class="donut-main position-relative">
<div style="max-width: 100%; overflow: auto;">
<canvas id="donutGraphtwo" style="max-width: 100%;"></canvas>
</div>
<div class="overall_text">70%</div>
</div>
<div class="donut-result mt-3 mb-3">
<span style="background-color: #0E9F6E;"></span>
<span>Your Revenue</span>
<span>$350</span>
</div>
<div class="donut-result">
<span style="background-color: #DEF7EC;"></span>
<span>Max Revenue</span>
<span>$999,999</span>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
I have a file “example.html” in my bot directory, I would like to make a button on my bot so that when I click it I download this document to my computer. How could I do this?
I am working in a forest project using angular and cesiumjs, and when I upload 100 trees into cesium ion and call it from my code, my viewer is completly slow. So, I found that instancing is a good idea to solve that problem, but I don’t know how to instance it
I what tryin with this code:
const treePOsitions = [
[-77.029383, -12.125592],
[-77.02938, -12.125692],
[-77.029382, -12.125804],
[-77.029384, -12.125916],
[-77.029382, -12.12535]
]
const resource = await IonResource.fromAssetId(2331166);
treePOsitions.forEach((tree) =>
this.createNAddModels({ resource, x: tree[0], y: tree[1], z: 0, modelid: 0 })
);
async createNAddModels({ resource, x, y, z, modelid }) {
try {
const origin = Cartesian3.fromDegrees(x, y, z);
const hpr = new HeadingPitchRoll(0.0, 0.0, 0.0);
const modelMatrix = Transforms.headingPitchRollToFixedFrame(origin, hpr);
const model = varCesiumViewer.scene.primitives.add(
await Model.fromGltfAsync({
url: resource,
modelMatrix: modelMatrix,
})
);
} catch (error) {console.log(error)}
}
but my fps is still in 17fps and when I move fast it downs to 9fps or less. this is the correct way? or there is another way to improve the instancing and improve my fps.
Thank you!!
I wrote a brainfuck compiler in javascript and it works fine with this code:
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>—.+++++++..+++.>>.<-.<.+++.——.——–.>>+.>++.
(output: Hello World!)
But the nested loop runs into an infinite loop. The nested loop:
+[-[<<[+[—>]-[<<<]]]>>>-]>-.—.>..>.<<<<-.<+.>>>>>.>.<<.<-.
(output: hello world)
What sould I modify?
Here is the code:
class BrainfuckInterpreter {
constructor() {
this.memory = new Array(30000).fill(0); // Brainfuck memory tape
this.pointer = 0; // Memory pointer
this.inputBuffer = ''; // Input buffer for ,
this.outputBuffer = ''; // Output buffer for .
this.loopStack = []; // Stack to keep track of loop positions
}
interpret(code, input) {
this.inputBuffer = input;
this.outputBuffer = '';
this.pointer = 0;
this.loopStack = [];
for (let i = 0; i < code.length; i++) {
const command = code.charAt(i);
switch (command) {
case '>':
this.pointer++;
break;
case '<':
this.pointer--;
break;
case '+':
this.memory[this.pointer]++;
break;
case '-':
this.memory[this.pointer]--;
break;
case '.':
this.outputBuffer += String.fromCharCode(this.memory[this.pointer]);
break;
case ',':
if (this.inputBuffer.length > 0) {
this.memory[this.pointer] = this.inputBuffer.charCodeAt(0);
this.inputBuffer = this.inputBuffer.slice(1);
} else {
this.memory[this.pointer] = 0;
}
break;
case '[':
if (this.memory[this.pointer] === 0) {
let depth = 1;
while (depth > 0) {
i++;
if (code.charAt(i) === '[') depth++;
if (code.charAt(i) === ']') depth--;
}
} else {
this.loopStack.push(i);
}
break;
case ']':
if (this.memory[this.pointer] !== 0) {
i = this.loopStack[this.loopStack.length - 1];
} else {
this.loopStack.pop();
}
break;
}
}
return this.outputBuffer;
}
}
function Compile()
{
// Example usage:
let code = '+[-[<<[+[--->]-[<<<]]]>>>-]>-.---.>..>.<<<<-.<+.>>>>>.>.<<.<-.';
let input = '';
const interpreter = new BrainfuckInterpreter();
let output = interpreter.interpret(code, input);
// Display the output
document.getElementById('output_field').innerText = this.output;
console.log(output);
}
I am having a problem when using a djikstra on a multigraph. I basically have a graph, that each node represents a stop and contains some information about the stop, including connections to the next stop (edges). The problem is that between two nodes, I have multiple connections (edges) which represents different buses that I can use to move to the next stop.
Example:
I can go from stop A to stop B using bus 1, bus 2, bus 3, etc.
It gives me a path, but is not the optimal due to choosing an incorrect bus.
I also have stops with the same name (which are stops with different directions).
My graph looks like:
{
...,
"5382778889": {
"name": "Praça dos Heróis",
"coordinates": {
"latitude": -25.9351311,
"longitude": 32.5792925
},
"street": "Av. Acordos de Lusaka",
"connections": [
{
"stop": 6797387579,
"bus": 10046632,
"path": [...]
},
{
"stop": 6797387579,
"bus": 10053951,
"path": [...]
},
{
"stop": 6797387579,
"bus": 10053954,
"path": [...]
},
{
"stop": 6797387579,
"bus": 10053956,
"path": [...]
},
{
"stop": 6797387579,
"bus": 10070649,
"path": [...]
}
],
"walking_connections": [
{
"stop": "5382778890"
}
]
},
"5382778890": {
"name": "Praça dos Heróis",
"coordinates": {
"latitude": -25.9351503,
"longitude": 32.5794082
},
"street": "Av. Acordos de Lusaka",
"connections": [
{
"stop": 5382778885,
"bus": 10046631,
"path": [...]
},
{
"stop": 5382778885,
"bus": 10053950,
"path": [...]
},
{
"stop": 5382778885,
"bus": 10053955,
"path": [...]
},
{
"stop": 5382778885,
"bus": 10070980,
"path": [...]
},
{
"stop": 5382778885,
"bus": 10102978,
"path": [...]
}
],
"walking_connections": [
{
"stop": "5382778889"
}
]
},
...
}
My djikstra algorithm looks like this:
findPaths(stops, startPoint, endPoint) {
const distance = {};
const queue = new PriorityQueue();
const previous = {};
const buses = {};
const visited = new Set();
for (const stop in stops) {
distance[stop] = stop == startPoint ? 0 : Infinity;
queue.enqueue(stop, distance[stop]);
};
while (!queue.isEmpty()) {
const currentStop = Number(queue.dequeue());
if (visited.has(currentStop)) {
continue;
};
visited.add(currentStop);
if (currentStop == endPoint) {
const shortestPath = [];
let stop = {
stop: endPoint,
name: stops[endPoint].name,
coordinates: stops[endPoint].coordinates,
street: stops[endPoint].street,
path: [],
bus: null,
};
while (stop) {
shortestPath.unshift({...stop});
stop = previous[stop.stop];
};
return shortestPath;
};
if (stops[currentStop] && stops[currentStop].connections) {
for (const connection of stops[currentStop].connections) {
const nextStop = connection.stop;
const nextBus = connection.bus;
const pathUsed = connection.path;
let weight = 200;
if (previous[currentStop] && previous[currentStop].bus) {
if (nextBus == previous[currentStop].bus.id) {
weight = 10;
};
};
const newDistance = distance[currentStop] + weight;
if (newDistance < distance[nextStop]) {
distance[nextStop] = newDistance;
previous[nextStop] = {
stop: currentStop,
name: stops[currentStop].name,
coordinates: stops[currentStop].coordinates,
street: stops[currentStop].street,
path: pathUsed,
bus: this.BusUseCase.getBusById(nextBus),
};
queue.enqueue(nextStop, newDistance);
};
};
};
if (stops[currentStop].walking_connections) {
for (const connection of stops[currentStop].walking_connections) {
const nextStop = connection.stop;
const newDistance = distance[currentStop] + (stops[currentStop].name !== stops[nextStop].name ? 50 : 0);
if (newDistance < distance[nextStop]) {
distance[nextStop] = newDistance;
previous[nextStop] = {
stop: currentStop,
name: stops[currentStop].name,
coordinates: stops[currentStop].coordinates,
street: stops[currentStop].street,
path: [],
bus: null,
};
queue.enqueue(nextStop, newDistance);
};
};
};
};
return [];
};
Id like to make my muiStaticTimePicker component reactive and shrink in size. I currently am displaying it in a modal and would like the clock part on top and full round clock on the bottom. Thank you !!
<div className={`${boxOpen ? "" : "hidden"} mb-20`} >
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticTimePicker
orientation="landscape"
slotProps={{ actionBar: { actions: [] } }}
onChange={handleTimeChange}
defaultValue={dayjs()}
/>
</LocalizationProvider>
</div>
I am trying to show for each test case the previous build status of the test case. I am trying to achieve using test.info() in playwright. But test.info() cannot be accessed from onTestEnd in playwright. I will need to fetch the previous build data from jenkins. Any inputs please.
I tried storing the build data in gsheet and access them on each run. But it seems to be very complex. Any ways to achieve this easily?
I’m using Postman to HTTP GET this URL:
The request works and it returns the JSON I’m expecting. When I use the “copy as curl” feature, the request works in my Terminal.
curl –location
‘https://redsky.target.com/redsky_aggregations/v1/web/plp_search_v2?key=9f36aeafbe60771e321a7cc95a78140772ab3e96&category=0snqs&channel=WEB&count=24&default_purchasability_filter=true&faceted_value=55e6uZakkosZ5tdv0Z55dgnZnqueqc6d44fZ54jftZ4bmrplmkj9nZpyq1lZwlkrxZkpg5pZ4bmrpllkdobZ56ds9Zfmt6gZ4bmrpli4j3qZ57yv4Z55kh9Z4bmrplqkc0lZpu2iyZftml9&include_sponsored=true&new_search=false&offset=48&page=%2Fc%2F0snqs&platform=desktop&pricing_store_id=746&scheduled_delivery_store_id=746&sort_by=newest&store_ids=746%2C1075%2C3424%2C2843%2C2848&useragent=Mozilla%2F5.0%2B%28Windows%2BNT%2B10.0%3B%2BWin64%3B%2Bx64%29%2BAppleWebKit%2F537.36%2B%28KHTML%2C%2Blike%2BGecko%29%2BChrome%2F119.0.0.0%2BSafari%2F537.36&visitor_id=018C306A752F02019455A6119EB0FB86&zip=33196’
–header ‘Cookie: mitata=ZDY4NmU2NDA3NjFlNGE2YjQ0YjAxY2NkMzY1OTU3MmRiNDFiOTAyY2UzOTRmMmQ3NTBlZDZlNDE3M2IxZTY2ZA==/@#/1701625898_/@#/cttujxbBJYtyKSbd_/@#/NGZhODVhZmNjY2UyZmJhOWE3MTk1MzQ0NWI5NmQwNDk4YTBhZTY2MWI0YjI1ZjQ5YzFhNmEwMjVhOWZmYzNlOA==_/@#/000′
After a few minutes the CURL request breaks, and I have to use Postman to make the GET request again because I noticed that the Cookie value is being changed automatically by Postman.
My question is how is Postman automatically refreshing this cookie value and how can I do this myself in code (any language like Python or Javascript is fine)?