<!DOCTYPE html>
<html lang="en">
<head>
<title>Multimedia Page</title>
</head>
<body>
<h2>Multimedia Page</h2>
<h3>Video Player</h3>
<video width="320" height="240" controls>
<source src="1.mp4" type="video/mp4">
</video>
<h3>Audio Player</h3>
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
</audio>
</body>
</html>
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) {
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
function modified_greater_than(x,y){ //CHANGED: ADDED modifed_greater_than function
if ((is_primitive_function(x) || is_compound_function(x)) && is_list(y)){
return map(p => apply(x, list(p)), y);
} else {
return x > y;
}
}
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", (x, y) => x + y ),
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", modified_greater_than),//CHANGED: replaced previous call with modified_greater_than
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// Use this evaluator in the Programmable REPL
set_evaluator(parse_and_evaluate);
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) {
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
//CHANGED: CREATED NEW modified_plus_interpretation function
function modified_plus_interpretation(x,y){
if (is_list(x) && is_list(y)){
return append(x,y);
} else {
return x + y;
}
}
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", modified_plus_interpretation), //CHANGED: ADDED modified_plus_interpretation function
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// Use this evaluator in the Programmable REPL
set_evaluator(parse_and_evaluate);
/*list(1, 2, 3) + list(4, 5, 6);*/
print("Goodbye, World!")
<!DOCTYPE html>
<html lang="en">
<head>
<title>To-Do List</title>
</head>
<body>
<input id="task" placeholder="New Task">
<button onclick="addTask()">Add</button>
<ul id="taskList"></ul>
<script>
function addTask() {
const task = document.getElementById("task").value;
if (task) {
const li = document.createElement("li");
li.textContent = task;
const removeBtn = document.createElement("button");
removeBtn.textContent = "Remove";
removeBtn.onclick = () => li.remove();
li.appendChild(removeBtn);
li.onclick = () => li.classList.toggle("completed");
document.getElementById("taskList").appendChild(li);
document.getElementById("task").value = "";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Grid and Flexbox</title>
<style>
body {
font-family: Arial, sans-serif;
}
.header, .footer {
display: flex;
justify-content: center;
align-items: center;
background: #4CAF50;
color: #fff;
height: 60px;
}
.content {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding: 20px;
}
.box {
padding: 20px;
background: #2196F3;
color: #fff;
text-align: center;
transition: transform 0.3s;
}
.box:hover { transform: scale(1.05); background: #1E88E5; }
</style>
</head>
<body>
<div class="header">Header</div>
<div class="content">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
<div class="footer">Footer</div>
</body>
</html>
let function_object_count = 1; //CHANGED: ADDED GLOBAL VARIABLE
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) { //CHANGED: ADDED FUNCTION OBJECT INCREMENT
function_object_count = function_object_count + 1;
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", (x, y) => x + y ),
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// set_evaluator configures the "Run" button
// in the Programmable REPL tab on the right
// to apply the given evaluate function to the
// program text in the Programmable REPL editor.
set_evaluator(parse_and_evaluate);
// your testing
function count_function_objects_created(program_string) {
function_object_count = 0;
parse_and_evaluate(program_string);
return function_object_count;
}
// use your function object counter in the Programmable REPL
set_evaluator(count_function_objects_created);
/*
Test function:
function fun(x){
const y = x => x * 2;
function inner(a){
return g;
}
return inner(y);
}
const g = a => a * 3;
fun(2);
*/
let frame_count = 0; // CHANGED: ADDED GLOBAL VARIABLE
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) {
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { //CHANGED: ADDED FRAME INCREMENT
frame_count = frame_count + 1;
return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", (x, y) => x + y ),
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// set_evaluator configures the "Run" button
// in the Programmable REPL tab on the right
// to apply the given evaluate function to the
// program text in the Programmable REPL editor.
set_evaluator(parse_and_evaluate);
// your testing
function count_frames_created(program_string) {
frame_count = 0;
evaluate(parse("{ " + program_string + " }"),
the_global_environment);
return frame_count;
}
// use your frame counter in the Programmable REPL
set_evaluator(count_frames_created);
/*
function fun(x){
return g;
}
const g = x => x * x;
fun(2);
*/
#Open the path: C:\Users\MuraliM\AppData\Local\Microsoft\Edge\User Data #backup the file 'Local State'
C Program to Construct Shortest Path Tree (SPT):
#include <stdio.h>
#include <limits.h>
#define V 5 // Define the number of vertices in the graph
// Function to find the vertex with the minimum distance value
int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == 0 && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// Function to print the constructed tree and distances
void printTree(int parent[], int dist[], int src) {
printf("Shortest Path Tree:\n");
printf("Vertex\tDistance from Source\tParent\n");
for (int i = 0; i < V; i++) {
printf("%d\t\t%d\t\t%d\n", i, dist[i], parent[i]);
}
}
// Dijkstra's algorithm to construct the shortest path tree
void dijkstra(int graph[V][V], int src) {
int dist[V]; // dist[i] will hold the shortest distance from src to i
int sptSet[V]; // sptSet[i] will be true if vertex i is included in SPT
int parent[V]; // To store the shortest path tree
// Initialize all distances as INFINITE and sptSet[] as false
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
parent[i] = -1; // Parent of the root node will be -1
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find the shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet
processed
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = 1;
// Update dist value of the adjacent vertices of the picked vertex
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] +
graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u; // Update the parent of vertex v
}
}
// Print the constructed shortest path tree
printTree(parent, dist, src);
}
int main() {
// Example graph represented using an adjacency matrix
int graph[V][V] = {
{0, 10, 0, 0, 5}, // Node 0 to 1 has weight 10, to 4 has weight 5
{0, 0, 1, 0, 3}, // Node 1 to 2 has weight 1, to 4 has weight 3
{0, 0, 0, 4, 0}, // Node 2 to 3 has weight 4
{7, 0, 6, 0, 0}, // Node 3 to 0 has weight 7, to 2 has weight 6
{0, 3, 9, 2, 0} // Node 4 to 1 has weight 3, to 2 has weight 9, to 3 has weight
2
};
// Source node for the algorithm
int source = 0;
// Call Dijkstra's algorithm to construct the shortest path tree
dijkstra(graph, source);
return 0;
}
{
...
"content_security_policy": {
"sandbox": "sandbox allow-scripts; script-src 'self' https://example.com"
},
"sandbox": {
"pages": [
"page1.html",
"directory/page2.html"
]
},
...
}
{
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": " :star: Boost Days: What's on in Melbourne! :star: "
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n\n Hey Melbourne, happy Monday! Please see below for what's on this week. "
}
},
{
"type": "divider"
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Xero Café ",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n :new-thing: *This week we are offering:* \n\n Yo Yo Biscuits, Funny Face Biscuits & Jumbo Smarties Cookies :cookie: \n\n *Weekly Café Special:* _ *French Mint Hot Chocolate* _ :frenchie:"
}
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": " Wednesday, 13th November :calendar-date-13:",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n\n :tart: Afternoon Tea from *2pm* in the L3 kitchen \n\n"
}
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Thursday, 14th November :calendar-date-14:",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am - 10:30am* in the Wominjeka Breakout Space.\n\n "
}
},
{
"type": "divider"
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":magic-blob: :xero-unicorn: End of Year Event - A Sprinkle of Magic :xero-unicorn: :magic-blob:",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n\n *Date:* 28th November 2024 \n*Time:* 4pm - 10pm \n *Location:* The Timber Yard, Port Melbourne \nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nRegistrations close on the *_14th November 2024_* :party-wx:"
}
}
]
}
$text = "Your text goes here" $filePath = "C:\path\to\your\file.txt" $text | Out-File -FilePath $filePath Start-Process notepad.exe $filePath
//1 ....datapreprocessing**************************************************
import pandas as pd
df=pd.read_csv("/content/sample.csv")
#print(df)
print("DATA SET:\n", df)
print("DATA SET SIZE:",df.size)
print("DATA SET SHAPE:",df.shape)
print("DATA SET DIMENSIONS:",df.ndim)
print("Head\n",df.head())
print("Tail\n", df.tail())
print("Head(2)\n",df.head(2))
print("Tail(2)\n",df.tail(2))
print("Head(-2)\n",df.head(-2))
print("Tail(-2) \n",df.tail(-2))
print("DATA TYPES")
df.info()
print("STATISTICS:\n",df.describe().T)
print("FRE. COUNT OF RECORDS:\n",df.value_counts())
print("\nFRE. COUNT OF GENDER",df['GENDER'].value_counts())
#print("TWO FEATURES FRQ", df[['GENDER','M1']].value_counts())
print("\nEXISTANCE of NaNs in data set", df.isna())
print("\nCOL-WISE NaNs in data set", df.isna().sum())
print("\nOVERALL NaNs in data set", df.isna().sum().sum())
print("\nTOT NaNs in M1", df['M1'].isna().sum())
print("\nBefore Filling\n", df)
df['M1'].fillna(df['M1'].mean(),inplace=True) #saving update/permament
df['PHY'].fillna(df['PHY'].mean(),inplace=True) #saving update/permament
print("\nAFTER Filling\n", df)
print("BEFORE DROP - DF")
print(df)
df.drop_duplicates('SID',keep='first',inplace=True,ignore_index=True)
print("AFTER DROP DF")
print(df)
def remove_outliers_iqr(df, column):
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
print("lower_bound :",lower_bound,"upper_bound:",upper_bound)
return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
# Remove outliers from the 'Math' column
df_no_outliers_math = remove_outliers_iqr(df, 'M1')
print("\nDataFrame after Removing Outliers in 'M1':")
print(df_no_outliers_math)
import matplotlib.pyplot as plt
import seaborn as sns
# Line Plot
plt.plot(df['M1'], df['PHY'],color='green')
plt.xlabel('M1')
plt.ylabel('PHY')
plt.title('Line Plot')
plt.show()
# Scatter Plot
plt.scatter(df['M1'], df['PHY'])
plt.xlabel('M1')
plt.ylabel('PHY')
plt.title('Scatter Plot')
plt.show()
plt.hist(df['M1'], bins=30, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
sns.boxplot(data=df)
plt.title('Box Plot')
plt.show()
sns.pairplot(df)
plt.title('Pair Plot')
plt.show()
sns.barplot(x='GENDER', y='M1', data=df)
plt.title('Bar Plot')
plt.show()
2.regression************************************************************
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn import metrics
# Sample data
df=pd.read_csv("/content/Stud_Data.csv")
# Reshape the data :: Single Feature
hours_studied = np.array(df["hours_studied"])
print(hours_studied.shape)
hours_studied =hours_studied.reshape(-1, 1)
print(hours_studied.shape)
scores=df["scores"]
# Create a linear regression model
model = LinearRegression()
# Fit the model
model.fit(hours_studied, scores)
#Print the Parameters
print("Beta 0 :", model.intercept_)
print("Beta 1 :", model.coef_[0])
#Regression Model
print("Y=",model.intercept_,"+",model.coef_[0],"X")
# Make predictions
predicted_scores = model.predict(hours_studied)
df["predicted_scores"]=predicted_scores
print("ORIGINAL SCORES:\n",df["scores"])
print("PREDICTED SCORES:\n",df["predicted_scores"])
print("MAE",metrics.mean_absolute_error(scores,predicted_scores))
print("MSE",metrics.mean_squared_error(scores,predicted_scores))
print("RMSE",np.sqrt(metrics.mean_squared_error(scores,predicted_scores)))
r2 = metrics.r2_score(scores,predicted_scores)
print('r2 score/Coefficient of Determination for perfect model is', r2)
print("\nCorrelation Coefficient: r =",df['hours_studied'].corr(df['scores']))
### USING MACHINE LEARNING APPROACH
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Sample data
df=pd.read_csv("/content/AgeData.csv")
#print(df.describe())
x = df[['Income (in $1000s)', 'Education Level (Years)', 'Years of Experience']]
y= df['Age']
#print(x)
#print(y)
x_train, x_test, y_train, y_test=train_test_split(x, y, test_size = 0.3)
#Fitting the Multiple Linear Regression model
mlr = LinearRegression()
mlr.fit(x_train, y_train)
#Intercept and Coefficient
print("Intercept: (Beta 0) ", mlr.intercept_)
#print("Coefficients:")
#print(list(zip(x, mlr.coef_)))
print("\nCoefficients:\n Beta 1:",mlr.coef_[0])
print("\n Beta 2:",mlr.coef_[1])
print("\n Beta 3:",mlr.coef_[2])
print("\nRegression Equation:",mlr.intercept_,"+",mlr.coef_[0],"*Income (in $1000s)+"
,mlr.coef_[1],"*Education Level (Years)+",mlr.coef_[2],"*Years of Experience")
#Prediction of test set
y_pred_mlr= mlr.predict(x_test)
meanAbErr = metrics.mean_absolute_error(y_test, y_pred_mlr)
meanSqErr = metrics.mean_squared_error(y_test, y_pred_mlr)
rootMeanSqErr = np.sqrt(metrics.mean_squared_error(y_test, y_pred_mlr))
#print('\nR squared: {:.2f}'.format(mlr.score(x,y)*100))
print('\nR squared: {:.2f}'.format(mlr.score(x,y)))
print('Mean Absolute Error:', meanAbErr)
print('Mean Square Error:', meanSqErr)
print('Root Mean Square Error:', rootMeanSqErr)
#### PREDICTING AGE BASED ON TEST/NEW OBSERVATION
newobs_df=pd.DataFrame([[38,15,12]], columns=x.columns)
y_pred_new= mlr.predict(newobs_df)
print("PREDICTED AGE OF NEW RESPONDENT",y_pred_new[0])
5 a..decision tree**********************************************
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report,accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# Load and display top 2 records of the Soybean dataset
df=pd.read_csv("/content/Soybean.csv")
print(df.head(2))
# DATA EXPLORATION
#Data set details/info
print(df.info())
print(df.describe())
#### DATA PRE-PROCESSING
# Missing Values , Duplicated and Outliers Handling
# Handling Missing Values
#Verify Missing Values
#print(df.isna().sum())
#Fill Missing Values with mean value of the respective feature/column
cols=list(df.columns)
print("Before Pre-Processing - Total Missing Values",df.isna().sum().sum())
for i in range(0,len(cols)-1):
#print(cols[i])
if(df[cols[i]].isna().sum()>0):
df[cols[i]].fillna(df[cols[i]].mean(),inplace=True)
print("After Pre-Processing - Total Missing Values",df.isna().sum().sum())
# Handling Duplicate Values
#Verify Duplicate Values/records
print("BEFORE DROP :: DATA SIZE", df.shape)
df.drop_duplicates(keep="first",inplace=True)
#Verify Duplicate Values/records
print("AFTER DROP :: DATA SIZE", df.shape)
# Handling Outliers
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(20, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Soybean Dataset Features")
plt.show()
''' NOTE:: DATA HAS OUTLIERS BUT THEY ARE VALID RESPONSES , HENCE WE ARE NOT DROPPING THE OUTLIERS.
IF THEY ARE REALLY OUTLERS THEN WE SHOULD DROP THE OUTLIERS USING THE BELOW CODE
# #DROP Outliers
# def remove_outliers_iqr(df, column):
# Q1 = df[column].quantile(0.25)
# Q3 = df[column].quantile(0.75)
# IQR = Q3 - Q1
# lower_bound = Q1 - 1.5 * IQR
# upper_bound = Q3 + 1.5 * IQR
# print(column,":","lower_bound :",lower_bound,"upper_bound:",upper_bound)
# return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
# # Remove outliers from the 'sepal_width' column
# print("BOX PLOT - B4", df.shape)
# for i in range(0,len(cols)-1):
# df = remove_outliers_iqr(df, cols[i])
# print("BOX PLOT - AFTER", df.shape)
'''
### MACHINE LEANING MODEL DESIGN AND EVALUATION
#Feature Set
X= df.iloc[:, :-1] #"Input Features
#Target Variable/ Classs variable
Y=df.iloc[:, [-1]]
# print("Input Features (X) : \n" , X)
# print("Target Variable/Class Variable (Y) : \n" , Y)
# Split data into train and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Initialising Decision Tree Classifier
clf = DecisionTreeClassifier()
clf.fit(X_train,Y_train)
# Train the model
# Y_train array Should be flatten into a 1D array
clf.fit(X_train, np.array(Y_train).ravel())
# Predict on the test data
Y_pred = clf.predict(X_test)
# Print accuracy
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy:.2f}")
# # Print detailed classification report
# report = classification_report(Y_test, Y_pred)
# print("Classification Report:")
# print(report)
#Predict the class of the new observation
new_observation= pd.DataFrame([[6,0,2,1,0,3,0,1,1,1,1,1,0,2,2,0,0,0,1,0,3,1,1,1,0,0,0,0,4,0,0,0,0,0,0]], columns=X.columns)
predicted_class = clf.predict(new_observation)
print("Predicted Class of NEW OBSERVATION :: ", predicted_class[0])
5 b knn*************************************************************
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report,accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# Load the Iris dataset
df=pd.read_csv("/content/sample_data/Iris.csv")
# DATA EXPLORATION
print(df.head())
print(df.info())
print(df.describe())
#Verify Missing Values
print(df.isna().sum())
#Verify Duplicate Values/records
print("BEFORE", df[df.duplicated()])
df.drop_duplicates(keep="first",inplace=True)
#Verify Duplicate Values/records
print("AFTER",df[df.duplicated()])
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(12, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Iris Dataset Features")
plt.show()
#DROP Outliers
def remove_outliers_iqr(df, column):
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
print("lower_bound :",lower_bound,"upper_bound:",upper_bound)
return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
# Remove outliers from the 'sepal_width' column
df_no_outliers_sepal_width = remove_outliers_iqr(df, 'sepal_width')
print("\nDataFrame after Removing Outliers in 'sepal_width':")
print(df_no_outliers_sepal_width)
df=df_no_outliers_sepal_width
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(12, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Iris Dataset Features AFTER OULIERS DROPPED")
plt.show()
### MACHINE LEANING MODEL DESIGN AND EVALUATION
#Feature Set
X= df.iloc[:, :-1]
#Target Variable/ Classs variable
Y=df.iloc[:, [-1]]
print("Input Features (X) : \n" , X)
print("Target Variable/Class Variable (Y) : \n" , Y)
# Split data into train and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Initialize KNN classifier
k = 3 # Define the number of neighbors
knn = KNeighborsClassifier(n_neighbors=k)
# Train the model
# Y_train array Should be flatten into a 1D array
knn.fit(X_train, np.array(Y_train).ravel())
# Predict on the test data
Y_pred = knn.predict(X_test)
# Print accuracy
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy:.2f}")
# Print detailed classification report
report = classification_report(Y_test, Y_pred)
print("Classification Report:")
print(report)
#Predict the class of the new observation
#new_observation with sepal_length sepal_width petal_length petal_width
new_observation= pd.DataFrame([[5.1, 3.5, 1.4, 0.2]], columns=X.columns)
predicted_class = knn.predict(new_observation)
print("Predicted Class of NEW OBSERVATION :: ", predicted_class[0])
6.random forest *************************************************
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report,accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# Load and display top 2 records of the Soybean dataset
df=pd.read_csv("/content/Loandata.csv")
# DATA EXPLORATION
print(df.info())
#print(df.head(2))
#DROP LOAN ID - NOT USEFUL IN ANALYSIS
df.drop(labels='Loan_ID', axis=1, inplace=True)
#REPLACE DEPENDENTS COUNT 3+ to 3
df['Dependents'] = df['Dependents'].replace('3+', '3')
#Missing Values Management
print("Before :: MISSING VALUE COUNT\n",df.isna().sum())
df['Gender'].fillna(df['Gender'].mode()[0],inplace=True)
df['Married'].fillna(df['Married'].mode()[0],inplace=True)
df['Dependents'].fillna(df['Dependents'].mode()[0],inplace=True)
df['Education'].fillna(df['Education'].mode()[0],inplace=True)
df['Self_Employed'].fillna(df['Self_Employed'].mode()[0],inplace=True)
df['Property_Area'].fillna(df['Property_Area'].mode()[0],inplace=True)
df['Loan_Status'].fillna(df['Loan_Status'].mode()[0],inplace=True)
df['Credit_History'].fillna(df['Credit_History'].mode()[0],inplace=True)
### FILL WITH MEAN
df['LoanAmount'].fillna(df['LoanAmount'].mean(),inplace=True)
df['Loan_Amount_Term'].fillna(df['Loan_Amount_Term'].mean(),inplace=True)
print("After :: MISSING VALUE COUNT\n",df.isna().sum())
# Handling Duplicate Values
#Verify Duplicate Values/records
print("BEFORE DROP :: DATA SIZE", df.shape)
df.drop_duplicates(keep="first",inplace=True)
#Verify Duplicate Values/records
print("AFTER DROP :: DATA SIZE", df.shape)
# Handling Outliers
#NOTE:: DATA HAS OUTLIERS BUT THEY ARE VALID RESPONSES , HENCE WE ARE NOT DROPPING THE OUTLIERS.
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(20, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Soybean Dataset Features")
plt.show()
#DATA TRANSORMATION
# Initialize the LabelEncoder
label_encoder = LabelEncoder()
print(df['Loan_Status'].value_counts())
# Fit and transform the columns
df['Gender'] = label_encoder.fit_transform(df['Gender'])
df['Married'] = label_encoder.fit_transform(df['Married'])
df['Education'] = label_encoder.fit_transform(df['Education'])
df['Self_Employed'] = label_encoder.fit_transform(df['Self_Employed'])
df['Property_Area'] = label_encoder.fit_transform(df['Property_Area'])
df['Loan_Status'] = label_encoder.fit_transform(df['Loan_Status'])
print(df['Loan_Status'].value_counts())
df.to_csv('CleanFile.csv', index=False)
### MACHINE LEANING MODEL DESIGN AND EVALUATION
#Feature Set
X= df.iloc[:, :-1] #"Input Features
#Target Variable/ Classs variable
Y=df.iloc[:, [-1]]
# print("Input Features (X) : \n" , X)
# print("Target Variable/Class Variable (Y) : \n" , Y)
# Split data into train and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Ensure Y_train and Y_test are 1D arrays
Y_train = np.array(Y_train).ravel()
Y_test = np.array(Y_test).ravel()
# Train a Random Forest Classifier
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, Y_train)
# Train the model
# Y_train array Should be flatten into a 1D array
clf.fit(X_train, Y_train)
# Predict on the test data
Y_pred = clf.predict(X_test)
# Print accuracy
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy:.2f}")
# Print detailed classification report
report = classification_report(Y_test, Y_pred)
print("Classification Report:")
print(report)
#Predict the class of the new observation
new_observation= pd.DataFrame([[1,1,0,1,0,2583,2358.0,120.0,360.0,1.0,2]], columns=X.columns)
predicted_class = clf.predict(new_observation)
#### 0 - NO 1 - YES
if (predicted_class[0]=='0') :
classLable="No"
else:
classLable="Yes"
print("Predicted Class of NEW OBSERVATION :: ",classLable)
1.mergesort***********************************************
import java.util.Scanner;
import java.util.Arrays;
public class Mergesort {
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
public static void merge(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
for (int i = 0; i < n1; i++) {
leftArray[i] = array[left + i];
}
for (int j = 0; j < n2; j++) {
rightArray[j] = array[mid + 1 + j];
}
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Original array:"+Arrays.toString(array));
mergeSort(array, 0, array.length - 1);
System.out.println("Sorted array:"+Arrays.toString(array));
scanner.close();
}
}
2.quicksort*****************************************************************
import java.util.Scanner;
import java.util.Arrays;
public class QuickSort {
// Main method that sorts the array
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
// Partition the array and get the pivot index
int pivotIndex = partition(array, low, high);
// Recursively sort the elements before and after partition
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
// Partition method with the first element as pivot
private static int partition(int[] array, int low, int high) {
int pivot = array[low]; // Choosing the first element as pivot
int i = low + 1; // Start from the element after the pivot
for (int j = low + 1; j <= high; j++) {
// If the current element is smaller than or equal to the pivot
if (array[j] <= pivot) {
swap(array, i, j);
i++;
}
}
// Swap the pivot element with the element at index i-1
swap(array, low, i - 1);
return i - 1; // Return the partitioning index
}
// Swap helper method
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// Method to print the array
// Main method to test the algorithm
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Original array:"+Arrays.toString(array));
quickSort(array, 0, array.length - 1);
System.out.println("Sorted array:"+Arrays.toString(array));
scanner.close();
}
}
3.articulation point**************************************************************
import java.util.*;
public class Articulation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int v = sc.nextInt(); // Number of vertices
int[][] adj = new int[v + 1][v + 1];
// Input adjacency matrix
System.out.println("Enter adjacency matrix:");
for (int i = 1; i <= v; i++) {
for (int j = 1; j <= v; j++) {
adj[i][j] = sc.nextInt();
}
}
System.out.println("Articulation points are:");
// Finding articulation points
for (int i = 1; i <= v; i++) {
boolean[] visited = new boolean[v + 1];
int components = 0;
// Counting connected components when vertex i is ignored
for (int j = 1; j <= v; j++) {
if (j != i && !visited[j]) {
dfs(j, visited, adj, v, i);
components++;
}
}
// If more than one component, i is an articulation point
if (components > 1) {
System.out.println(i);
}
}
}
private static void dfs(int curr, boolean[] visited, int[][] adj, int v, int ignore) {
visited[curr] = true;
for (int k = 1; k <= v; k++) {
if (adj[curr][k] == 1 && k != ignore && !visited[k]) {
dfs(k, visited, adj, v, ignore);
}
}
}
}
4.prims*************************************************************************
import java.util.*;
public class Prims {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int n = sc.nextInt();
int[][] graph = new int[n][n];
System.out.println("Enter adjacency matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = sc.nextInt();
}
}
// Arrays to store the MST data
boolean[] inMST = new boolean[n];
int[] key = new int[n];
int[] parent = new int[n];
// Initialize keys as infinite, and select the first vertex to start
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0;
parent[0] = -1;
// Prim's algorithm loop
for (int i = 0; i < n - 1; i++) {
int u = minKey(key, inMST, n); // Find vertex with minimum key value
inMST[u] = true; // Include this vertex in MST
// Update the key and parent arrays
for (int v = 0; v < n; v++) {
if (graph[u][v] != 0 && !inMST[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Output the edges of the MST
int totalWeight = 0;
System.out.println("Edge \tWeight");
for (int i = 1; i < n; i++) {
System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
totalWeight += graph[i][parent[i]];
}
System.out.println("Total weight of MST: " + totalWeight);
}
// Function to find the vertex with the minimum key value
static int minKey(int[] key, boolean[] inMST, int n) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < n; v++) {
if (!inMST[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
}
5.knapsack*****************************************************************
import java.util.*;
public class Knapsack1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of objects");
int n = sc.nextInt();
int[] p = new int[n];
int[] w = new int[n];
System.out.println("Enter the item weight and value:");
for (int i = 0; i < n; i++) {
System.out.println("Item " + (i + 1) + " weight:");
w[i] = sc.nextInt();
System.out.println("Item " + (i + 1) + " profit:");
p[i] = sc.nextInt();
}
System.out.println("Enter maximum knapsack capacity:");
int m = sc.nextInt();
sort(w, p);
double maxProfit = 0;
double remainingCapacity = m;
System.out.println("Selected items:");
for (int i = 0; i < w.length; i++) {
if (remainingCapacity >= w[i]) {
maxProfit += p[i];
remainingCapacity -= w[i];
System.out.println("Added item with weight " + w[i] + " and profit " + p[i]);
} else {
double fraction = remainingCapacity / (double) w[i];
maxProfit += p[i] * fraction;
System.out.println(
"Added fraction: " + fraction + " of item with weight " + w[i] + " and profit " + p[i]);
break;
}
}
System.out.println("Maximum profit: " + maxProfit);
}
public static void sort(int[] w, int[] p) {
// Sort items based on profit-to-weight ratio in descending order
for (int i = 0; i < w.length - 1; i++) {
for (int j = i + 1; j < w.length; j++) {
double ratio1 = (double) p[i] / w[i];
double ratio2 = (double) p[j] / w[j];
if (ratio1 < ratio2) {
// Swap weights
int tempW = w[i];
w[i] = w[j];
w[j] = tempW;
// Swap profits
int tempP = p[i];
p[i] = p[j];
p[j] = tempP;
}
}
}
}
}
6.job sequencing*********************************************************
import java.util.Scanner;
public class JobSequencing
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of jobs: ");
int n = sc.nextInt();
int[] d = new int[n + 1];
int[] profits = new int[n + 1];
for (int i = 0; i < n; i++)
{
System.out.println("Enter the profits and deadlines of Job: " + (i + 1));
profits[i + 1] = sc.nextInt();
d[i + 1] = sc.nextInt();
}
// Arranging profits in descending order- therefore swaping deadlines too
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
if (profits[j] < profits[j + 1])
{
int temp = profits[j];
profits[j] = profits[j + 1];
profits[j + 1] = temp;
temp = d[j];
d[j] = d[j + 1];
d[j + 1] = temp;
}
}
}
// optimal sol logic
int[] j = new int[n + 1];
j[0] = 0;
d[0] = 0;
j[1] = 1;
int k = 1;
for (int i = 2; i <= n; i++)
{
int r = k;
while ((d[j[r]] > d[i]) && d[j[r]] != r)
{
r--;
}
if ((d[j[r]] <= d[i]) && d[i] > r)
{
for (int x = k; x >= r + 1; x--)
{
j[x + 1] = j[x];
}
j[r + 1] = i;
k++;
}
}
int profit = 0;
System.out.println("Final Job Sequence: ");
for (int i = 1; i < n + 1; i++)
{
System.out.println(j[i] + " ");
profit +=profits[j[i]];
}
System.out.println(profit);
}
}
7.shortestpath ****************************************************************
import java.util.*;
public class Source {
private static final int INF = Integer.MAX_VALUE; // Constant for infinity
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
int n = scanner.nextInt(); // Number of vertices
int[][] graph = new int[n][n]; // Initialize the adjacency matrix
// Input graph values from the user
System.out.println("Enter the adjacency matrix (0 for no edge):");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = scanner.nextInt();
}
}
single(graph, n, 0); // Start from vertex 0
scanner.close();
}
public static void single(int[][] graph, int n, int start) {
int[] dist = new int[n]; // Distance from source to each vertex
boolean[] s = new boolean[n]; // Track visited vertices
// Initialize distances based on direct edges from the start vertex
for (int i = 0; i < n; i++) {
dist[i] = (graph[start][i] != 0) ? graph[start][i] : INF;
s[i] = false;
}
dist[start] = 0; // Distance to the source is 0
s[start] = true; // Mark the starting vertex as visited
int count = 0;
do {
int u = minDistance(dist, s, n);
s[u] = true; // Mark the vertex as visited
// Update the distance of the adjacent vertices
for (int v = 0; v < n; v++) {
if (!s[v] && graph[u][v] != 0 && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
count++;
} while (count < n - 1);
// Print the distances and calculate the sum
int totalDistance = 0;
System.out.println("Vertex Distance from Source");
for (int i = 0; i < n; i++) {
if (dist[i] != INF) {
totalDistance += dist[i];
}
}
// Print the total distance
System.out.println("Total distance from source: " + totalDistance);
}
// Function to find the vertex with the minimum distance value
private static int minDistance(int[] dist, boolean[] s, int n) {
int min = INF, minIndex = -1;
for (int v = 0; v < n; v++) {
if (!s[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
}
////////******* IIFE IN JS ************///////////
// why IIFE is used in js ??
// IIFE function is used when we want to invoke function immediately and also removes pollution of global scope variables
// 1 method
// NAMED IIFE
(function chai(){
console.log("db connected");
})(); // // here we used ; because there is 2 IIFE in a programme
// here first() is for creating function and second () for calling the function
// 2 method
// UNNAMED IIFE
( (name) => { //name is function parameter in which we put value ,
console.log(`db connected${name}`);
})("tanishq"); // here tanishq is just passing value in name
// here first() is for creating function and second () for calling the function
////////*******THIS IN JS ************///////////
const user ={
username: "hitesh",
price: 999,
welcomeMessage: function(){
console.log(`${this.username}, welcome to website `);
// console.log(this); // it will print whole function
}
}
user.welcomeMessage() // hitesh, welcome to website
user.username = "harry"
user.welcomeMessage() // harry, welcome to website
console.log(this); // OUTPUT = {}
const chai = () => {
let username = "hitesh "
console.log(this);
}
chai()
///////////////********ARROW FUNCTION IN JS************//////////////
//// FIRST METHOD
const add2 = (num1 , num2 ) =>{ // implict function (when we use parethensis{} we have to write return also )
return num1 + num2
}
console.log(add2(2,3));
//// SECOND METHOD
const addtwo = (num1 , num2 ) => (num1 + num2) // explict function (when we don't use parethensis{} we have no need to write return also )
console.log(addtwo(5,3));
////////
Laravel Cache Clear php artisan optimize:clear php artisan cache:clear php artisan config:clear php artisan config:cache php artisan view:clear php artisan view:cache php artisan route:clear php artisan route:cache php artisan event:clear php artisan event:cache php artisan clear-compiled Clearing Composer Cache composer dump-autoload composer clear-cache composer clearcache composer cc Schedule Backup DB php artisan backup:run php artisan backup:run --only-db php artisan backup:clean
Secure File Transfer Protocol (SFTP) sftp> put – Upload file sftp> get – Download file sftp> cd path – Change remote directory to ‘path’ sftp> pwd – Display remote working directory sftp> lcd path – Change the local directory to ‘path’ sftp> lpwd – Display local working directory sftp> ls – Display the contents of the remote working directory sftp> lls – Display the contents of the local working directory sftp -P port usrename@your_server_ip_or_domain I.e sftp -P 39922 root@45.58.35.53 zip -r filename.zip /path/to/folder1 Secure Copy Protocol (SCP) -p: Use passive mode. This is not directly related to specifying the port but is a commonly used option for FTP connections. -u username: Specify the username to use for the FTP connection. hostname: The IP address or domain name of the FTP server. port: The port number on which the FTP server is running. -P 39922: Specifies the SSH port on the remote server (replace 39922 with your actual port if different). root: The username on the remote server. 45.58.35.53: The IP address or hostname of the remote server. /path/on/remote/server/file: The path to the file on the remote server. /path/on/local/machine: The destination path on your local machine. For upload File scp destinationor source scp -P 39922 /path/on/local/machine/file root@45.58.35.55:/path/on/remote/server scp -P 39922 /home/hur/quickinvoice_details_202309202129.sql root@45.58.35.53:/var/www/html/ For Download File scp source destinationor scp -P 39922 root@45.58.35.55:/path/on/remote/server/file /path/on/local/machine I.e scp -P 39922 root@45.58.35.53:/var/www/html/quickinvoice_details_202309202129.sql /home/hur/Music Rsync to copy or sync files between your servers rsync [option] [source] [destination] -a | copy files recursively -h | produce a readable output –progress | displays the process while the command is being run -q | processes running in the background will not be shown -v | processes that are run will be written out for the user to read -z | compress the data rsync [option] [source] user@hostname-or-ip:[destination path] rsync -avh root@5.252.161.46:/home/receive-rsync/ /home/test-rsync/ I.e rsync -e "ssh -p 39922" root@45.58.35.53:/var/www/html/quickinvoice_details_202309202129.sql /home/hur/Videos
sudo nano /etc/php/8.3/cli/php.ini sudo update-alternatives --config php sudo apt-get install php8.3-grpc php -m | grep grpc For uninstall sudo apt-get remove php8.3-grpc
{
"blocks": [
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Stay In the Know - November | 2024 \n\n Stay in the loop about what’s happening at the office such as upcoming visitors, onsite meetings, lunches, and more. Don’t miss out—click to subscribe below!",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":google-workspace-calendar: DEN Happenings calendar"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Me",
"emoji": true
},
"value": "click_me_123",
"url": "https://calendar.google.com/calendar/u/0/embed?src=xero.com_5r7ut3e120f1mfj5aptg90tm34@group.calendar.google.com&ctz=America/Denver",
"action_id": "button-action"
}
},
{
"type": "divider"
},
{
"type": "rich_text",
"elements": [
{
"type": "rich_text_section",
"elements": [
{
"type": "text",
"text": " "
},
{
"type": "text",
"text": "Announcments",
"style": {
"bold": true
}
}
]
}
]
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": " :door: New Doors - You should see our new doors installed. Stay tuned for a Q&A and some FAQ info on the new doors, processes and expectations.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":WX:Boost Days - Boost days have been extended until March 2025 due to the great feedback gathered. Yay!",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":celebrate:End of Year party - Don't forget to RSVP for the Denver party at The Lob on 22 Nov. A Sprinkle of magic and lots of fun to be had! ",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":turkey: Please emoji a Turkey on this post to let us know if you will be in office for breakfast on Nov 26th so we can determine if we will run service that day. Nov 28th and 29th the office will be closed for the Holiday.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":wave: Keep an eye our for visitors from the US Roadshow and US XPAc visit duriing the week of the 18th.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":calendar-date-14: Our next US Stand Up is Nov 14 at 2PM MDT. Add it to your calendar below and join us for a quick meeting with some fun updates. This is a monthly meeting and we would love to see you there!",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Add to Calendar"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Me",
"emoji": true
},
"value": "meet.google.com/awh-gacj-hfw",
"action_id": "meet.google.com/awh-gacj-hfw"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Breakfast & Lunch Schedule\n\n :calendar-date-5: Trez banderas\n\n:calendar-date-7: Costa Vida\n\n:calendar-date-12: That Personal Touch\n\n:calendar-date-14: Lazo Empanadas\n\n:calendar-date-19: Renegade Burrito\n\n:calendar-date-21: Paradise Biryani\n\n:calendar-date-26: TBD - Please emoji :turkey: if you will be here.\n\n:calendar-date-28: No Service - Holiday",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Boost Days Café - Tue and Thur\n\n On Boost Days enjoy your free cup of coffee on or beverage on Xero from Blue Sparrow on the 1st floor Lobby.Show your ID :badge: and don't forget to hit the 12% tip as this is included in our budget. ",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "WX offers comprehensive event planning services, including:\n\n:dot:Assistance with logistics and coordination\n\n:dot:Access to a network of vendors for catering, supply ordering, etc.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Note: Are you traveling to a Xero office? Please notify Wx ahead of your visit to ensure access. Even if you don’t need our assistance but are using the office space, kindly inform WX.\n\n:pushpin: Have something important to add to our calendar? Don’t hesitate to reach out if you have any questions or concerns. Get in touch with us at via the Help Centre or at #hello-px\n\nWishing everyone a successful month ahead!",
"emoji": true
}
}
]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scientific Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.calculator {
width: 300px;
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
}
.display {
width: 100%;
height: 50px;
margin-bottom: 10px;
font-size: 1.5rem;
text-align: right;
border: 1px solid #ddd;
border-radius: 5px;
padding: 5px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.button {
height: 50px;
background: #2196f3;
color: white;
font-size: 1.2rem;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
.button:hover {
background: #1976d2;
}
.button.clear {
background: #f44336;
}
.button.clear:hover {
background: #d32f2f;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" class="display" disabled>
<div class="buttons">
<button class="button" onclick="append('7')">7</button>
<button class="button" onclick="append('8')">8</button>
<button class="button" onclick="append('9')">9</button>
<button class="button" onclick="append('/')">/</button>
<button class="button" onclick="append('4')">4</button>
<button class="button" onclick="append('5')">5</button>
<button class="button" onclick="append('6')">6</button>
<button class="button" onclick="append('*')">*</button>
<button class="button" onclick="append('1')">1</button>
<button class="button" onclick="append('2')">2</button>
<button class="button" onclick="append('3')">3</button>
<button class="button" onclick="append('-')">-</button>
<button class="button" onclick="append('0')">0</button>
<button class="button" onclick="append('.')">.</button>
<button class="button" onclick="calculate()">=</button>
<button class="button" onclick="append('+')">+</button>
<button class="button clear" onclick="clearDisplay()">C</button>
<button class="button" onclick="append('%')">%</button>
</div>
</div>
<script>
const display = document.getElementById('display');
function append(value) {
display.value += value;
}
function calculate() {
try {
display.value = eval(display.value);
} catch (error) {
display.value = "Error";
}
}
function clearDisplay() {
display.value = '';
}
</script>
</body>
</html>
java
Copy code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
PrintWriter out = response.getWriter();
out.println("Hello from HttpServlet!");
}
}
Step 1: Install Apache Tomcat
Download and install Apache Tomcat.
Set up Tomcat by configuring environment variables (CATALINA_HOME and JAVA_HOME), if needed.
Step 2: Save and Structure Your Servlet
Save the servlet code in a file named HelloServlet.java.
Organize it within the WEB-INF/classes directory inside your web application folder. For example:
Copy code
your-webapp
├── WEB-INF
│ ├── classes
│ │ └── HelloServlet.java
│ └── web.xml
Step 3: Compile the Servlet
Open a terminal or command prompt, navigate to WEB-INF/classes, and compile:
bash
Copy code
javac -classpath <path-to-servlet-api.jar> HelloServlet.java
Replace <path-to-servlet-api.jar> with the path to servlet-api.jar in the lib folder of your Tomcat installation.
Step 4: Configure web.xml
In the WEB-INF folder, create or update web.xml with the servlet mapping:
xml
Copy code
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step 5: Deploy and Start Tomcat
Place the your-webapp folder in Tomcat’s webapps directory.
Start Tomcat by running startup.sh (Linux/Mac) or startup.bat (Windows) in the bin folder.
Step 6: Access the Servlet
Open a browser and navigate to: http://localhost:8080/your-webapp/hello
Expected Output
If everything is set up correctly, you should see:
plaintext
Copy code
Hello from HttpServlet!
vSTEP 1: Create an Empty Activity
STEP 2: Create a raw resource folder
Create a raw resource folder under the res folder and copy one of
the .mp3 file extension.
Right Click on "raw" folder ----> select "new" ---> click on "Android
Resource Directory" ----> Change resource type values to "raw" ---->
then finally click "OK".
Download required audio MP3 file (Size <500kb approximately) from
Internet , right click and Paste it in "raw" folder whatever newly created.
--------------------------------------------------------------------
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<TextView
android:id="@+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="MEDIA PLAYER"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/headingText"
android:layout_marginTop="16dp"
android:gravity="center_horizontal">
<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:backgroundTint="@color/colorPrimary"
android:text="STOP"
android:textColor="@android:color/white"
tools:ignore="ButtonStyle,TextContrastCheck" />
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:backgroundTint="@color/colorPrimary"
android:text="PLAY"
android:textColor="@android:color/white"
tools:ignore="ButtonStyle,TextContrastCheck" />
<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimary"
android:text="PAUSE"
android:textColor="@android:color/white"
tools:ignore="ButtonStyle,TextContrastCheck" />
</LinearLayout>
</RelativeLayout>
MainActivity.kt
// As per your application (or) file name package name will displayed
package com.example.mediaplayer
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// create an instance of mediplayer for audio playback
val mediaPlayer: MediaPlayer =
MediaPlayer.create(applicationContext, R.raw.music)
// register all the buttons using their appropriate IDs
val bPlay: Button = findViewById(R.id.playButton)
val bPause: Button = findViewById(R.id.pauseButton)
val bStop: Button = findViewById(R.id.stopButton)
// handle the start button to
// start the audio playback
bPlay.setOnClickListener {
// start method is used to start
// playing the audio file
mediaPlayer.start()
}
// handle the pause button to put the
// MediaPlayer instance at the Pause state
bPause.setOnClickListener {
// pause() method can be used to
// pause the mediaplyer instance
mediaPlayer.pause()
}
// handle the stop button to stop playing
// and prepare the mediaplayer instance
// for the next instance of play
bStop.setOnClickListener {
// stop() method is used to completely
// stop playing the mediaplayer instance
mediaPlayer.stop()
// after stopping the mediaplayer instance
// it is again need to be prepared
// for the next instance of playback
mediaPlayer.prepare()
ACTIVITY_MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACTIVITY LIFE CYCLE DEMO"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
MAINACTIVITY.kt
package com.example.myapp_activitylifecyclemethods
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Toast.makeText(applicationContext,"ONCREATE()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onStart() {
super.onStart()
Toast.makeText(applicationContext,"ONSTART()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onRestart() {
super.onRestart()
Toast.makeText(applicationContext,"ONRESTART()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onResume() {
super.onResume()
Toast.makeText(applicationContext,"ONRESUME()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onPause() {
super.onPause()
Toast.makeText(applicationContext,"ONPAUSE()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onStop() {
super.onStop()
Toast.makeText(applicationContext,"ONSTOP()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onDestroy() {
super.onDestroy()
Toast.makeText(applicationContext,"ONDESTROY()
CALLED",Toast.LENGTH_SHORT).show()
}
}
java
Copy code
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
public class MyServlet implements Servlet {
public void init(ServletConfig config) throws ServletException {}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Hello Servlet Lifecycle!");
}
public void destroy() {}
public ServletConfig getServletConfig() { return null; }
public String getServletInfo() { return null; }
}
Step 1: Install Apache Tomcat
Download and install Apache Tomcat.
Set up Tomcat by configuring the environment variables (CATALINA_HOME and JAVA_HOME), if necessary.
Step 2: Save Your Java Code
Save your servlet code in a file named MyServlet.java.
Ensure that this file is located in the WEB-INF/classes directory within your web application directory
structure. For example:
Copy code
your-webapp ├── WEB-INF │ ├── classes │ │ └── MyServlet.java │ └── web.xml
Step 3: Compile the Servlet
Open a terminal or command prompt and navigate to the WEB-INF/classes directory.
Compile the servlet:
bash
Copy code
javac -classpath <path-to-servlet-api.jar> MyServlet.java
Replace <path-to-servlet-api.jar> with the path to the servlet-api.jar file in your Tomcat installation, typically
located in the lib folder.
Step 4: Configure web.xml
In the WEB-INF folder, create or update the web.xml file with the following content:
xml
Copy code
<web-app> <servlet>
class>
<servlet-name>MyServlet</servlet-name>
</servlet> <servlet-mapping>
<servlet-class>MyServlet</servlet
<servlet-name>MyServlet</servlet-name>
pattern>/myservlet</url-pattern> </servlet-mapping> </web-app>
This configuration maps the servlet to the URL path /myservlet.
Step 5: Deploy and Run
<url
Copy your web application folder (your-webapp) into the webapps directory of your Tomcat installation.
Start Tomcat by running the startup.sh (Linux/Mac) or startup.bat (Windows) file located in the bin directory
of your Tomcat installation.
Open a web browser and navigate to http://localhost:8080/your-webapp/myservlet.
Expected Output
If the servlet is configured and deployed correctly, you should see:
plaintext
Copy code
Hello Servlet Lifecycle!
If there’s an error, the Tomcat logs (located in the logs directory of your Tomcat installation) will contain
information to help you debug.
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBCPreparedStatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user",
"password");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO books (title, author) VALUES (?, ?)");
pstmt.setString(1, "Java Programming");
pstmt.setString(2, "Author Name");
pstmt.executeUpdate();
System.out.println("Data inserted successfully");
} catch (Exception e) {
System.out.println(e);
}
}
}
Set Up Your Database:
Ensure you have a MySQL server running on localhost with a database named testdb.
Create a books table with at least a title column:
sql
Copy code
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL
);
Compile the java code in cmd and expected output
Data inserted successfully
[OR]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class App {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/testdb"; // Replace with your DB name
String user = "root"; // Replace with your DB username
String password = "Varun13@"; // Replace with your DB password
// SQL queries
String insertQuery = "INSERT INTO books (title, author) VALUES (?, ?)";
String updateQuery = "UPDATE books SET author = ? WHERE id = ?";
String deleteQuery = "DELETE FROM books WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to the database!");
// INSERT operation
try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) {
insertStmt.setString(1, "John Doe");
insertStmt.setString(2, "john.doe@example.com");
int rowsInserted = insertStmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
}
// UPDATE operation
try (PreparedStatement updateStmt = conn.prepareStatement(updateQuery)) {
updateStmt.setString(1, "john.newemail@example.com");
updateStmt.setInt(2, 1); // Assuming user with ID 1 exists
int rowsUpdated = updateStmt.executeUpdate();
System.out.println(rowsUpdated + " row(s) updated.");
}
// DELETE operation
try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery)) {
deleteStmt.setInt(1, 1); // Assuming user with ID 1 exists
int rowsDeleted = deleteStmt.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
public class DatabaseMetadata {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user",
"password");
DatabaseMetaData dbMeta = con.getMetaData();
System.out.println("Database Product Name: " + dbMeta.getDatabaseProductName());
} catch (Exception e) {
System.out.println(e);
}
}
}
Set Up Your Database:
Ensure you have a MySQL server running on localhost with a database named testdb.
Create a books table with at least a title column:
sql
Copy code
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL
);
Compile the java code in cmd and expected output
Database Product Name: MySQL
[OR]
import java.sql.*;
public class App {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";
Connection connection = null;
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection to the database
connection = DriverManager.getConnection(jdbcURL, username, password);
// Retrieve and print database metadata
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion());
System.out.println("Driver Name: " + metaData.getDriverName());
System.out.println("Driver Version: " + metaData.getDriverVersion());
} catch (Exception e) {
// Handle exceptions
e.printStackTrace();
} finally {
// Close the connection
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseConnection {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user",
"password");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO books (title) VALUES ('Sample Book')");
System.out.println("SQL Query Executed");
} catch (Exception e) {
System.out.println(e);
}
}
}
Set Up Your Database:
Ensure you have a MySQL server running on localhost with a database named testdb.
Create a books table with at least a title column:
sql
Copy code
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL
);
Compile the java code in cmd and expected output
SQL Query Executed
[OR]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class App {
public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "Varun13@";
// SQL query
String query = "SELECT * FROM books";
// Establish connection and execute query
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
System.out.println("Connected to the database!");
// Process the result set
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Connected to the database!
java
Copy code
import java.io.*;
import javax.xml.parsers.*;
public class DOMValidator {
public static void main(String[] args) {
try {
System.out.println("Enter the XML file name:");
File file = new File(new BufferedReader(new InputStreamReader(System.in)).readLine());
if (file.exists() && isWellFormed(file)) {
System.out.println(file.getName() + " is well-formed.");
} else {
System.out.println(file.exists() ? "Not well-formed." : "File not found.");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static boolean isWellFormed(File file) {
try {
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
return true;
} catch (Exception e) {
return false;
}
}
}
xml
Copy code
hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>Java Programming</title>
<author>John Doe</author>
</book>
<book>
<title>XML Development</title>
<author>Jane Smith</author>
</book>
</library>
output:XML is valid
1.// getter and setter properties
class CSE {
var name: String = " "
get() = field // getter
set(value) { // setter
field = value
}
}
fun main(args: Array<String>) {
val c = CSE()
c.name = "WELCOME TO CSE-B" // access setter
println(c.name) // access getter
}
Output:
WELCOME TO CSE-B
2.// object accessing
class CSE {
fun Mobile() = println("WELCOME TO MAD LAB")
}
fun main(args: Array<String>) {
val obj = CSE()
// calling Mobile() method using object obj
obj.Mobile()
}
Output:
WELCOME TO MAD LAB
3.// companion object
class CSE {
companion object Test { //companion object name Test
fun section_b() = println("WELCOME TO CSE-B MAD LAB")
}
}
fun main(args: Array<String>) {
CSE.section_b() // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB
4.// accessing variable and method using class name in companion object
class CSE
{
companion object Test
{ //companion object name Test
var v:Int=100
fun section_b() = println("WELCOME TO CSE-B MAD LAB")
}
}
fun main(args: Array<String>)
{
println(CSE.v) // accessing variable using class name
CSE.section_b() // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB
5.// creating the employee class
class employee {
// properties / member variables
var name: String = "XYZ"
var age: Int = 10
var gender: Char = 'M'
var salary: Double = 500.toDouble()
// member functions
fun display(){
println("WELCOME TO CSE-B")
}
}
fun main()
{
var obj=employee() //object creation for class
obj.display() // accessing member function using object name
// accessing properties using object name
println(obj.name)
println(obj.age)
println(obj.gender)
println(obj.salary)
}
Output:
WELCOME TO CSE-B
XYZ
10
M
500.0
6.//DICE ROLLER PROGRAM USING CLASSES
// Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
//IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint.
//IntRange is a suitable data type for representing the possible values a dice roll can produce.
class Dice {
var sides = 6
fun roll(): Int {
//random() function to generate random numbers.
//random() takes a series of numbers as an input and it returns a random Int as an output.
val randomNumber = (1..sides).random()
return randomNumber
}
}
fun main() {
val myFirstDice = Dice()
val diceRoll = myFirstDice.roll()
println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!")
myFirstDice.sides = 20
println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!")
}
Output:
Your 6 sided dice rolled 4!
Your 20 sided dice rolled 7!
7.// random() function
fun main() {
// random() generates a random number between 0 to 10
println((0..10).random())
}
Output:
7
8.//primary constructor
fun main(args: Array<String>)
{
val add = Add(5, 6)
println("The Sum of numbers 5 and 6 is: ${add.c}")
}
class Add constructor(a: Int,b:Int)
{
var c = a+b;
}
Output:
The Sum of numbers 5 and 6 is 11
9.//secondary constructor
fun main(args: Array<String>)
{
Add(5, 6)
}
//class with one secondary constructor
class Add
{
constructor(a: Int, b:Int)
{
var c = a + b
println("The sum of numbers 5 and 6 is: ${c}")
}
}
Output:
The Sum of numbers 5 and 6 is 11
10.//this keyword and Constructor Declaration of Class
//Kotlin program of creating multiple objects and accessing the property and member function of class:
class employee {
var name: String = ""
var age: Int = 0
var gender: Char = 'M'
var salary: Double = 0.toDouble()
fun insertValues(n: String, a: Int, g: Char, s: Double) {
name = n
age = a
gender = g
salary = s
println("Name of the employee: $name")
println("Age of the employee: $age")
println("Gender: $gender")
println("Salary of the employee: $salary")
}
fun insertName(n: String) {
this.name = n
}
}
fun main(args: Array<String>) {
// creating multiple objects
var obj = employee()
// object 2 of class employee
var obj2 = employee()
//accessing the member function
obj.insertValues("X1", 50, 'M', 500000.00)
// accessing the member function
obj2.insertName("X2")
// accessing the name property of class
println("Name of the new employee: ${obj2.name}")
}
Output:
Name of the employee: X1
Age of the employee: 50
Gender: M
Salary of the employee: 500000.0
Name of the new employee: X2
11.//INHERITENCE IN KOTLIN
//base class
open class baseClass{
val name = "CSE-B"
fun A(){
println("Base Class")
}
}
//derived class
class derivedClass: baseClass() {
fun B() {
println(name) //inherit name property
println("Derived class")
}
}
fun main(args: Array<String>) {
val obj = derivedClass()
obj.A() // inheriting the base class function
obj.B() // calling derived class function
}
Output:
Base Class
CSE-B
Derived class
12. //DWELLINGS PROGRAM
/**
* Program that implements classes for different kinds of dwellings.
* Shows how to:
* Create class hierarchy, variables and functions with inheritance,
* abstract class, overriding, and private vs. public variables.
*/
import kotlin.math.PI
import kotlin.math.sqrt
fun main() {
val squareCabin = SquareCabin(6, 50.0)
val roundHut = RoundHut(3, 10.0)
val roundTower = RoundTower(4, 15.5)
with(squareCabin) {
println("\nSquare Cabin\n============")
println("Capacity: ${capacity}")
println("Material: ${buildingMaterial}")
println("Floor area: ${floorArea()}")
}
with(roundHut) {
println("\nRound Hut\n=========")
println("Material: ${buildingMaterial}")
println("Capacity: ${capacity}")
println("Floor area: ${floorArea()}")
println("Has room? ${hasRoom()}")
getRoom()
println("Has room? ${hasRoom()}")
getRoom()
println("Carpet size: ${calculateMaxCarpetLength()}")
}
with(roundTower) {
println("\nRound Tower\n==========")
println("Material: ${buildingMaterial}")
println("Capacity: ${capacity}")
println("Floor area: ${floorArea()}")
println("Carpet Length: ${calculateMaxCarpetLength()}")
}
}
/**
* Defines properties common to all dwellings.
* All dwellings have floorspace,
* but its calculation is specific to the subclass.
* Checking and getting a room are implemented here
* because they are the same for all Dwelling subclasses.
*
* @param residents Current number of residents
*/
abstract class Dwelling(private var residents: Int) {
abstract val buildingMaterial: String
abstract val capacity: Int
/**
* Calculates the floor area of the dwelling.
* Implemented by subclasses where shape is determined.
*
* @return floor area
*/
abstract fun floorArea(): Double
/**
* Checks whether there is room for another resident.
*
* @return true if room available, false otherwise
*/
fun hasRoom(): Boolean {
return residents < capacity
}
/**
* Compares the capacity to the number of residents and
* if capacity is larger than number of residents,
* add resident by increasing the number of residents.
* Print the result.
*/
fun getRoom() {
if (capacity > residents) {
residents++
println("You got a room!")
} else {
println("Sorry, at capacity and no rooms left.")
}
}
}
/**
* A square cabin dwelling.
*
* @param residents Current number of residents
* @param length Length
*/
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
override val buildingMaterial = "Wood"
override val capacity = 6
/**
* Calculates floor area for a square dwelling.
*
* @return floor area
*/
override fun floorArea(): Double {
return length * length
}
}
/**
* Dwelling with a circular floorspace
*
* @param residents Current number of residents
* @param radius Radius
*/
open class RoundHut(
residents: Int, val radius: Double) : Dwelling(residents) {
override val buildingMaterial = "Straw"
override val capacity = 4
/**
* Calculates floor area for a round dwelling.
*
* @return floor area
*/
override fun floorArea(): Double {
return PI * radius * radius
}
/**
* Calculates the max length for a square carpet
* that fits the circular floor.
*
* @return length of square carpet
*/
fun calculateMaxCarpetLength(): Double {
return sqrt(2.0) * radius
}
}
/**
* Round tower with multiple stories.
*
* @param residents Current number of residents
* @param radius Radius
* @param floors Number of stories
*/
class RoundTower(
residents: Int,
radius: Double,
val floors: Int = 2) : RoundHut(residents, radius) {
override val buildingMaterial = "Stone"
// Capacity depends on the number of floors.
override val capacity = floors * 4
/**
* Calculates the total floor area for a tower dwelling
* with multiple stories.
*
* @return floor area
*/
override fun floorArea(): Double {
return super.floorArea() * floors
}
}
Output:
Square Cabin
============
Capacity: 6
Material: Wood
Floor area: 2500.0
Round Hut
=========
Material: Straw
Capacity: 4
Floor area: 314.1592653589793
Has room? true
You got a room!
Has room? false
Sorry, at capacity and no rooms left.
Carpet size: 14.142135623730951
Round Tower
==========
Material: Stone
Capacity: 8
Floor area: 1509.5352700498956
Carpet Length: 21.920310216782976
13.//repeat statement
fun main(args: Array<String>) {
repeat(4) {
println("WELCOME TO CSE-B!")
}
}
Output:
WELCOME TO CSE-B!
WELCOME TO CSE-B!
WELCOME TO CSE-B!
WELCOME TO CSE-B!
14. // INIT BLOCK
class InitOrderDemo(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints $name")
}
val secondProperty = "Second property:${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
fun main() {
InitOrderDemo("hello")
}
Output:
First property: hello
First initializer block that prints hello
Second property: 5
Second initializer block that prints 5
15.//RANGETO() function
fun main(args : Array<String>){
println("Integer range:")
// creating integer range
for(num in 1.rangeTo(5)){
println(num)
}
}
Output:
Integer range:
1
2
3
4
5
16. //downTo() function
fun main(args : Array<String>){
println("Integer range in descending order:")
// creating integer range
for(num in 5.downTo(1)){
println(num)
}
}
Output:
Integer range in descending order:
5
4
3
2
1
17. //step keyword
fun main(args: Array<String>) {
//for iterating over the range
var i = 2
// for loop with step keyword
for (i in 3..10 step 2)
print("$i ")
println()
// print first value of the range
println((11..20 step 2).first)
// print last value of the range
println((11..20 step 4).last)
// print the step used in the range
println((11..20 step 5).step)
}
Output:
3 5 7 9
11
19
5
18. //reversed function
fun main(args: Array<String>) {
var range = 2..8
for (x in range.reversed()){
print("$x ")
}
}
Output:
8 7 6 5 4 3 2
19. //In Operator Example Program in Kotlin
fun main(args: Array<String>) {
val collection = 10..20
val num2 = 5
println("in operator in if condition")
if (15 in collection) {
println("15 is in $collection")
}
println("\nin operator in for loop")
for(item in collection){
println("$item is in $collection")
}
println("\nin operator in when statement")
when{
19 in collection -> println("19 in collection is true")
}
}
Output:
in operator in if condition
15 is in 10..20
in operator in for loop
10 is in 10..20
11 is in 10..20
12 is in 10..20
13 is in 10..20
14 is in 10..20
15 is in 10..20
16 is in 10..20
17 is in 10..20
18 is in 10..20
19 is in 10..20
20 is in 10..20
in operator in when statement
19 in collection is true
1.//Standard Library Function
fun main(args: Array<String>)
{
// arrayOf()-- to create an array by passing the values of the elements to the function.
var sum = arrayOf(1,2,3,4,5,6,7,8,9,10).sum()
println("The sum of all the elements of an array is: $sum")
}
Output:
The sum of all the elements of an array is: 55
2.// Kotlin user-defined function student() having different types of parameters-
fun student(name: String , roll_no: Int , grade: Char)
{
println("Name of the student is : $name")
println("Roll no of the student is: $roll_no")
println("Grade of the student is: $grade")
}
fun main(args: Array<String>) {
var result = student("CSE-B",66,'A')
println("Details of Student: $result")
}
Output:
Name of the student is : CSE-B
Roll no of the student is: 66
Grade of the student is: A
[OR]
// Kotlin user-defined function student() having different types of parameters-
fun student(name: String , roll_no: Int , grade: Char) {
println("Name of the student is : $name")
println("Roll no of the student is: $roll_no")
println("Grade of the student is: $grade")
}
fun main(args: Array<String>) {
student("CSE-B",66,'A')
}
Output:
Name of the student is : CSE-B
Roll no of the student is: 66
Grade of the student is: A
3. // function with parameter & with return type
fun CSE_B(x: Int): Int
{
return (x + 5)
}
fun main()
{
var result = CSE_B(3)
println(result)
}
Output:
8
4.// function WITHOUT PARAMETERS & WITHOUT RETURN TYPE
fun CSE_B()
{
println("WELCOME TO MAD LAB")
}
fun main()
{
CSE_B()
}
Output:
WELCOME TO MAD LAB
5.// demonstrate how to pass a variable number of arguments to a function Using vararg
fun main (args: Array<String>)
{
CSE_B ( "abc", "def", "ghi", "123", "sun")
}
fun CSE_B (vararg a: String)
{
for (a_ in a)
{
println(a_)
}
}
Output:
abc
def
ghi
123
sun
6.// lambda function
fun main(args: Array<String>){
val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambdafunction
addNumber(5,10,myLambda)
}
//The variable mylambda in function definition is actually a lambdafunction.
fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){
//high level function lambda as parameter
val add = a + b
mylambda(add) // println(add)
}
Output:
15
7.// lambda function
// with type annotation in lambda expression
val sum1 = { a: Int, b: Int -> a + b }
// Kotlin program of using lambda expression-
// without type annotation in lambda expression
val sum2:(Int,Int)-> Int = { a , b -> a + b}
fun main(args: Array<String>)
{
val result1 = sum1(2,3)
val result2 = sum2(3,4)
println("The sum of two numbers is: $result1")
println("The sum of two numbers is: $result2")
// directly print the return value of lambda
// without storing in a variable.
println(sum1(5,7))
}
Output:
The sum of two numbers is: 5
The sum of two numbers is: 7
12
8.// anonymous function
// anonymous function with body as an expression
val anonymous1 = fun(x: Int, y: Int): Int = x + y
// anonymous function with body as a block
val anonymous2 = fun(a: Int, b: Int): Int
{
val mul = a * b
return mul
}
fun main(args: Array<String>)
{
//invoking functions
val sum = anonymous1(3,5)
val mul = anonymous2(3,5)
println("The sum of two numbers is: $sum")
println("The multiply of two numbers is: $mul")
}
Output:
The sum of two numbers is: 8
The multiply of two numbers is: 15
9.//Kotlin program of lambda expression which returns Unit-
var lambda = {println("WELCOME TO CSE-B MAD LAB")}
// lambda expression
// higher-order function
fun higherfunc( lmbd: () -> Unit )
{ // accepting lambda as parameter
lmbd() //invokes lambda expression
}
fun main(args: Array<String>)
{
//invoke higher-order function
higherfunc(lambda) // passing lambda as parameter
}
Output:
WELCOME TO CSE-B MAD LAB
10. //Kotlin program of lambda expression which returns Integer value –
var lambda = {a: Int , b: Int -> a + b } // lambda expression
// higher order function
fun higherfunc( lmbd: (Int, Int) -> Int)
{
// accepting lambda as parameter
var result = lmbd(2,4) // invokes the lambda expression by passing parameters
println("The sum of two numbers is: $result")
}
fun main(args: Array<String>)
{
higherfunc(lambda) //passing lambda as parameter
}
Output:
The sum of two numbers is: 6
11. //Take input from user using readline() method
fun main(args : Array<String>) {
println("Enter text: ")
var input = readLine()
print("You entered: $input")
}
Output:
Enter text: CSE-B
You entered: CSE-B
1.Sample Program
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main()
{
println("Hello, world!!!")
}
------------------------------------------------------------------------------------------------
2.// main() function with parameters
fun main(args : Array<String>) {
println("Hello World")
}
3.// val / var demonstration
fun main()
{
var name = "Kotlin" // String (text)
val birthyear = 2023 // Int (number)
println(name) // Print the value of name
println(birthyear) // Print the value of birthyear
}
OR
// val / var demonstration
fun main()
{
var name: String = "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}
OR
// val / var demonstration
fun main()
{
var name: String
name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}
OR
// val / var demonstration
fun main()
{
var name
name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}
// var demonstration
fun main()
{
var name= "CSE B"
name = "CVR" // can be reassigned
println(name)
}
// val demonstration
fun main()
{
val name= "CSE B"
name = "CVR" // cannot be reassigned
println(name)
}
4.// DATA TYPE demonstration
fun main()
{
val a: Int = 5 // Int
val b: Double = 5.99 // Double
val c: Char = 'v' // Char
val d: Boolean = true // Boolean
val e: String = "CSE B" // String
val f: Float = 100.00f // float
println("a value is:" +a)
println("b value is:" +b)
println("c value is:" +c)
println("d value is:" +d)
println("e value is:" +e)
println("f value is:" +f)
}
5.// escape sequences of character demonstration
fun main()
{
println('\n') //prints a newline character
println('\t') //prints a tab character
println('\b') //prints a backspace character
println('\r') //prints a form feed character
println('\'') //prints a single quote character
println('\"') //prints a double quote character
println('\$') //prints a dollar $ character
println('\\') //prints a back slash \ character
}
6.// ARRAY demonstration
fun main()
{
val n:IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Value at 3rd position : " + n[2])
}
7.// TYPE CONVERSION demonstration
fun main()
{
val x: Int = 100
val y: Long = x.toLong()
println(y)
}
8.// ARTHIMETIC OPERATOR demonstration
fun main()
{
var sum1 = 100 + 50 // 150 (100 + 50)
var sum2 = sum1 + 250 // 400 (150 + 250)
var sum3 = sum2 + sum2 // 800 (400 + 400)
println(sum3)
}
9.// ASSIGNMENT OPERATOR demonstration
fun main()
{
var sum1 = 100 // ASSIGN A VALUE
println(sum1)
}
10.// COMPARISION OPERATOR demonstration
fun main() {
var x = 5
var y = 3
println(x > y) // returns true because 5 is greater than 3
}
11.// logical OPERATOR demonstration
fun main() {
var x = 5
println(x > 3 && x < 10) // returns true because 5 is greater than 3 AND 5 is less than 10
}
12.// STRING demonstration
fun main() {
var a:String="CSE B"
println(a[2]) // DISPLAYS CHARACTER AT LOACTION OR INDEX 2
}
13.// IF ELSE demonstration
fun main() {
val x = 20
val y = 18
if (x > y) {
println( "x is greater than y" )
}
else {
println( "x is lesser than y" )
} }
14.// WHEN demonstration
fun main() {
val day = 4
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result) // DISPLAYS OUTPUT AS "Thursday"
}
15.// WHILE Loop demonstration
fun main() {
var i = 0
while (i < 5) {
println(i)
i++
}
}
16.// DO WHILE LOOP demonstration
fun main() {
var i=0
do {
println(i)
i++
}
while (i < 5)
}
17.// FOR LOOP demonstration
fun main() {
val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
println(x)
}
}
18.// BREAK demonstration
fun main() {
var i = 0
while (i < 10) {
println(i)
i++
if (i == 4) {
break
}
}
19.//CONTINUE demonstration
fun main() {
var i = 0
while (i < 10)
{
if (i == 4)
{
i++
continue
}
println(i)
i++
}
}
20.//RANGE demonstration
fun main() {
for (n in 5..15) {
println(n)
}
}
21.//ARRAY demonstration
fun main() {
val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size) // check array length or size
for (x in cse)
{
println(x)
}
println(cse[0]) // You can access an array element by referring to the index number, inside square brackets
if ("CSE B" in cse)
{
println("It exists!")
}
else
{
println("It does not exist.")
}
}
XML File (books.xml):
xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="books.xsd">
<book>
<title>Wings of Fire</title>
<author>A.P.J Abdul Kalam</author>
<isbn>81-7371-146-1</isbn>
<publisher>Arun Tiwar</publisher>
<edition>1st</edition>
<price>180</price>
</book>
<book>
<title>Introduction to xml</title>
<author>Jane doe</author>
<isbn>978-0451524935</isbn>
<publisher>Tech Books Publisher</publisher>
<edition>1st</edition>
<price>29.99</price>
</book>
</books>
XSD File (books.xsd):
xsd
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="author" type="xs:string" />
<xs:element name="isbn" type="xs:string" />
<xs:element name="publisher" type="xs:string" />
<xs:element name="edition" type="xs:string" />
<xs:element name="price" type="xs:decimal" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML File (books.xml):
xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "books.dtd">
<books>
<book>
<title>Wings of Fire</title>
<author>A.P.J Abdul Kalam</author>
<isbn>81-7371-146-1</isbn>
<publisher>Arun Tiwar</publisher>
<edition>1st</edition>
<price>180</price>
</book>
<book>
<title>Introduction to xml</title>
<author>Jane doe</author>
<isbn>978-0451524935</isbn>
<publisher>Tech Books Publisher</publisher>
<edition>1st</edition>
<price>29.99</price>
</book>
</books>
DTD File (books.dtd):
dtd
Copy code
<!ELEMENT books (book+)>
<!ELEMENT book (title, author, isbn, publisher, edition, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
1.Develop an Android Application to display message using Toast Class.
Activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- android:inputType="textPersonName|textPassword" It will take text as password with asterisk symbol and combination of characters and numbers -->
<EditText
android:id="@+id/etView"
android:layout_width="380dp"
android:layout_height="62dp"
android:layout_marginTop="84dp"
android:layout_marginBottom="147dp"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName|textPassword"
android:textColor="#9C27B0"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/btn1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.483"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="400dp"
android:text="Click Here"
android:gravity="center_horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.435"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etView"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="@+id/txtView"
android:layout_width="361dp"
android:layout_height="70dp"
android:text="Text View"
android:textColor="#E91E63"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn1" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.example.myapp_lakshmi
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
//Declaration of Widgets
lateinit var editText:EditText
lateinit var btn:Button
lateinit var textView:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//findViewById() method is used to find an existing view in your XML layout by its android:id attribute.
editText=findViewById(R.id.etView)
btn=findViewById(R.id.btn1)
textView=findViewById(R.id.txtView)
btn.setOnClickListener(){
// A toast provides simple feedback about an operation in a small popup.
Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()
//Reading/Copying the text from edit text and writing/displaying/Pasting into the textview
textView.text=editText.text.toString()
}
}
}
Output:
2. Develop an Android Application showing clipboard by performing Copy and Paste Operations.
Activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- android:inputType="textPersonName|textPassword" It will take text as password with asterisk symbol and combination of characters and numbers -->
<EditText
android:id="@+id/etView"
android:layout_width="380dp"
android:layout_height="62dp"
android:layout_marginTop="84dp"
android:layout_marginBottom="147dp"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName|textPassword"
android:textColor="#9C27B0"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/btn1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.483"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="400dp"
android:text="Click Here"
android:gravity="center_horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.435"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etView"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="@+id/txtView"
android:layout_width="361dp"
android:layout_height="70dp"
android:text="Text View"
android:textColor="#E91E63"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn1" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.example.myapp_lakshmi
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
//Declaration of Widgets
lateinit var editText:EditText
lateinit var btn:Button
lateinit var textView:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//findViewById() method is used to find an existing view in your XML layout by its android:id attribute.
editText=findViewById(R.id.etView)
btn=findViewById(R.id.btn1)
textView=findViewById(R.id.txtView)
btn.setOnClickListener(){
// A toast provides simple feedback about an operation in a small popup.
Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()
//Reading/Copying the text from edit text and writing/displaying/Pasting into the textview
textView.text=editText.text.toString()
}
}
}
Outpu
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Callbacks, Promises, Async/Await</title>
</head>
<body>
<h1>JavaScript Callbacks, Promises, and Async/Await Demo</h1>
<script>
// Callback Example
function doSomething(callback) {
setTimeout(() => {
callback("Callback done!");
}, 1000);
}
doSomething(console.log);
// Promise Example
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise resolved!"), 1000);
});
promise.then(console.log);
// Async/Await Example
async function asyncFunction() {
let result = await promise;
console.log(result);
}
asyncFunction();
</script>
</body>
</html>
ACTIVITY_MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="20dp">
<EditText
android:id="@+id/eTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/btn_click"
android:hint="Type Here"
android:layout_margin="20dp"
android:textSize="20sp"
android:textColor="@color/purple_500"
/>
<Button
android:id="@+id/btn_click"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Here"
android:textSize="20sp"
android:textColor="#fff"
android:layout_margin="20dp"
android:background="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="@+id/tvShow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
app:layout_constraintTop_toBottomOf="@+id/btn_click"
android:textSize="20sp"
android:textStyle="bold"
android:text="Show"
android:textColor="#FF5722"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MAINACTIVITY.kt
package com.example.my_viewbinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.example.my_viewbinding.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_main)
var binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// var btn1 : Button = findViewById(R.id.btn_click)
// btn1.setOnClickListener(){
//var etxt1 : EditText = findViewById(R.id.eTxt)
//var tv1: TextView = findViewById(R.id.tvShow)
// var msg: String= etxt1.text.toString()
//tv1.text=msg
//}
binding.btnClick.setOnClickListener(){
binding.tvShow.setText(binding.eTxt.text)
}
}
}
NOTE:
build.gradle:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.my_viewbinding'
compileSdk 33
defaultConfig {
applicationId "com.example.my_viewbinding"
minSdk 24
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
viewBinding{
enabled true
}
[OR]
buildFeatures {
viewBinding = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles
getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
OUTPUT:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Web Design</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
header {
background-color: #3498db;
color: white;
padding: 20px;
text-align: center;
}
.container {
padding: 20px;
}
.content {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.content div {
background-color: #2980b9;
color: white;
text-align: center;
padding: 20px;
border-radius: 8px;
}
@media (max-width: 768px) {
.content {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 480px) {
.content {
grid-template-columns: 1fr;
}
header {
padding: 15px;
}
.content div {
font-size: 14px;
}
}
</style>
</head>
<body>
<header>
<h1>Responsive Web Design</h1>
</header>
<div class="container">
<div class="content">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
</div>
</body>
</html>
popUpDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Pop-Up Boxes</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 15px;
font-size: 16px;
margin: 10px;
}
</style>
</head>
<body>
<h1>JavaScript Pop-Up Box Demonstration</h1>
<button onclick="showAlert()">Show Alert</button>
<button onclick="showConfirm()">Show Confirm</button>
<button onclick="showPrompt()">Show Prompt</button>
<script>
function showAlert() {
alert("This is an alert box!");
}
function showConfirm() {
const result = confirm("Do you want to proceed?");
if (result) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
}
function showPrompt() {
const name = prompt("Please enter your name:");
if (name) {
alert("Hello, " + name + "!");
} else {
alert("No name entered.");
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Flexbox with Animations</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background: linear-gradient(to right, #ff7e5f, #feb47b);
color: #333;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
gap: 20px;
padding: 20px;
max-width: 900px;
background-color: rgba(255, 255, 255, 0.2);
border-radius: 15px;
box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
animation: fadeIn 1.5s ease-in-out;
}
.card {
background: #fff;
border-radius: 10px;
padding: 20px;
text-align: center;
flex: 1 1 200px;
max-width: 300px;
min-width: 200px;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: scale(1.1);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
}
.card h3 {
font-size: 1.5rem;
margin-bottom: 10px;
}
.card p {
font-size: 1rem;
color: #666;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(50px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
</head>
<body>
<div class="container">
<div class="card">
<h3>Card 1</h3>
<p>Some interesting text goes here.</p>
</div>
<div class="card">
<h3>Card 2</h3>
<p>More details about something awesome.</p>
</div>
<div class="card">
<h3>Card 3</h3>
<p>Another piece of useful information.</p>
</div>
<div class="card">
<h3>Card 4</h3>
<p>Additional content for your interest.</p>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic CSS Grid with Animation</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
width: 80%;
max-width: 800px;
}
.grid-item {
background-color: #3498db;
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 150px;
font-size: 20px;
font-weight: bold;
border-radius: 8px;
transition: transform 0.3s ease, background-color 0.3s ease;
}
.grid-item:hover {
transform: scale(1.1);
background-color: #2980b9;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
<div class="grid-item">Item 5</div>
<div class="grid-item">Item 6</div>
</div>
</body>
</html>
%env PROJ_DATA=/network/rit/lab/snowclus/miniforge3/envs/jan24_env/share/proj
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Discord Webhook Messenger</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
font-family: Arial, sans-serif;
background-color: #2c2f33;
color: #ffffff;
}
.container {
width: 350px;
padding: 20px;
background-color: #23272a;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
h2 {
text-align: center;
margin-bottom: 15px;
color: #7289da;
}
.input-field, textarea {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #40444b;
border-radius: 5px;
background-color: #2c2f33;
color: #ffffff;
font-size: 14px;
resize: none;
}
.send-button {
width: 100%;
padding: 10px;
background-color: #7289da;
color: #ffffff;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
font-weight: bold;
text-transform: uppercase;
transition: background-color 0.3s;
}
#charCount {
font-size: 12px;
color: #b9bbbe;
margin-bottom: 10px;
text-align: right;
}
#statusMessage {
font-size: 14px;
color: #43b581;
margin-top: 10px;
text-align: center;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.emoji-picker {
cursor: pointer;
font-size: 20px;
margin-left: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>Send a Message To Me On Discord</h2>
<input type="text" id="username" class="input-field" placeholder="Enter your name..." required>
<textarea id="message" placeholder="Enter your message here..." oninput="updateCharacterCount()" required></textarea>
<p id="charCount">200 characters remaining</p>
<span class="emoji-picker" onclick="addEmoji('😊')">😊</span>
<span class="emoji-picker" onclick="addEmoji('🎉')">🎉</span>
<span class="emoji-picker" onclick="addEmoji('❤️')">❤️</span>
<span class="emoji-picker" onclick="addEmoji('😂')">😂</span>
<span class="emoji-picker" onclick="addEmoji('😢')">😢</span>
<span class="emoji-picker" onclick="addEmoji('👍')">👍</span>
<span class="emoji-picker" onclick="addEmoji('👀')">👀</span>
<span class="emoji-picker" onclick="addEmoji('🔥')">🔥</span>
<span class="emoji-picker" onclick="addEmoji('✨')">✨</span>
<span class="emoji-picker" onclick="addEmoji('🙌')">🙌</span>
<button class="send-button" id="sendButton" onclick="sendMessage()">Send</button>
<p id="statusMessage"></p>
</div>
<audio id="confirmationSound" src="https://www.soundjay.com/button/beep-07.wav"></audio>
<script>
const MAX_CHAR = 200;
const RATE_LIMIT_MS = 3000; // 3 seconds
let lastSentTime = 0;
function updateCharacterCount() {
const message = document.getElementById("message").value;
const charCount = document.getElementById("charCount");
const remaining = MAX_CHAR - message.length;
charCount.textContent = `${remaining} characters remaining`;
}
function addEmoji(emoji) {
const messageInput = document.getElementById("message");
messageInput.value += emoji;
updateCharacterCount();
}
function playConfirmationSound() {
document.getElementById("confirmationSound").play();
}
function showStatusMessage(text, isError = false) {
const statusMessage = document.getElementById("statusMessage");
statusMessage.textContent = text;
statusMessage.style.opacity = 1;
statusMessage.style.color = isError ? "#f04747" : "#43b581";
setTimeout(() => {
statusMessage.style.opacity = 0;
}, 3000);
}
function sendMessage() {
const now = new Date().getTime();
if (now - lastSentTime < RATE_LIMIT_MS) {
showStatusMessage("Please wait before sending another message.", true);
return;
}
lastSentTime = now;
const username = document.getElementById("username").value.trim();
const message = document.getElementById("message").value.trim();
const webhookUrl = "https://discordapp.com/api/webhooks/1301556804056256613/Ol0hP3NfPrSKC6TUEXRw9gof3HPLecSphgUdrTYDGDusTP6nVtuC03Mo69wyLFA_NswS";
if (!username || !message) {
showStatusMessage("Please fill out all fields.", true);
return;
}
if (message.length > MAX_CHAR) {
showStatusMessage("Message exceeds character limit.", true);
return;
}
// Format message using Markdown without HTML
const content = `**${username}**: ${message}`;
fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content })
})
.then(response => {
if (response.ok) {
showStatusMessage("Message sent successfully!");
playConfirmationSound();
document.getElementById("message").value = "";
updateCharacterCount();
} else {
showStatusMessage("Failed to send message.", true);
}
})
.catch(error => {
console.error("Error:", error);
showStatusMessage("An error occurred.", true);
});
}
</script>
</body>
</html>
getUrl("https://httpstat.us/200?sleep=7000");
import React from 'react';
/**
* Toggles the presence of a number in the selectedNumbers array state.
*
* @param number - The number to toggle in the selection.
* @param setSelectedNumbers - The state setter function from useState.
*/
const toggleNumber = (
number: number,
setSelectedNumbers: React.Dispatch<React.SetStateAction<number[]>>
): void => {
setSelectedNumbers((prevSelectedNumbers) => {
if (prevSelectedNumbers.includes(number)) {
// Number is already selected; remove it from the array
return prevSelectedNumbers.filter((n) => n !== number);
} else {
// Number is not selected; add it to the array
return [...prevSelectedNumbers, number];
}
});
};
// Initialize State in Your Component
const [selectedNumbers, setSelectedNumbers] = useState<number[]>([]);
// Use the toggleNumber Function
// Example usage within a component event handler
const handleNumberClick = (number: number): void => {
toggleNumber(number, setSelectedNumbers);
};
// Implement in JSX
<button onClick={() => handleNumberClick(5)}>
{selectedNumbers.includes(5) ? 'Deselect 5' : 'Select 5'}
</button>
ctivity_main.xml:
?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layoutManager="LinearLayoutManager" />
</FrameLayout>
MainActivity.kt
package com.polymath.affirmations
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.polymath.affirmations.adapter.ItemAdapter
import com.polymath.affirmations.data.Datasource
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myDataSet = Datasource().loadAffirmations()
// getting the recycler view by its id
val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
// this will pass the arraylist to our adapter
recyclerView.adapter = ItemAdapter(this, myDataSet)
recyclerView.setHasFixedSize(true)
}
}
Steps to create a new layout resource file:
Right click on “layout” -- click on “new” - select “Layout Resource File” and give file name as list_item.xml. Finally, a new xml file is created in layout folder.
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/item_image"
android:layout_width="match_parent"
android:layout_height="194dp"
android:importantForAccessibility="no"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:textAppearance="?attr/textAppearanceHeadline6" />
</LinearLayout>
Steps to create a class file in studio:
Right click on “res” select “new” select “kotlin class/file”
Affirmations.kt
package com.polymath.affirmations.model
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
data class Affirmation(
@StringRes val stringResourceId: Int,
@DrawableRes val imageResourceId: Int) {
}
DataSource class file
package com.polymath.affirmations.data
import com.polymath.affirmations.R
import com.polymath.affirmations.model.Affirmation
class Datasource {
fun loadAffirmations(): List<Affirmation>
{
return listOf<Affirmation>(
Affirmation(R.string.affirmation1, R.drawable.image1),
Affirmation(R.string.affirmation2, R.drawable.image2),
Affirmation(R.string.affirmation3, R.drawable.image3),
Affirmation(R.string.affirmation4, R.drawable.image4),
Affirmation(R.string.affirmation5, R.drawable.image5),
Affirmation(R.string.affirmation6, R.drawable.image6),
Affirmation(R.string.affirmation7, R.drawable.image7),
Affirmation(R.string.affirmation8, R.drawable.image8),
Affirmation(R.string.affirmation9, R.drawable.image9),
Affirmation(R.string.affirmation10, R.drawable.image10),
)
}
}
ItemAdapter.kt
package com.polymath.affirmations.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.polymath.affirmations.R
import com.polymath.affirmations.model.Affirmation
class ItemAdapter(
private val context: Context,
private val dataset: List<Affirmation>
) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
class ItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
val textView : TextView = view.findViewById(R.id.item_title)
val imageView: ImageView = view.findViewById(R.id.item_image)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
//Create a new view
val adapterLayout = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
return ItemViewHolder(adapterLayout)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = dataset[position]
holder.textView.text = context.resources.getString(item.stringResourceId)
holder.imageView.setImageResource(item.imageResourceId)
}
override fun getItemCount() = dataset.size
}
star
photo_camera
Fri Nov 01 2024 10:28:22 GMT+0000 (Coordinated Universal Time) https://techcommunity.microsoft.com/t5/discussions/add-import-export-flags-option/m-p/1118546#M22328
star
photo_camera
Fri Nov 01 2024 05:15:01 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/docs/extensions/reference/manifest/sandbox?thumb
star
Thu Oct 31 2024 13:44:29 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/67238740-c09c-800e-bfbc-dc08c451dc4e
star
Thu Oct 31 2024 13:11:53 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/67237e2a-a1f0-800e-881c-d0546056cc1d
star
Thu Oct 31 2024 13:11:34 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/67237a03-5898-800e-8485-32c64ffe5d44


