Skip to content

Instantly share code, notes, and snippets.

@renfeisong
Last active June 16, 2024 18:42
Show Gist options
  • Save renfeisong/3403c5f4c2f08155ab4a010a4429201e to your computer and use it in GitHub Desktop.
Save renfeisong/3403c5f4c2f08155ab4a010a4429201e to your computer and use it in GitHub Desktop.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// Constants
#define PI 3.14159
#define E 2.71828
// Function prototypes
void printWelcomeMessage();
void inputStudentDetails(int *id, char *name, float *grade);
void displayStudentDetails(int id, const char *name, float grade);
float calculateAverageGrade(float grades[], int count);
void printGoodbyeMessage();
// Main function
int main() {
printWelcomeMessage();
int studentCount;
printf("Enter the number of students (max 10): ");
scanf("%d", &studentCount);
if (studentCount > 10) {
printf("Exceeded maximum number of students. Setting to 10.\n");
studentCount = 10;
}
int ids[10];
char names[10][50];
float grades[10];
for (int i = 0; i < studentCount; i++) {
printf("\nEntering details for student %d\n", i + 1);
inputStudentDetails(&ids[i], names[i], &grades[i]);
}
printf("\nStudent Details:\n");
for (int i = 0; i < studentCount; i++) {
displayStudentDetails(ids[i], names[i], grades[i]);
}
float averageGrade = calculateAverageGrade(grades, studentCount);
printf("\nAverage Grade: %.2f\n", averageGrade);
printGoodbyeMessage();
return 0;
}
// Function implementations
void printWelcomeMessage() {
printf("Welcome to the Student Management System!\n");
}
void inputStudentDetails(int *id, char *name, float *grade) {
printf("Enter student ID: ");
scanf("%d", id);
printf("Enter student name: ");
scanf("%s", name);
printf("Enter student grade: ");
scanf("%f", grade);
}
void displayStudentDetails(int id, const char *name, float grade) {
printf("ID: %d, Name: %s, Grade: %.2f\n", id, name, grade);
}
float calculateAverageGrade(float grades[], int count) {
float sum = 0.0;
for (int i = 0; i < count; i++) {
sum += grades[i];
}
return sum / count;
}
void printGoodbyeMessage() {
printf("Thank you for using the Student Management System. Goodbye!\n");
}
// Sample C# file for syntax highlighting
using System;
using System.IO;
using System.Collections.Generic;
namespace StudentManagementSystem
{
class Program
{
// Constants
const double PI = 3.14159;
const double E = 2.71828;
static void Main(string[] args)
{
PrintWelcomeMessage();
var students = new List<Student>();
int studentCount = 3;
for (int i = 1; i <= studentCount; i++)
{
students.Add(new Student(i, $"Student {i}", new Random().Next(60, 100)));
}
Console.WriteLine("\nStudent Details:");
students.ForEach(student => student.DisplayDetails());
int number = 5;
Console.WriteLine($"Factorial of {number}: {CalculateFactorial(number)}");
Console.WriteLine($"Current time: {DateTime.Now}");
// Array operations
var squares = new int[10];
for (int i = 0; i < squares.Length; i++)
{
squares[i] = i * i;
}
Console.WriteLine("Squares: " + string.Join(", ", squares));
// Lambda function
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine($"Sum of 3 and 5: {add(3, 5)}");
// Using math functions
Console.WriteLine($"Cosine of 0: {Math.Cos(0)}");
Console.WriteLine($"Natural log of E: {Math.Log(E)}");
// Escaped characters
Console.WriteLine("This is a string with a newline character.\nThis is on a new line.");
Console.WriteLine("This is a string with a tab character.\tThis is after the tab.");
PrintGoodbyeMessage();
}
static void PrintWelcomeMessage()
{
Console.WriteLine("Welcome to the Student Management System!");
}
static void PrintGoodbyeMessage()
{
Console.WriteLine("Thank you for using the Student Management System. Goodbye!");
}
static int CalculateFactorial(int n)
{
if (n == 0)
return 1;
return n * CalculateFactorial(n - 1);
}
// Class definition
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Grade { get; set; }
public Student(int id, string name, int grade)
{
Id = id;
Name = name;
Grade = grade;
}
public void DisplayDetails()
{
Console.WriteLine($"ID: {Id}, Name: {Name}, Grade: {Grade}");
}
}
}
}
/* Global styles */
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
color: #333;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: normal;
color: #444;
}
p {
line-height: 1.6;
margin: 1em 0;
}
/* Navigation styles */
nav {
background-color: #333;
color: #fff;
padding: 1em;
}
nav a {
color: #fff;
text-decoration: none;
padding: 0.5em;
}
nav a:hover {
background-color: #575757;
border-radius: 5px;
}
/* Container styles */
.container {
width: 80%;
margin: 0 auto;
padding: 2em;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
/* Grid system */
.row {
display: flex;
flex-wrap: wrap;
margin: -1em;
}
.col {
flex: 1;
padding: 1em;
box-sizing: border-box;
}
.col-1 {
flex: 0 0 8.33%;
}
.col-2 {
flex: 0 0 16.66%;
}
.col-3 {
flex: 0 0 25%;
}
.col-4 {
flex: 0 0 33.33%;
}
.col-5 {
flex: 0 0 41.66%;
}
.col-6 {
flex: 0 0 50%;
}
.col-7 {
flex: 0 0 58.33%;
}
.col-8 {
flex: 0 0 66.66%;
}
.col-9 {
flex: 0 0 75%;
}
.col-10 {
flex: 0 0 83.33%;
}
.col-11 {
flex: 0 0 91.66%;
}
.col-12 {
flex: 0 0 100%;
}
/* Button styles */
button {
background-color: #007bff;
color: #fff;
border: none;
padding: 0.5em 1em;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
/* Form styles */
input[type="text"],
input[type="email"],
textarea {
width: 100%;
padding: 0.5em;
margin: 0.5em 0;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type="submit"] {
background-color: #28a745;
color: #fff;
border: none;
padding: 0.5em 1em;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
input[type="submit"]:hover {
background-color: #218838;
}
/* Media queries */
@media (max-width: 768px) {
.container {
width: 100%;
padding: 1em;
}
.col {
flex: 0 0 100%;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample HTML File</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
color: #333;
}
header, footer {
background-color: #333;
color: #fff;
padding: 10px;
}
nav a {
color: #fff;
margin: 0 10px;
text-decoration: none;
}
nav a:hover {
text-decoration: underline;
}
.container {
padding: 20px;
}
</style>
</head>
<body>
<header>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
</header>
<div class="container">
<h1>Welcome to Our Website</h1>
<p>This is a sample paragraph to demonstrate HTML syntax highlighting.</p>
<h2>About Us</h2>
<p>We are a team of web developers creating awesome websites.</p>
<h2>Services</h2>
<ul>
<li>Web Development</li>
<li>Mobile App Development</li>
<li>UI/UX Design</li>
</ul>
<h2>Contact</h2>
<form action="/submit-form" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="4" required></textarea><br><br>
<input type="submit" value="Submit">
</form>
</div>
<footer>
<p>&copy; 2024 Web Solutions. All rights reserved.</p>
</footer>
</body>
</html>
// Sample Java file for syntax highlighting
import java.util.Date;
import java.util.Arrays;
public class Sample {
// Constants
public static final double PI = 3.14159;
public static final double E = 2.71828;
// Main method
public static void main(String[] args) {
printWelcomeMessage();
Circle circle = new Circle(5);
System.out.println(circle);
System.out.println("Area: " + circle.area());
System.out.println("Perimeter: " + circle.perimeter());
int number = 5;
System.out.println("Factorial of " + number + ": " + calculateFactorial(number));
printGoodbyeMessage();
// Array operations
int[] squares = new int[10];
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i;
}
System.out.println("Squares: " + Arrays.toString(squares));
// Lambda function (using an anonymous class for demonstration)
MathOperation add = new MathOperation() {
@Override
public int operate(int a, int b) {
return a + b;
}
};
System.out.println("Sum of 3 and 5: " + add.operate(3, 5));
// Using Math class
System.out.println("Cosine of 0: " + Math.cos(0));
System.out.println("Natural log of E: " + Math.log(E));
// Escaped characters
System.out.println("This is a string with a newline character.\nThis is on a new line.");
System.out.println("This is a string with a tab character.\tThis is after the tab.");
}
// Function to print a welcome message
public static void printWelcomeMessage() {
System.out.println("Welcome to the Student Management System!");
}
// Function to print a goodbye message
public static void printGoodbyeMessage() {
System.out.println("Thank you for using the Student Management System. Goodbye!");
}
// Function to calculate factorial
public static int calculateFactorial(int n) {
if (n == 0) {
return 1;
}
return n * calculateFactorial(n - 1);
}
// Interface for demonstrating lambda functions
interface MathOperation {
int operate(int a, int b);
}
}
// Abstract class definition
abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
public abstract double area();
public abstract double perimeter();
@Override
public String toString() {
return "Shape with color: " + color;
}
}
// Subclass definition
class Circle extends Shape {
private double radius;
public Circle(double radius) {
super("Blue");
this.radius = radius;
}
@Override
public double area() {
return Sample.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Sample.PI * radius;
}
@Override
public String toString() {
return "Circle with radius: " + radius + " and color: " + color;
}
}
// Constants
const PI = 3.14159;
const E = 2.71828;
// Function to calculate area of a circle
function calculateArea(radius) {
return PI * radius * radius;
}
// Function to calculate perimeter of a circle
function calculatePerimeter(radius) {
return 2 * PI * radius;
}
// Class representing a Shape
class Shape {
constructor(color = "Red") {
this.color = color;
}
area() {
throw new Error("Method 'area()' must be implemented.");
}
perimeter() {
throw new Error("Method 'perimeter()' must be implemented.");
}
}
// Class representing a Circle
class Circle extends Shape {
constructor(radius, color = "Blue") {
super(color);
this.radius = radius;
}
area() {
return calculateArea(this.radius);
}
perimeter() {
return calculatePerimeter(this.radius);
}
toString() {
return `Circle with radius ${this.radius} and color ${this.color}`;
}
}
// Function to calculate factorial
function calculateFactorial(n) {
if (n === 0) {
return false;
}
return n * calculateFactorial(n - 1);
}
// Display current time
function displayCurrentTime() {
const now = new Date();
console.log(`Current time: ${now.toISOString()}`);
}
// Main function
function main() {
const circle = new Circle(5);
console.log(circle.toString());
console.log(`Area: ${circle.area()}`);
console.log(`Perimeter: ${circle.perimeter()}`);
const number = 5;
console.log(`Factorial of ${number}: ${calculateFactorial(number)}`);
displayCurrentTime();
// Array operations
const squares = Array.from({ length: 10 }, (v, k) => k * k);
console.log(`Squares: ${squares}`);
// Lambda function
const add = (x, y) => x + y;
console.log(`Sum of 3 and 5: ${add(3, 5)}`);
// Using Math object
console.log(`Cosine of 0: ${Math.cos(0)}`);
console.log(`Natural log of E: ${Math.log(E)}`);
// Escaped characters
console.log("This is a string with a newline character.\nThis is on a new line.");
console.log("This is a string with a tab character.\tThis is after the tab.");
}
// Run main function
main();
#import <Foundation/Foundation.h>
// Book class implementation
@implementation Book
- (instancetype)initWithTitle:(NSString *)title author:(NSString *)author {
self = [super init];
if (self) {
_title = title;
_author = author;
}
return self;
}
- (NSString *)describe {
return [NSString stringWithFormat:@"%@ by %@", self.title, self.author];
}
@end
// Library class interface
@interface Library : NSObject
@property (nonatomic, strong) NSMutableArray<Book *> *books;
- (void)addBook:(Book *)book;
- (Book *)findBookByTitle:(NSString *)title;
- (NSString *)describeAllBooks;
@end
// Library class implementation
@implementation Library
- (instancetype)init {
self = [super init];
if (self) {
_books = [NSMutableArray array];
}
return self;
}
- (void)addBook:(Book *)book {
[self.books addObject:book];
}
- (Book *)findBookByTitle:(NSString *)title {
for (Book *book in self.books) {
if ([book.title isEqualToString:title]) {
return book;
}
}
return nil;
}
- (NSString *)describeAllBooks {
NSMutableArray *descriptions = [NSMutableArray array];
for (Book *book in self.books) {
[descriptions addObject:[book describe]];
}
return [descriptions componentsJoinedByString:@", "];
}
@end
// Fetch data function
void fetchData(FetchCompletionHandler completion) {
NSArray *data = @[
[[Book alloc] initWithTitle:@"1984" author:@"George Orwell"],
[[Book alloc] initWithTitle:@"To Kill a Mockingbird" author:@"Harper Lee"]
];
BOOL isSuccess = YES;
if (isSuccess) {
completion(ResultTypeSuccess, data, nil);
} else {
NSError *error = [NSError errorWithDomain:@"LibraryError" code:1 userInfo:nil];
completion(ResultTypeFailure, nil, error);
}
}
// Main execution
int main(int argc, const char * argv[]) {
@autoreleasepool {
Library *library = [[Library alloc] init];
fetchData(^(ResultType resultType, NSArray * _Nullable data, NSError * _Nullable error) {
if (resultType == ResultTypeSuccess) {
for (Book *book in data) {
[library addBook:book];
}
NSLog(@"Books loaded: %@", [library describeAllBooks]);
} else {
NSLog(@"Failed to load books: %@", error.localizedDescription);
}
});
}
return 0;
}

Sample Markdown File

Welcome to this Markdown sample file. This file includes various Markdown syntaxes for testing purposes.

Headings

Heading Level 3

Heading Level 4

Heading Level 5
Heading Level 6

Paragraphs

This is a simple paragraph. Here is another paragraph with italic text, bold text, and bold italic text.

Lists

Unordered List

  • Item 1
  • Item 2
    • Subitem 1
    • Subitem 2
  • Item 3

Ordered List

  1. First item
  2. Second item
    1. Subitem 1
    2. Subitem 2
  3. Third item

Links

Here is a link to Google.

Images

Sample Image

Code

Inline code: console.log("Hello, World!");

Code Block

def greet(name):
    print(f"Hello, {name}!")

Blockquote

This is a blockquote. This is the second line of the blockquote.

Tables

Header Header Header Header
Data Data Data Data
Data Data Data Data
Data Data Data Data
<?php
// Constants
define("PI", 3.14159);
define("E", 2.71828);
// Function to print a welcome message
function printWelcomeMessage() {
echo "Welcome to the Student Management System!\n";
}
// Class definition
class Student {
public $id;
public $name;
public $grade;
function __construct($id, $name, $grade) {
$this->id = $id;
$this->name = $name;
$this->grade = $grade;
}
function displayDetails() {
echo "ID: $this->id, Name: $this->name, Grade: $this->grade\n";
}
}
// Function to calculate factorial
function calculateFactorial($n) {
if ($n == 0) {
return 1;
}
return $n * calculateFactorial($n - 1);
}
// Main script execution
printWelcomeMessage();
$students = [];
$studentCount = 3;
for ($i = 1; $i <= $studentCount; $i++) {
$students[] = new Student($i, "Student $i", rand(60, 100));
}
echo "\nStudent Details:\n";
foreach ($students as $student) {
$student->displayDetails();
}
$number = 5;
echo "Factorial of $number: " . calculateFactorial($number) . "\n";
echo "Current time: " . date('Y-m-d H:i:s') . "\n";
// Array operations
$squares = array_map(function($x) { return $x * $x; }, range(0, 9));
echo "Squares: " . implode(", ", $squares) . "\n";
// Lambda function
$add = function($x, $y) { return $x + $y; };
echo "Sum of 3 and 5: " . $add(3, 5) . "\n";
// Using math functions
echo "Cosine of 0: " . cos(0) . "\n";
echo "Natural log of E: " . log(E) . "\n";
// Escaped characters
echo "This is a string with a newline character.\nThis is on a new line.\n";
echo "This is a string with a tab character.\tThis is after the tab.\n";
?>
import os
import sys
import math
from datetime import datetime
# Constants
PI = 3.14159
E = 2.71828
class Shape:
"""A base class for different shapes."""
def __init__(self, color="Red"):
self.color = color
def area(self):
raise NotImplementedError("Subclasses should implement this!")
def perimeter(self):
raise NotImplementedError("Subclasses should implement this!")
class Circle(Shape):
"""A class to represent a circle."""
def __init__(self, radius, color="Blue"):
super().__init__(color)
self.radius = radius
def area(self):
return PI * self.radius ** 2
def perimeter(self):
return 2 * PI * self.radius
def __str__(self):
return f"Circle with radius {self.radius} and color {self.color}"
def calculate_factorial(n):
"""Calculate factorial using recursion."""
if n == 0:
return 1
return n * calculate_factorial(n - 1)
def current_time():
"""Returns the current time."""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if __name__ == "__main__":
circle = Circle(5)
print(circle)
print(f"Area: {circle.area()}")
print(f"Perimeter: {circle.perimeter()}")
number = 5
print(f"Factorial of {number}: {calculate_factorial(number)}")
print(f"Current time: {current_time()}")
# File operations
with open("sample.txt", "w") as file:
file.write("This is a sample text file.\n")
file.write(f"Current time: {current_time()}\n")
try:
with open("sample.txt", "r") as file:
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
print("File not found!")
# List comprehension
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")
# Lambda function
add = lambda x, y: x + y
print(f"Sum of 3 and 5: {add(3, 5)}")
# Using math module
print(f"Cosine of 0: {math.cos(0)}")
print(f"Natural log of E: {math.log(E)}")
# Escaped characters
print("This is a string with a newline character.\nThis is on a new line.")
print("This is a string with a tab character.\tThis is after the tab.")
# Constants
PI = 3.14159
E = 2.71828
# Module definition
module Geometry
# Class definition
class Shape
attr_accessor :color
def initialize(color = "Red")
@color = color
end
def area
raise NotImplementedError, "Subclasses must implement the area method"
end
def perimeter
raise NotImplementedError, "Subclasses must implement the perimeter method"
end
end
# Subclass definition
class Circle < Shape
attr_accessor :radius
def initialize(radius, color = "Blue")
super(color)
@radius = radius
end
def area
PI * @radius ** 2
end
def perimeter
2 * PI * @radius
end
def to_s
"Circle with radius #{@radius} and color #{@color}"
end
end
end
# Function definition
def calculate_factorial(n)
return 1 if n == 0
n * calculate_factorial(n - 1)
end
# Main script execution
if __FILE__ == $0
circle = Geometry::Circle.new(5)
puts circle
puts "Area: #{circle.area}"
puts "Perimeter: #{circle.perimeter}"
number = 5
puts "Factorial of #{number}: #{calculate_factorial(number)}"
# File operations
File.open("sample.txt", "w") do |file|
file.puts "This is a sample text file."
file.puts "Current time: #{Time.now}"
end
begin
content = File.read("sample.txt")
puts "File content:\n#{content}"
rescue Errno::ENOENT
puts "File not found!"
end
# Array operations
squares = (0..9).map { |x| x ** 2 }
puts "Squares: #{squares}"
# Lambda function
add = ->(x, y) { x + y }
puts "Sum of 3 and 5: #{add.call(3, 5)}"
# Using Math module
puts "Cosine of 0: #{Math.cos(0)}"
puts "Natural log of E: #{Math.log(E)}"
# Escaped characters
puts "This is a string with a newline character.\nThis is on a new line."
puts "This is a string with a tab character.\tThis is after the tab."
end
import UIKit
// Create a custom UIView subclass
class GreetingView: UIView {
var person: Person
var age = 24
private lazy var greetButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Greetings, fellow humans!", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(greetButtonTapped), for: .touchUpInside)
return button
}()
init(person: Person) {
self.person = person
super.init(frame: .zero)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
addSubview(greetingLabel)
addSubview(greetButton)
NSLayoutConstraint.activate([
greetingLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
greetingLabel.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -20),
greetButton.centerXAnchor.constraint(equalTo: centerXAnchor),
greetButton.topAnchor.constraint(equalTo: greetingLabel.bottomAnchor, constant: 20)
])
}
@objc private func greetButtonTapped() {
greetingLabel.text = person.greet()
}
}
// Example usage
let person = Person(firstName: "John", lastName: "Doe")
let greetingView = GreetingView(person: person)
// Simulate a button tap (usually handled by the user in a real app)
greetingView.greetButton.sendActions(for: .touchUpInside)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment