row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
13,262
|
what is this in byte code, command line keep converting it on my end b'\xe0\xfc\x00'
|
79d7aa2e841665043222c10dbfd755c6
|
{
"intermediate": 0.358648419380188,
"beginner": 0.4042874872684479,
"expert": 0.23706406354904175
}
|
13,263
|
i want to create a laravel table with this content : "knncodes for tasks: tasks price worked
Dayrate Ca Dayrate pre agreed with PM 130
Dayrate Sp Dayrate pre agreed with PM 150
FC4A Clear Blockage in Soft / Footway Surface 105
N300 Test Roding & Roping per 100m 28
" .at the worked column i can insert values numbers that multiplies the price of the row and i need a total price of all like a invoice.i need to download the file in pdf format .in the pdf i need to view codes tasks price worked value and total price,everything .i need when i click generate invoice make the file name with date when it was generated .all the files should be stored on the server to view them later if i want.the project name is knn.public path is public_html.i whant to edit all the lines
|
aa9600ba4c21ff86966edbec348772c3
|
{
"intermediate": 0.3569842278957367,
"beginner": 0.3687879145145416,
"expert": 0.2742278277873993
}
|
13,264
|
write curl what can communicate with chat gpt
|
9dae99300cbba725f6f393dbb4a3a0b0
|
{
"intermediate": 0.3952861726284027,
"beginner": 0.3476710021495819,
"expert": 0.25704285502433777
}
|
13,265
|
You are using Express. js to develop a Turing system. You have a route path in Express.js app. You want to create chainable route handlers for it. How could you do that?
|
a0ea499be7358a586202c5663f397931
|
{
"intermediate": 0.4883919060230255,
"beginner": 0.13886594772338867,
"expert": 0.372742235660553
}
|
13,266
|
The CSS and SASS files import from the version Next. js 9.1
|
3bf8e0e874d3faa39f7ca179f749cdf0
|
{
"intermediate": 0.3441619277000427,
"beginner": 0.21894453465938568,
"expert": 0.4368934631347656
}
|
13,267
|
My input component:
import React from 'react';
import { FormField } from '../FormField';
import styles from './styles.module.css';
const Input = React.forwardRef(
({ label, type = 'text', className, value, onChange, error, name }, ref) => {
return (
<FormField error={error}>
<div className={styles.inputWrapper}>
{label && (
<label
htmlFor={name}
className={styles.inputLabel}
style={{ marginBottom: 0 }}
>
{label}
</label>
)}
<input
type={type}
className={`form-control morphfield ${styles.input} ${className}`}
id={name}
value={value}
onChange={onChange}
ref={ref}
/>
</div>
</FormField>
);
}
);
export { Input };
my Controller that container the form:
import React from 'react';
import { Input } from '../../components/Input';
import { useFormContext, Controller } from 'react-hook-form';
import styles from '../styles.module.css';
const INPUTS = [
{ label: 'Firma', id: 'verzeichnis-firma' },
{ label: 'Bezeichnung', id: 'verzeichnis-bezeichnung' },
{ label: 'Zweck', id: 'verzeichnis-zweck' },
];
const Verzeichnis_Step1 = () => {
const { control, formState } = useFormContext();
console.log('formState: ', formState);
return (
<div className="card-body">
<div className={styles.verzeichnisInputsWrapper}>
{INPUTS.map((input) => (
<Controller
key={input.id}
control={control}
name={`step1.${input.label.toLowerCase()}`}
rules={{ required: true }}
defaultValue=""
render={({ field }) => (
<Input
{...input}
{...field}
value={field.value}
onChange={field.onChange}
error={formState.errors[input.label.toLowerCase()]}
/>
)}
/>
))}
</div>
</div>
);
};
export { Verzeichnis_Step1 };
my form container:
import React, { useContext, useState } from 'react';
import Navbar from '../components/Navbar';
import AuthContext from '../context/AuthProvider';
import { useNavigate } from 'react-router-dom';
import VerzeichnisProzesse from './components/VerzeichnisProzesse';
import VerzeichnisStart from './components/VerzeichnisStart';
import { VerzeichnisFormular } from './components/VerzeichnisFormular';
import { useForm, FormProvider } from 'react-hook-form';
const generateUniqueId = () => {
return Math.random().toString(36).substr(2, 6).toUpperCase();
};
const Verzeichnis = () => {
const { auth, setToken } = useContext(AuthContext);
const navigate = useNavigate();
const [activeStep, setActiveStep] = useState(0);
const handleNext = () => {
setActiveStep((prevStep) => prevStep + 1);
};
const handleBack = () => {
setActiveStep((prevStep) => prevStep - 1);
};
const methods = useForm({ mode: 'onChange' });
const onSubmit = (data) => {
const formattedData = { ...data, id: generateUniqueId() };
if (activeStep === 9) {
const prevData = JSON.parse(localStorage.getItem('verzeichnisData'));
const newData = prevData ? [formattedData, ...prevData] : [formattedData];
localStorage.setItem('verzeichnisData', JSON.stringify(newData));
navigate('/VerzeichnisOverview');
}
console.log(data);
};
console.log('formValues: ', methods.getValues());
return (
<div className="wrapper">
<div id="content">
<div className="container">
<div className="row topmargin100">
<div className="col-md-2"></div>
<div className="card col-md-8">
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
{activeStep === 0 && <VerzeichnisStart next={handleNext} />}
{activeStep === 1 && (
<VerzeichnisProzesse next={handleNext} back={handleBack} />
)}
{activeStep > 1 && (
<VerzeichnisFormular
activeStep={activeStep}
next={handleNext}
back={handleBack}
/>
)}
</form>
</FormProvider>
</div>
<div className="col-md-2"></div>
</div>
</div>
</div>
</div>
);
};
export default Verzeichnis;
why is validation rules not working? In this case the 'required' is not working. I can submit the form without the fields being filled in
|
d7b3804122c0e0eb3b78a60913bc6863
|
{
"intermediate": 0.33686041831970215,
"beginner": 0.4909423589706421,
"expert": 0.17219728231430054
}
|
13,268
|
print the model view matrix
|
bed2bd44b579fc39312d3612fb9e7a60
|
{
"intermediate": 0.25435879826545715,
"beginner": 0.1536683440208435,
"expert": 0.591972827911377
}
|
13,269
|
give me informations about Global Business Solutions
|
55b5fd9bec878db39273f53a4a788c0e
|
{
"intermediate": 0.5788976550102234,
"beginner": 0.24169494211673737,
"expert": 0.17940743267536163
}
|
13,270
|
$ git push --set-upstream origin extend-uam-tests
Enumerating objects: 50, done.
Counting objects: 100% (48/48), done.
Delta compression using up to 12 threads
Compressing objects: 100% (36/36), done.
Writing objects: 100% (36/36), 6.12 KiB | 2.04 MiB/s, done.
Total 36 (delta 22), reused 0 (delta 0), pack-reused 0
remote: GitLab: Commit must be signed with a GPG key
To https://git.rvision.pro/rpoint/rpoint-at.git
! [remote rejected] extend-uam-tests -> extend-uam-tests (pre-receive hook declined)
error: failed to push some refs to ‘https://git.rvision.pro/rpoint/rpoint-at.git’
что мне делать, быстрее
|
7f1716e588ca2551eb13de66bd9b76db
|
{
"intermediate": 0.3456975519657135,
"beginner": 0.3083372414112091,
"expert": 0.345965176820755
}
|
13,271
|
please add logo of html landing page
|
8a40d74cc0d1a40becdf2910bd18ee82
|
{
"intermediate": 0.3756715953350067,
"beginner": 0.29181984066963196,
"expert": 0.33250853419303894
}
|
13,272
|
modern opengl and old opengl what is the main difference, is pyopengl suppport modern opengl?
|
64f048e4ea4be6aaed3396fe2d6fc498
|
{
"intermediate": 0.36205992102622986,
"beginner": 0.2718350291252136,
"expert": 0.3661050498485565
}
|
13,273
|
heyy, act as a professional developer and teach me C++ from the scratch
|
15db2e7888ac3235962807840165dc04
|
{
"intermediate": 0.3789873719215393,
"beginner": 0.3228774964809418,
"expert": 0.29813510179519653
}
|
13,274
|
my react hook form does not trigger validation if I submit form without touching fields
|
bf0c121b1a7f207d9eb6da71f1de9563
|
{
"intermediate": 0.5037062764167786,
"beginner": 0.1894996166229248,
"expert": 0.30679404735565186
}
|
13,275
|
is there a component that contains text and a copy to clipboard button in antDesign?
|
26bab10992b293c593933f518dc1a6fa
|
{
"intermediate": 0.4241287112236023,
"beginner": 0.31677162647247314,
"expert": 0.25909969210624695
}
|
13,276
|
I have a mysql table:
creaate table transaction (
name varchar(10) not null,
firstdate timestamp default CURRENT_DATETIME,
expirydate timestamp default DATE_ADD(now(), INTERVAL 1 MONTH)):
I want to select all record's name and if firstdate > expirdate, then 1, else 0. how to do?
|
ca9f690f13569b6b54ec30672350405b
|
{
"intermediate": 0.49602895975112915,
"beginner": 0.2775275409221649,
"expert": 0.22644354403018951
}
|
13,277
|
suivant cette ligne de code " bytes1 firstLetterBytes = bytes(find[_gameId].word)[0];" qui appartient au contrat "Penduel", comment accéder à la structure Find d’un autre contrat que "Pendue" avec ces éléments suivant : " structure Find"struct Find {
Game game;
string word;
string firstLetter;
string letterToGuess;
string letterWin;
string wordToGuess;
}” struct Game " structure Game " struct Game {
address player1;
address player2;
address activePlayer;
uint64 gameId;
uint256 _requestId;
uint32 playerMove;
" les mappings “mapping(uint64 => Game) public games;” “mapping(address => mapping(uint => bool)) public gameFindsLetters;”
" mapping(address => mapping(uint64 => string)) public gameFindsWords;" ?
|
94ec976f98c6f665a7acb7cac109669e
|
{
"intermediate": 0.3711191713809967,
"beginner": 0.31029531359672546,
"expert": 0.31858551502227783
}
|
13,278
|
hi
|
e1e5e8c69a558c69fd1b540c11fa8169
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
13,279
|
Halo, if you give me code of python about algorithm metaheuristik?
|
b6234fd6d9fec6240e8df1a8fb1218d3
|
{
"intermediate": 0.09792065620422363,
"beginner": 0.08724090456962585,
"expert": 0.8148384690284729
}
|
13,280
|
negative samples, changing their labels to positive, and retraining the model based on the following paper:
https://github.com/UFNRec-code/UFNRec/tree/main
Please implement this code in the PTGCN model and give or show it to me.
|
0e0a8c347732ddf032bb0b63ce1e66be
|
{
"intermediate": 0.12635311484336853,
"beginner": 0.09467337280511856,
"expert": 0.7789735794067383
}
|
13,281
|
generate me a data image url with a blue stickman
|
484b19e319300aaf3cb1624b63024306
|
{
"intermediate": 0.438776433467865,
"beginner": 0.17054614424705505,
"expert": 0.39067745208740234
}
|
13,282
|
I know what this code does but try to guess what this code does:
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
document.title = data.ip;
})
|
7a71ad1413950177acffe65a88ba2120
|
{
"intermediate": 0.5531611442565918,
"beginner": 0.2677173912525177,
"expert": 0.1791214644908905
}
|
13,283
|
what is the minecraft java edition source code
|
bc42bfec1a7c11ff9638a618639c99d8
|
{
"intermediate": 0.37741780281066895,
"beginner": 0.3252412676811218,
"expert": 0.29734092950820923
}
|
13,284
|
how to use javascipt function on flask jinja template variables
|
e140b66b7e40f113cefcac433b38bea4
|
{
"intermediate": 0.6235973238945007,
"beginner": 0.19812068343162537,
"expert": 0.17828205227851868
}
|
13,285
|
English: As a tester, I have thoroughly analyzed ProgressTris and can confidently say that it is a challenging and enjoyable game with a variety of features and settings.
Spanish: Como tester, he analizado minuciosamente ProgressTris y puedo decir con confianza que es un juego desafiante y agradable con una variedad de características y configuraciones.
French: En tant que testeur, j’ai soigneusement analysé ProgressTris et je peux dire avec confiance que c’est un jeu stimulant et agréable avec une variété de fonctionnalités et de réglages.
German: Als Tester habe ich ProgressTris gründlich analysiert und kann mit Zuversicht sagen, dass es ein herausforderndes und unterhaltsames Spiel mit vielen Funktionen und Einstellungen ist.
Simplify
|
7307fad5b5f76b7e5fb154c3b0c1214d
|
{
"intermediate": 0.3389926254749298,
"beginner": 0.37234991788864136,
"expert": 0.2886574864387512
}
|
13,286
|
Turn into a boot pep. It is a preparation of the footer and will present options. A html with orofijhe and a go dodo. And a css with modern togo sans with 23 pixels.
|
34507de74e342738bf903bf1de67f67e
|
{
"intermediate": 0.4030759036540985,
"beginner": 0.23863665759563446,
"expert": 0.3582874536514282
}
|
13,287
|
Explain the FOurier Transform in simple terms
|
ce6fca221bb9c2c46854e3de5bb5e152
|
{
"intermediate": 0.2979666292667389,
"beginner": 0.19089841842651367,
"expert": 0.511134922504425
}
|
13,288
|
Please give me an example to get a good intuition for statistical likelihood. It could focus on different sided dies or even two dies being added. The example should be implementable in R and show how data can inform the relative evidence of each model.
|
cd9ad0c77406fd17eb7444c173a8e09b
|
{
"intermediate": 0.3958069980144501,
"beginner": 0.13839039206504822,
"expert": 0.4658026397228241
}
|
13,289
|
Act as a React web developer expert.
This is my AddRoute.jsx:
import { useEffect, useState } from 'react';
import { Alert, Col, Container, Row } from 'react-bootstrap';
import { ActionList, BlockList, CreatePageBody, Title } from './AddComponents';
import { BackButton } from './NavigationComponents';
import API from '../API';
function AddRoute(props) {
const [list, setList] = useState([]); // Used as array of objects
const [title, setTitle] = useState("");
const [isLoading, setIsLoading] = useState(true);
const [images, setImages] = useState([]) // For storing urls and alts of the images retrieved by server.
//const [dirtylist, dirtySetList] = useState(true);
useEffect(() => { props.setDirtyWebsiteName(true) }, []); // For handling multi-user experience. Every route visited we request again WebsiteName
useEffect(() => { props.handleError('') }, []);
useEffect(() => {
API.getImages()
.then((x) => {
setImages(x);
setIsLoading(false);
})
.catch((err) => props.handleError(err)); // handleError defined in App.jsx
}, []);
return (
<Container fluid>
<p></p>
<Row>
<Col xs={2}>
<BackButton />
</Col>
<Col>
<h2 style={{ textAlign: "center" }}>Create Page</h2>
<p></p>
{props.errorMsg && <Alert variant='danger' onClose={() => props.handleError('')} dismissible>{props.errorMsg}</Alert>}
{isLoading ?
<props.LoadingBody />
:
<>
<Title title={title} setTitle={setTitle} />
<p></p>
<CreatePageBody list={list} setList={setList} images={images} hh={hh}/>
</>
}
</Col>
<Col xs={2}>
<Col style={{ position: "relative", paddingRight: "10%", top: "50px" }}>
{isLoading ?
<props.LoadingBody />
:
<>
<BlockList list={list} setList={setList} />
<ActionList setList={setList} title={title} list={list} errorMsg={props.errorMsg} handleError={props.handleError} />
</>
}
</Col>
</Col>
</Row>
</Container>
);
}
export default AddRoute;
This is my AddComponents.jsx:
import 'bootstrap-icons/font/bootstrap-icons.css';
import '../style.css';
import { Accordion, Button, ButtonGroup, Card, Col, Form, ListGroup } from 'react-bootstrap';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import API from '../API';
import dayjs from 'dayjs';
//Can't get it from database because it is not saved.
//This number is used only for triggering the re-render of the content of the Forms of each block showed at video. (ex when handleUp or handleDown)
function generatelocalId() {
return Math.random().toString(36).substring(2) + Date.now().toString(36);
}
function BlockList(props) {
function headerBlock() {
this.blockType = "Header";
this.content = "";
}
function paragraphBlock() {
this.blockType = "Paragraph";
this.content = "";
}
function imageBlock() {
this.blockType = "Image";
this.content = "";
}
const addToList = (x) => {
props.setList((oldList) => [...oldList, x]);
};
return (
<>
<h5 style={{ textAlign: "center" }}>Components</h5>
<p></p>
<Card>
<ListGroup>
<ListGroup.Item >
Header
<Button className="float-end addbutton" variant="outline-success"
onClick={() => {
addToList(new headerBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
<ListGroup.Item >
Paragraph
<Button className="float-end addbutton" variant="outline-success"
onClick={() => {
addToList(new paragraphBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
<ListGroup.Item >
Image
<Button className="float-end addbutton" variant="outline-success"
onClick={() => {
addToList(new imageBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
</ListGroup>
</Card>
</>
);
}
function CreatePageBody(props) {
return (
<Accordion>
{props.list.map((x) => <MyBlock x={x} key={generatelocalId()} list={props.list} setList={props.setList} images={props.images} />)}
</Accordion>
);
}
function MyBlock(props) {
const x = props.x;
const images = props.images;
const [content, setContent] = useState(x.content);
const removeFromList = (x) => {
props.setList((oldlist) => oldlist.filter((item) => item != x));
};
const handleUp = (x) => {
props.setList(oldList => {
const index = oldList.indexOf(x);
const newList = [...oldList];
[newList[index - 1], newList[index]] = [newList[index], newList[index - 1]];
return newList;
});
};
const handleDown = (x) => {
props.setList(oldList => {
const index = oldList.indexOf(x);
const newList = [...oldList];
[newList[index], newList[index + 1]] = [newList[index + 1], newList[index]];
return newList;
});
};
return (
<Accordion.Item eventKey={props.list.indexOf(x)}>
<Accordion.Header >
<div className="accordion-style">
{x.blockType}
<ButtonGroup style={{ paddingRight: "2%" }} >
{props.list.indexOf(x) != 0 && ( //button as div avoid nested buttons error validateDOMnesting - since accordion header is a button itself!
<Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary"
onClick={(ev) => { ev.stopPropagation(); handleUp(x) }}>
<i className="bi bi-arrow-up"></i>
</Button>)}
{props.list.indexOf(x) != (props.list.length - 1) && (
<Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary"
onClick={(ev) => { ev.stopPropagation(); handleDown(x) }}>
<i className="bi bi-arrow-down"></i>
</Button>)}
<Button as='div' size="sm" variant="outline-danger"
onClick={(ev) => { ev.stopPropagation(); removeFromList(x) }}>
<i className="bi bi-x-lg"></i>
</Button>
</ButtonGroup>
</div>
</Accordion.Header>
<Accordion.Body>
{x.blockType != "Image" ? (
<Form.Control as="textarea" value={content} onChange={(ev) => { x.content = ev.target.value; setContent(ev.target.value); }}></Form.Control>
) : (
<div>
{images.map((image) => (
<label key={generatelocalId()} style={{ paddingRight: "20px" }}>
<input value={image.url} onChange={(ev) => { x.content = ev.target.value; setContent(ev.target.value); }} checked={content == image.url} type="radio" />
<img className="img-box" src={image.url} alt={image.alt} />
</label>
))}
</div>
)}
</Accordion.Body>
</Accordion.Item>
);
}
function ActionList(props) {
// Placed here because otherwise handleAction couldn't call navigate.
// Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
const navigate = useNavigate();
const [date, setDate] = useState(""); // Used to publish programmed pages
const list = props.list;
const title = props.title;
return (
<Col className="pt-4">
<Button variant="warning" style={{ marginBottom: "2%", width: "100%" }} onClick={() => handleAction("draft")}>Save as Draft</Button>
<Button variant="success" style={{ marginBottom: "10%", width: "100%" }} onClick={() => handleAction("publish")}>Publish</Button>
<Form.Control type="date" name="date" value={date} onChange={(ev) => setDate(ev.target.value)} />
<Button variant="secondary" style={{ marginTop: "2%", width: "100%" }} onClick={() => handleAction("programmed")}>Schedule Publication</Button>
</Col>
);
function handleAction(action) {
let valid = true;
let data = {};
if (title.trim() == "") {
valid = false;
props.handleError("You have to choose a title for the page.");
}
else if (!(list.some(item => item.blockType == 'Header')) ||
(!(list.some(item => item.blockType == 'Paragraph') || list.some(item => item.blockType == 'Image')))
) {
valid = false;
props.handleError("You have to insert at least a Header and a Paragraph/Image.");
}
else if (list.some(item => (item.content.trim() == ""))) {
valid = false;
props.handleError("At least one block without content!");
}
if (valid) {
data = { // Data formatted. Ready to send it to the server for Page Creation.
title: title,
blocks: JSON.stringify(list) // Saved directly as json in db
};
switch (action) {
case "draft":
Object.assign(data, { publishDate: null });
break;
case "publish":
Object.assign(data, { publishDate: dayjs().format("YYYY-MM-DD") });
break;
case "programmed":
const Date = dayjs(date);
if (!Date.isValid() || Date.isBefore(dayjs())) { //dayjs() returns today date
props.handleError("Select a valid date.");
return;
}
Object.assign(data, { publishDate: Date.format("YYYY-MM-DD") });
break;
default:
break;
}
API.createPage(data)
.then(() => {
navigate("/backoffice")
})
.catch((err) => props.handleError(err));
}
}
}
function Title(props) {
return (
<Form.Control type="text" name="text" autoFocus value={props.title} placeholder="Page Title" onChange={ev => props.setTitle(ev.target.value)} />
);
}
export { Title, ActionList, BlockList, CreatePageBody, MyBlock };
In AddComponents.jsx how can I avoid doing x.content = ev.target.value ? And, is it wrong anyway?
|
13f91ce2366247e6685b8bc6c1fc02c1
|
{
"intermediate": 0.5109530091285706,
"beginner": 0.3927328586578369,
"expert": 0.09631422907114029
}
|
13,290
|
will asp.net core routing work without app.UseRouting() call ?
|
42abe8ea33a7acbae5be94ff3cbbc141
|
{
"intermediate": 0.4671628177165985,
"beginner": 0.24870792031288147,
"expert": 0.28412926197052
}
|
13,291
|
get element attibute value xml dom4j example
|
a66d458dd7418b83330f4c63075dec65
|
{
"intermediate": 0.47259101271629333,
"beginner": 0.26435497403144836,
"expert": 0.2630540132522583
}
|
13,292
|
why should I customize user identity in asp.net core
|
4e8fbdca1f994b575302e041a7894192
|
{
"intermediate": 0.4640030860900879,
"beginner": 0.24357984960079193,
"expert": 0.2924170196056366
}
|
13,293
|
Explain Cwt vs stft for ecg signal 1d to 2d conversion
|
6fe60e77bf409cb63b5c05900f0fb556
|
{
"intermediate": 0.3540393114089966,
"beginner": 0.23176315426826477,
"expert": 0.4141976237297058
}
|
13,294
|
import 'bootstrap-icons/font/bootstrap-icons.css';
import '../style.css';
import { Accordion, Button, ButtonGroup, Card, Col, Form, ListGroup } from 'react-bootstrap';
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import API from '../API';
import dayjs from 'dayjs';
//Can't get it from database because it is not saved.
//This number is used only for triggering the re-render of the content of the Forms of each block showed at video. (ex when handleUp or handleDown)
function generatelocalId() {
return Math.random().toString(36).substring(2) + Date.now().toString(36);
}
function BlockList(props) {
function headerBlock() {
this.blockType = "Header";
this.content = "";
}
function paragraphBlock() {
this.blockType = "Paragraph";
this.content = "";
}
function imageBlock() {
this.blockType = "Image";
this.content = "";
}
const addToList = (x) => {
props.setList((oldList) => [...oldList, x]);
};
return (
<>
<h5 style={{ textAlign: "center" }}>Components</h5>
<p></p>
<Card>
<ListGroup>
<ListGroup.Item >
Header
<Button className="float-end addbutton" variant="outline-success"
onClick={() => {
addToList(new headerBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
<ListGroup.Item >
Paragraph
<Button className="float-end addbutton" variant="outline-success"
onClick={() => {
addToList(new paragraphBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
<ListGroup.Item >
Image
<Button className="float-end addbutton" variant="outline-success"
onClick={() => {
addToList(new imageBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
</ListGroup>
</Card>
</>
);
}
function CreatePageBody(props) {
return (
<Accordion>
{props.list.map((x) => <MyBlock x={x} key={generatelocalId()} list={props.list} setList={props.setList} images={props.images} />)}
</Accordion>
);
}
function MyBlock(props) {
const x = props.x;
const images = props.images;
const [content, setContent] = useState(x.content);
const [notAligned, setNotAligned] = useState(false);
const removeFromList = (x) => {
props.setList((oldlist) => oldlist.filter((item) => item != x));
};
const handleUp = (x) => {
props.setList(oldList => {
const index = oldList.indexOf(x);
const newList = [...oldList];
[newList[index - 1], newList[index]] = [newList[index], newList[index - 1]];
return newList;
});
};
const handleDown = (x) => {
props.setList(oldList => {
const index = oldList.indexOf(x);
const newList = [...oldList];
[newList[index], newList[index + 1]] = [newList[index + 1], newList[index]];
return newList;
});
};
const handleContentChange = (x) => {
props.setList((oldList) => {
const newList = oldList.map((item) => (item === x ? { ...item, content: content } : item));
return newList;
})
};
useEffect(() => {
if(notAligned){
handleContentChange(x);
setNotAligned(false);
}
}, [notAligned]);
return (
<Accordion.Item eventKey={props.list.indexOf(x)}>
<Accordion.Header >
<div className="accordion-style">
{x.blockType}
<ButtonGroup style={{ paddingRight: "2%" }} >
{props.list.indexOf(x) != 0 && ( //button as div avoid nested buttons error validateDOMnesting - since accordion header is a button itself!
<Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary"
onClick={(ev) => { ev.stopPropagation(); handleUp(x) }}>
<i className="bi bi-arrow-up"></i>
</Button>)}
{props.list.indexOf(x) != (props.list.length - 1) && (
<Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary"
onClick={(ev) => { ev.stopPropagation(); handleDown(x) }}>
<i className="bi bi-arrow-down"></i>
</Button>)}
<Button as='div' size="sm" variant="outline-danger"
onClick={(ev) => { ev.stopPropagation(); removeFromList(x) }}>
<i className="bi bi-x-lg"></i>
</Button>
</ButtonGroup>
</div>
</Accordion.Header>
<Accordion.Body>
{x.blockType != "Image" ? (
<Form.Control as="textarea" value={content} onChange={(ev) => { setContent(ev.target.value); setNotAligned(true); }} ></Form.Control>
) : (
<div>
{images.map((image) => (
<label key={generatelocalId()} style={{ paddingRight: "20px" }}>
<input value={image.url} onChange={(ev) => { setContent(ev.target.value); setNotAligned(true); }} checked={content == image.url} type="radio" />
<img className="img-box" src={image.url} alt={image.alt} />
</label>
))}
</div>
)}
</Accordion.Body>
</Accordion.Item>
);
}
function ActionList(props) {
// Placed here because otherwise handleAction couldn't call navigate.
// Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
const navigate = useNavigate();
const [date, setDate] = useState(""); // Used to publish programmed pages
const list = props.list;
const title = props.title;
return (
<Col className="pt-4">
<Button variant="warning" style={{ marginBottom: "2%", width: "100%" }} onClick={() => handleAction("draft")}>Save as Draft</Button>
<Button variant="success" style={{ marginBottom: "10%", width: "100%" }} onClick={() => handleAction("publish")}>Publish</Button>
<Form.Control type="date" name="date" value={date} onChange={(ev) => setDate(ev.target.value)} />
<Button variant="secondary" style={{ marginTop: "2%", width: "100%" }} onClick={() => handleAction("programmed")}>Schedule Publication</Button>
</Col>
);
function handleAction(action) {
let valid = true;
let data = {};
if (title.trim() == "") {
valid = false;
props.handleError("You have to choose a title for the page.");
}
else if (!(list.some(item => item.blockType == 'Header')) ||
(!(list.some(item => item.blockType == 'Paragraph') || list.some(item => item.blockType == 'Image')))
) {
valid = false;
props.handleError("You have to insert at least a Header and a Paragraph/Image.");
}
else if (list.some(item => (item.content.trim() == ""))) {
valid = false;
props.handleError("At least one block without content!");
}
if (valid) {
data = { // Data formatted. Ready to send it to the server for Page Creation.
title: title,
blocks: JSON.stringify(list) // Saved directly as json in db
};
switch (action) {
case "draft":
Object.assign(data, { publishDate: null });
break;
case "publish":
Object.assign(data, { publishDate: dayjs().format("YYYY-MM-DD") });
break;
case "programmed":
const Date = dayjs(date);
if (!Date.isValid() || Date.isBefore(dayjs())) { //dayjs() returns today date
props.handleError("Select a valid date.");
return;
}
Object.assign(data, { publishDate: Date.format("YYYY-MM-DD") });
break;
default:
break;
}
API.createPage(data)
.then(() => {
navigate("/backoffice")
})
.catch((err) => props.handleError(err));
}
}
}
function Title(props) {
return (
<Form.Control type="text" name="text" autoFocus value={props.title} placeholder="Page Title" onChange={ev => props.setTitle(ev.target.value)} />
);
}
export { Title, ActionList, BlockList, CreatePageBody, MyBlock };
The use of setNotAligned(true) makes me stop writing inside the form. I want to be able to keep writing how much I want
|
54ac7c1ff7eaed3a840edf37bea6969f
|
{
"intermediate": 0.39975354075431824,
"beginner": 0.4865495264530182,
"expert": 0.11369693279266357
}
|
13,295
|
hi
|
d35f8082d460e1bc54810b6baf037d9d
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
13,296
|
When i use `viewContainerRef.createComponent`, the dynamic component not load ngOninit!
my code:
import { ChangeDetectorRef, Component, ComponentRef, ElementRef, ViewChild, ViewContainerRef } from '@angular/core';
import { EmojiServiceService } from './emoji-service.service';
import { EmojiComponent } from './emoji/emoji.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'myQuery';
@ViewChild('emojiInput') emojiInput: ElementRef;
emojiComponentRef: ComponentRef<EmojiComponent>;
constructor(
private es: EmojiServiceService,
private viewContainerRef: ViewContainerRef
) { }
addEmoji(event: any) {
const emojiInput = this.emojiInput.nativeElement;
const selection = window.getSelection();
const emojiInputRange = document.createRange();
emojiInputRange.selectNodeContents(emojiInput);
this.emojiComponentRef = this.viewContainerRef.createComponent(EmojiComponent);
this.emojiComponentRef.instance.id = event.id;
this.emojiComponentRef.instance.size = '24px';
const emojiNode = this.emojiComponentRef.location.nativeElement;
if (selection && selection.focusNode && emojiInputRange.isPointInRange(selection.focusNode, selection.focusOffset)) {
const range = selection.getRangeAt(0);
if (selection.isCollapsed) {
// Insert the emoji at the cursor position
range.insertNode(emojiNode);
range.collapse(false);
} else {
// Replace the selected text with the emoji
range.deleteContents();
range.insertNode(emojiNode);
}
// Move the cursor to the end of the inserted emoji
range.setStartAfter(emojiNode);
range.collapse(true);
// Update the selection and focus the emoji input
selection.removeAllRanges();
selection.addRange(range);
emojiInput.focus();
}
}
}
|
084674577147541680e04f02edfc038a
|
{
"intermediate": 0.4574592113494873,
"beginner": 0.259360671043396,
"expert": 0.2831801474094391
}
|
13,297
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
48c1b82749040e38f53547b2be1cff36
|
{
"intermediate": 0.46675726771354675,
"beginner": 0.330436110496521,
"expert": 0.20280657708644867
}
|
13,298
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
09d61f416676f0298b4fb2838588c167
|
{
"intermediate": 0.46675726771354675,
"beginner": 0.330436110496521,
"expert": 0.20280657708644867
}
|
13,299
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
7a4b6b15db9122bca09848e51ef3590f
|
{
"intermediate": 0.46675726771354675,
"beginner": 0.330436110496521,
"expert": 0.20280657708644867
}
|
13,300
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
835b7e8391edab24eaf5d265fd268774
|
{
"intermediate": 0.46675726771354675,
"beginner": 0.330436110496521,
"expert": 0.20280657708644867
}
|
13,301
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
38be578dc00cfb641605e66041ff8eb8
|
{
"intermediate": 0.46675726771354675,
"beginner": 0.330436110496521,
"expert": 0.20280657708644867
}
|
13,302
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
e8924588e95ac60e740fd595ca296345
|
{
"intermediate": 0.4312450587749481,
"beginner": 0.37657031416893005,
"expert": 0.19218459725379944
}
|
13,303
|
Find the solution of the following PDEs
𝑝 tan 𝑥 + 𝑞 tan 𝑦 = tan z
|
9f9ed47d0dfd32dfb82662d9fbd571bb
|
{
"intermediate": 0.35124650597572327,
"beginner": 0.2321559488773346,
"expert": 0.41659754514694214
}
|
13,304
|
When i try to add in a new ticket, it isn't rendering on the screen properly, only after i come back to that page the ticket is added on the table fix it...import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import { getJwtToken } from "../GlobalVar/JwtToken";
import { getUserObject } from "../GlobalVar/UserObject";
import "./ProjectView.css";
import AddTicket from "../component/Modal/AddTicket";
function ProjectView() {
const [project, setProject] = useState(null);
const [userObject, setUserObject] = useState(null);
const [showAddTicketModal, setShowAddTicketModal] = useState(false);
const params = useParams();
const handleAddMember = () => {};
const handleAddTicket = async () => {
setShowAddTicketModal(true);
};
const handleEditTicket = (ticketId) => {};
const handleRemoveTicket = (ticketId) => {};
useEffect(() => {
const jwtToken = getJwtToken();
const fetchProject = async () => {
try {
const response = await axios.get(
`http://localhost:8080/dashboard/project/${params.projectId}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`,
},
}
);
setProject(response.data);
} catch (error) {
console.error("Error fetching project:", error);
}
};
const fetchUserObject = async () => {
try {
const userObject = await getUserObject();
setUserObject(userObject);
} catch (error) {
console.error("Error fetching user object:", error);
}
};
fetchProject();
fetchUserObject();
}, []);
const handleTicketAdded = (ticket) => {
setProject((prevProject) => {
const updatedTickets = [...prevProject.tickets, ticket];
const updatedProject = { ...prevProject, tickets: updatedTickets };
return updatedProject;
});
setShowAddTicketModal(false);
};
if (!project || !userObject) {
return <div>Loading...</div>;
}
return (
<div className="project-details">
<h2 className="section-title">Project Details</h2>
<table className="details-table">
<thead>
<tr>
<th>Project ID</th>
<th>Project Name</th>
<th>Description</th>
<th>Project Identifier</th>
<th>Date Created</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody>
<tr>
<td>{project.projectId}</td>
<td>{project.projectName}</td>
<td>{project.description}</td>
<td>{project.projectIdentifier}</td>
<td>{project.dateCreated}</td>
<td>{project.lastUpdated}</td>
</tr>
</tbody>
</table>
<h2 className="section-title">Project Associates</h2>
<table className="associates-table">
<thead>
<tr>
<th>Email</th>
</tr>
</thead>
<tbody>
{project.projectAssociates.map((associate) => (
<tr key={associate}>
<td>{associate}</td>
</tr>
))}
</tbody>
</table>
<h2 className="section-title">Tickets</h2>
<table className="tickets-table">
<thead>
<tr>
<th>Ticket ID</th>
<th>Title</th>
<th>Description</th>
<th>Status</th>
{userObject.role === "ADMIN" || userObject.role === "MANAGER" ? (
<th>Actions</th>
) : null}
</tr>
</thead>
<tbody>
{project.tickets.map((ticket) => (
<tr key={ticket.id}>
<td>{ticket.id}</td>
<td>{ticket.ticketName}</td>
<td>{ticket.description}</td>
<td>{ticket.ticketStatus}</td>
{userObject.role === "ADMIN" || userObject.role === "MANAGER" ? (
<td>
<button
className="edit-button"
onClick={() => handleEditTicket(ticket.id)}
>
Edit
</button>
<button
className="remove-button"
onClick={() => handleRemoveTicket(ticket.id)}
>
Remove
</button>
</td>
) : null}
</tr>
))}
</tbody>
</table>
{userObject.role === "ADMIN" || userObject.role === "MANAGER" ? (
<div className="add-member-button-container">
<button className="add-member-button" onClick={handleAddMember}>
Add Member
</button>
</div>
) : null}
{userObject.role === "ADMIN" || userObject.role === "MANAGER" ? (
<div className="add-ticket-button-container">
<button className="add-ticket-button" onClick={handleAddTicket}>
Add Ticket
</button>
</div>
) : null}
{/* Render the modal if showAddTicketModal state is true */}
{showAddTicketModal && (
<div className="add-ticket-container">
<AddTicket
onAddTicket={handleTicketAdded}
projectId={params.projectId}
/>
</div>
)}
</div>
);
}
export default ProjectView;
this is the add ticket moda
import React, { useState } from "react";
import axios from "axios";
import { getJwtToken } from "../../GlobalVar/JwtToken";
function AddTicket({ onAddTicket, projectId }) {
const [ticketName, setTicketName] = useState("");
const [roles, setRoles] = useState("");
const [description, setDescription] = useState("");
const [priority, setPriority] = useState("");
const [type, setType] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false); // Added isSubmitting state
const handleSubmit = async (e) => {
e.preventDefault();
if (isSubmitting) {
return; // Prevent multiple submissions
}
setIsSubmitting(true); // Set isSubmitting to true when submit button is clicked
const ticket = {
ticketName,
roles,
description,
priority,
type,
};
try {
const jwtToken = getJwtToken();
const response = await axios.put(
`http://localhost:8080/dashboard/project/add-ticket/${projectId}`,
ticket,
{
headers: {
Authorization: `Bearer ${jwtToken}}`,
},
}
);
setTicketName("");
setRoles("");
setDescription("");
setPriority("");
setType("");
onAddTicket(response.data);
} catch (error) {
console.error("Error adding ticket:", error);
} finally {
setIsSubmitting(false); // Reset isSubmitting to false after submission
}
};
return (
<div>
<h2>Add Ticket</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Ticket Name:</label>
<input
type="text"
value={ticketName}
onChange={(e) => setTicketName(e.target.value)}
required
/>
</div>
<div>
<label>Roles:</label>
<input
type="text"
value={roles}
onChange={(e) => setRoles(e.target.value)}
required
/>
</div>
<div>
<label>Description:</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
required
></textarea>
</div>
<div>
<label>Priority:</label>
<select
value={priority}
onChange={(e) => setPriority(e.target.value)}
required
>
<option value="">Select Priority</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
<div>
<label>Type:</label>
<select
value={type}
onChange={(e) => setType(e.target.value)}
required
>
<option value="">Select Type</option>
<option value="Bug">Bug</option>
<option value="Feature">Feature</option>
<option value="Enhancement">Enhancement</option>
</select>
</div>
<button type="submit" disabled={isSubmitting}>Submit</button>
</form>
</div>
);
}
export default AddTicket;
|
cf876021ed9889197c940c4162cec600
|
{
"intermediate": 0.37105271220207214,
"beginner": 0.4331842064857483,
"expert": 0.19576309621334076
}
|
13,305
|
How to create a custom Ubuntu live from scratch
This procedure shows how to create a bootable and installable Ubuntu Live (along with the automatic hardware detection and configuration) from scratch. The steps described below are also available in this repo in the /scripts directory.
Authors
• Marcos Vallim - Founder, Author, Development, Test, Documentation - mvallim
• Ken Gilmer - Commiter, Development, Test, Documentation - kgilmer
See also the list of contributors who participated in this project.
Ways of Using this Tutorial
• (Recommended) follow the directions step by step below to understand how to build an Ubuntu ISO.
• Run the build.sh script in the scripts directory after checking this repo out locally.
• Fork this repo and run the github action build. This will generate an ISO in your github account.
Terms
• build system - the computer environment running the build scripts that generate the ISO.
• live system - the computer environment that runs from the live OS, generated by a build system. This may also be referred to as the chroot environment.
• target system - the computer environment that runs after installation has completed from a live system.
Prerequisites (GNU/Linux Debian/Ubuntu)
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
Bootstrap and Configure Ubuntu
debootstrap is a program for generating OS images. We install it into our build system to begin generating our ISO.
• Checkout bootstrap
sudo debootstrap \
--arch=amd64 \
--variant=minbase \
focal \
$HOME/live-ubuntu-from-scratch/chroot \
http://us.archive.ubuntu.com/ubuntu/
debootstrap is used to create a Debian base system from scratch, without requiring the availability of dpkg or apt. It does this by downloading .deb files from a mirror site, and carefully unpacking them into a directory which can eventually be chrooted into.
• Configure external mount points
sudo mount --bind /dev $HOME/live-ubuntu-from-scratch/chroot/dev
sudo mount --bind /run $HOME/live-ubuntu-from-scratch/chroot/run
As we will be updating and installing packages (grub among them), these mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
Define chroot environment
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. The term "chroot" may refer to the chroot system call or the chroot wrapper program. The modified environment is called a chroot jail.
Reference: https://en.wikipedia.org/wiki/Chroot
From this point we will be configuring the live system.
1. Access chroot environment
sudo chroot $HOME/live-ubuntu-from-scratch/chroot
2. Configure mount points, home and locale
mount none -t proc /proc
mount none -t sysfs /sys
mount none -t devpts /dev/pts
export HOME=/root
export LC_ALL=C
These mount points are necessary inside the chroot environment, so we are able to finish the installation without errors.
3. Set a custom hostname
echo "ubuntu-fs-live" > /etc/hostname
4. Configure apt sources.list
cat <<EOF > /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
EOF
5. Update indexes packages
apt-get update
6. Install systemd
apt-get install -y libterm-readline-gnu-perl systemd-sysv
systemd is a system and service manager for Linux. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic.
7. Configure machine-id and divert
dbus-uuidgen > /etc/machine-id
ln -fs /etc/machine-id /var/lib/dbus/machine-id
The /etc/machine-id file contains the unique machine ID of the local system that is set during installation or boot. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase ID. When decoded from hexadecimal, this corresponds to a 16-byte/128-bit value. This ID may not be all zeros.
dpkg-divert --local --rename --add /sbin/initctl
ln -s /bin/true /sbin/initctl
dpkg-divert is the utility used to set up and update the list of diversions.
8. Upgrade packages
apt-get -y upgrade
9. Install packages needed for Live System
apt-get install -y \
sudo \
ubuntu-standard \
casper \
lupin-casper \
discover \
laptop-detect \
os-prober \
network-manager \
resolvconf \
net-tools \
wireless-tools \
wpagui \
locales \
grub-common \
grub-gfxpayload-lists \
grub-pc \
grub-pc-bin \
grub2-common
apt-get install -y --no-install-recommends linux-generic
10. Graphical installer
apt-get install -y \
ubiquity \
ubiquity-casper \
ubiquity-frontend-gtk \
ubiquity-slideshow-ubuntu \
ubiquity-ubuntu-artwork
The next steps will appear, as a result of the packages that will be installed from the previous step, this will happen without anything having to be informed or executed.
1. Configure keyboard
2. Console setup
11. Install window manager
apt-get install -y \
plymouth-theme-ubuntu-logo \
ubuntu-gnome-desktop \
ubuntu-gnome-wallpapers
12. Install useful applications
apt-get install -y \
clamav-daemon \
terminator \
apt-transport-https \
curl \
vim \
nano \
less
13. Install Visual Studio Code (optional)
14. Download and install the key
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /etc/apt/trusted.gpg.d/
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list
rm microsoft.gpg
15. Then update the package cache and install the package using
apt-get update
apt-get install -y code
16. Install Google Chrome (optional)
17. Download and install the key
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
18. Then update the package cache and install the package using
apt-get update
apt-get install google-chrome-stable
19. Install Java JDK 8 (optional)
apt-get install -y \
openjdk-8-jdk \
openjdk-8-jre
20. Remove unused applications (optional)
apt-get purge -y \
transmission-gtk \
transmission-common \
gnome-mahjongg \
gnome-mines \
gnome-sudoku \
aisleriot \
hitori
21. Remove unused packages
apt-get autoremove -y
22. Reconfigure packages
23. Generate locales
dpkg-reconfigure locales
1. Select locales
2. Select default locale
24. Reconfigure resolvconf
dpkg-reconfigure resolvconf
1. Confirm changes
25. Configure network-manager
cat <<EOF > /etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false
EOF
26. Reconfigure network-manager
dpkg-reconfigure network-manager
27. Cleanup the chroot environment
28. If you installed software, be sure to run
truncate -s 0 /etc/machine-id
29. Remove the diversion
rm /sbin/initctl
dpkg-divert --rename --remove /sbin/initctl
30. Clean up
apt-get clean
rm -rf /tmp/* ~/.bash_history
umount /proc
umount /sys
umount /dev/pts
export HISTSIZE=0
exit
Unbind mount points
sudo umount $HOME/live-ubuntu-from-scratch/chroot/dev
sudo umount $HOME/live-ubuntu-from-scratch/chroot/run
Create the CD image directory and populate it
We are now back in our build environment after setting up our live system and will continue creating files necessary to generate the ISO.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create directories
mkdir -p image/{casper,isolinux,install}
3. Copy kernel images
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
4. Copy memtest86+ binary (BIOS)
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
5. Download and extract memtest86 binary (UEFI)
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
GRUB menu configuration
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create base point access file for grub
touch image/ubuntu
3. Create image/isolinux/grub.cfg
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "Try Ubuntu FS without installing" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "Install Ubuntu FS" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
Create manifest
Next we create a file filesystem.manifest to specify each package and it's version that is installed on the live system. We create another file filesystem.manifest-desktop which specifies which files will be installed on the target system. Once the Ubiquity installer completes, it will remove packages specified in filesystem.manifest that are not listed in filesystem.manifest-desktop.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/casper/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/discover/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/laptop-detect/d' image/casper/filesystem.manifest-desktop
sudo sed -i '/os-prober/d' image/casper/filesystem.manifest-desktop
Compress the chroot
After everything has been installed and preconfigured in the chrooted environment, we need to generate an image of everything that was done by following the next steps in the build environment.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create squashfs
sudo mksquashfs chroot image/casper/filesystem.squashfs
Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K. Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.
3. Write the filesystem.size
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
Create diskdefines
README file often found on Linux LiveCD installer discs, such as an Ubuntu Linux installation CD; typically named “README.diskdefines” and may be referenced during installation.
1. Access build directory
cd $HOME/live-ubuntu-from-scratch
2. Create file image/README.diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME Ubuntu from scratch
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
Create ISO Image for a LiveCD (BIOS + UEFI)
1. Access image directory
cd $HOME/live-ubuntu-from-scratch/image
2. Create a grub UEFI image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
3. Create a FAT16 UEFI boot disk image containing the EFI bootloader
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
4. Create a grub BIOS image
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
5. Combine a bootable Grub cdboot.img
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
6. Generate md5sum.txt
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
7. Create iso from the image directory using the command-line
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
Alternative way, if previous one fails, create an Hybrid ISO
1. Create a ISOLINUX (syslinux) boot menu
cat <<EOF> isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 600
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Try Ubuntu FS
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper
LABEL linux
MENU LABEL Try Ubuntu FS (nomodeset)
MENU DEFAULT
KERNEL /casper/vmlinuz
APPEND initrd=/casper/initrd boot=casper nomodeset
EOF
2. Include syslinux bios modules
apt install -y syslinux-common && \
cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ && \
cp /usr/lib/syslinux/modules/bios/* isolinux/
3. Create iso from the image directory
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "Ubuntu from scratch" \
-output "../ubuntu-from-scratch.iso" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef EFI/boot/efiboot.img \
"$HOME/live-ubuntu-from-scratch/image"
Make a bootable USB image
It is simple and easy, using "dd"
sudo dd if=ubuntu-from-scratch.iso of=<device> status=progress oflag=sync
Summary
This completes the process of creating a live Ubuntu installer from scratch. The generated ISO may be tested in a virtual machine such as VirtualBox or written to media and booted from a standard PC.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use GitHub for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE - see the LICENSE file for details
A partir de ceci, je voudrais realiser ma propre distribution avec les logiciels suivant: R, Rstudio, Jupyterlab, Ugene, ImageJ, VLC, biopython, zotero, libreoffice, firefox et peut etre d'autres logiciels par la suite.
|
4248a93ad55b250f45cfcaac1f0d6eab
|
{
"intermediate": 0.46675726771354675,
"beginner": 0.330436110496521,
"expert": 0.20280657708644867
}
|
13,306
|
i want to use free API keys chatpgt that can build that write me book only fron title and story book will save on file text or something , script must be very powerfull and smart and vip and more Distinctive additions
|
175635fddddec11e6fa03320a96d4a45
|
{
"intermediate": 0.7232259511947632,
"beginner": 0.09411388635635376,
"expert": 0.18266014754772186
}
|
13,307
|
Выведите тип данных для типа топлива автомобиля.
|
879d66046e7693beabe6656d6529bf9b
|
{
"intermediate": 0.2924138307571411,
"beginner": 0.26765143871307373,
"expert": 0.43993470072746277
}
|
13,308
|
https://itnext.io/how-to-create-a-custom-ubuntu-live-from-scratch-dd3b3f213f81
|
62d3efe1b65e006255c6522e4c3e54d9
|
{
"intermediate": 0.3158339560031891,
"beginner": 0.3236549198627472,
"expert": 0.3605111539363861
}
|
13,309
|
#!/bin/bash
set -e # exit on error
set -o pipefail # exit on pipeline error
set -u # treat unset variable as error
#set -x
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
CMD=(setup_host debootstrap run_chroot build_iso)
DATE=`TZ="UTC" date +"%y%m%d-%H%M%S"`
function help() {
# if $1 is set, use $1 as headline message in help()
if [ -z ${1+x} ]; then
echo -e "This script builds a bootable ubuntu ISO image"
echo -e
else
echo -e $1
echo
fi
echo -e "Supported commands : ${CMD[*]}"
echo -e
echo -e "Syntax: $0 [start_cmd] [-] [end_cmd]"
echo -e "\trun from start_cmd to end_end"
echo -e "\tif start_cmd is omitted, start from first command"
echo -e "\tif end_cmd is omitted, end with last command"
echo -e "\tenter single cmd to run the specific command"
echo -e "\tenter '-' as only argument to run all commands"
echo -e
exit 0
}
function find_index() {
local ret;
local i;
for ((i=0; i<${#CMD[*]}; i++)); do
if [ "${CMD[i]}" == "$1" ]; then
index=$i;
return;
fi
done
help "Command not found : $1"
}
function chroot_enter_setup() {
sudo mount --bind /dev chroot/dev
sudo mount --bind /run chroot/run
sudo chroot chroot mount none -t proc /proc
sudo chroot chroot mount none -t sysfs /sys
sudo chroot chroot mount none -t devpts /dev/pts
}
function chroot_exit_teardown() {
sudo chroot chroot umount /proc
sudo chroot chroot umount /sys
sudo chroot chroot umount /dev/pts
sudo umount chroot/dev
sudo umount chroot/run
}
function check_host() {
local os_ver
os_ver=`lsb_release -i | grep -E "(Ubuntu|Debian)"`
if [[ -z "$os_ver" ]]; then
echo "WARNING : OS is not Debian or Ubuntu and is untested"
fi
if [ $(id -u) -eq 0 ]; then
echo "This script should not be run as 'root'"
exit 1
fi
}
# Load configuration values from file
function load_config() {
if [[ -f "$SCRIPT_DIR/config.sh" ]]; then
. "$SCRIPT_DIR/config.sh"
elif [[ -f "$SCRIPT_DIR/default_config.sh" ]]; then
. "$SCRIPT_DIR/default_config.sh"
else
>&2 echo "Unable to find default config file $SCRIPT_DIR/default_config.sh, aborting."
exit 1
fi
}
# Verify that necessary configuration values are set and they are valid
function check_config() {
local expected_config_version
expected_config_version="0.4"
if [[ "$CONFIG_FILE_VERSION" != "$expected_config_version" ]]; then
>&2 echo "Invalid or old config version $CONFIG_FILE_VERSION, expected $expected_config_version. Please update your configuration file from the default."
exit 1
fi
}
function setup_host() {
echo "=====> running setup_host ..."
sudo apt update
sudo apt install -y binutils debootstrap squashfs-tools xorriso grub-pc-bin grub-efi-amd64-bin mtools dosfstools unzip
sudo mkdir -p chroot
}
function debootstrap() {
echo "=====> running debootstrap ... will take a couple of minutes ..."
sudo debootstrap --arch=amd64 --variant=minbase $TARGET_UBUNTU_VERSION chroot $TARGET_UBUNTU_MIRROR
}
function run_chroot() {
echo "=====> running run_chroot ..."
chroot_enter_setup
# Setup build scripts in chroot environment
sudo ln -f $SCRIPT_DIR/chroot_build.sh chroot/root/chroot_build.sh
sudo ln -f $SCRIPT_DIR/default_config.sh chroot/root/default_config.sh
if [[ -f "$SCRIPT_DIR/config.sh" ]]; then
sudo ln -f $SCRIPT_DIR/config.sh chroot/root/config.sh
fi
# Launch into chroot environment to build install image.
sudo chroot chroot /usr/bin/env DEBIAN_FRONTEND=${DEBIAN_FRONTEND:-readline} /root/chroot_build.sh -
# Cleanup after image changes
sudo rm -f chroot/root/chroot_build.sh
sudo rm -f chroot/root/default_config.sh
if [[ -f "chroot/root/config.sh" ]]; then
sudo rm -f chroot/root/config.sh
fi
chroot_exit_teardown
}
function build_iso() {
echo "=====> running build_iso ..."
rm -rf image
mkdir -p image/{casper,isolinux,install}
# copy kernel files
sudo cp chroot/boot/vmlinuz-**-**-generic image/casper/vmlinuz
sudo cp chroot/boot/initrd.img-**-**-generic image/casper/initrd
# memtest86
sudo cp chroot/boot/memtest86+.bin image/install/memtest86+
wget --progress=dot https://www.memtest86.com/downloads/memtest86-usb.zip -O image/install/memtest86-usb.zip
unzip -p image/install/memtest86-usb.zip memtest86-usb.img > image/install/memtest86
rm -f image/install/memtest86-usb.zip
# grub
touch image/ubuntu
cat <<EOF > image/isolinux/grub.cfg
search --set=root --file /ubuntu
insmod all_video
set default="0"
set timeout=30
menuentry "${GRUB_LIVEBOOT_LABEL}" {
linux /casper/vmlinuz boot=casper nopersistent toram quiet splash ---
initrd /casper/initrd
}
menuentry "${GRUB_INSTALL_LABEL}" {
linux /casper/vmlinuz boot=casper only-ubiquity quiet splash ---
initrd /casper/initrd
}
menuentry "Check disc for defects" {
linux /casper/vmlinuz boot=casper integrity-check quiet splash ---
initrd /casper/initrd
}
menuentry "Test memory Memtest86+ (BIOS)" {
linux16 /install/memtest86+
}
menuentry "Test memory Memtest86 (UEFI, long load time)" {
insmod part_gpt
insmod search_fs_uuid
insmod chain
loopback loop /install/memtest86
chainloader (loop,gpt1)/efi/boot/BOOTX64.efi
}
EOF
# generate manifest
sudo chroot chroot dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee image/casper/filesystem.manifest
sudo cp -v image/casper/filesystem.manifest image/casper/filesystem.manifest-desktop
for pkg in $TARGET_PACKAGE_REMOVE; do
sudo sed -i "/$pkg/d" image/casper/filesystem.manifest-desktop
done
# compress rootfs
sudo mksquashfs chroot image/casper/filesystem.squashfs \
-noappend -no-duplicates -no-recovery \
-wildcards \
-e "var/cache/apt/archives/*" \
-e "root/*" \
-e "root/.*" \
-e "tmp/*" \
-e "tmp/.*" \
-e "swapfile"
printf $(sudo du -sx --block-size=1 chroot | cut -f1) > image/casper/filesystem.size
# create diskdefines
cat <<EOF > image/README.diskdefines
#define DISKNAME ${GRUB_LIVEBOOT_LABEL}
#define TYPE binary
#define TYPEbinary 1
#define ARCH amd64
#define ARCHamd64 1
#define DISKNUM 1
#define DISKNUM1 1
#define TOTALNUM 0
#define TOTALNUM0 1
EOF
# create iso image
pushd $SCRIPT_DIR/image
grub-mkstandalone \
--format=x86_64-efi \
--output=isolinux/bootx64.efi \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
(
cd isolinux && \
dd if=/dev/zero of=efiboot.img bs=1M count=10 && \
sudo mkfs.vfat efiboot.img && \
LC_CTYPE=C mmd -i efiboot.img efi efi/boot && \
LC_CTYPE=C mcopy -i efiboot.img ./bootx64.efi ::efi/boot/
)
grub-mkstandalone \
--format=i386-pc \
--output=isolinux/core.img \
--install-modules="linux16 linux normal iso9660 biosdisk memdisk search tar ls" \
--modules="linux16 linux normal iso9660 biosdisk search" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=isolinux/grub.cfg"
cat /usr/lib/grub/i386-pc/cdboot.img isolinux/core.img > isolinux/bios.img
sudo /bin/bash -c "(find . -type f -print0 | xargs -0 md5sum | grep -v -e 'md5sum.txt' -e 'bios.img' -e 'efiboot.img' > md5sum.txt)"
sudo xorriso \
-as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid "$TARGET_NAME" \
-eltorito-boot boot/grub/bios.img \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog boot/grub/boot.cat \
--grub2-boot-info \
--grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img \
-eltorito-alt-boot \
-e EFI/efiboot.img \
-no-emul-boot \
-append_partition 2 0xef isolinux/efiboot.img \
-output "$SCRIPT_DIR/$TARGET_NAME.iso" \
-m "isolinux/efiboot.img" \
-m "isolinux/bios.img" \
-graft-points \
"/EFI/efiboot.img=isolinux/efiboot.img" \
"/boot/grub/bios.img=isolinux/bios.img" \
"."
popd
}
# ============= main ================
# we always stay in $SCRIPT_DIR
cd $SCRIPT_DIR
load_config
check_config
check_host
# check number of args
if [[ $# == 0 || $# > 3 ]]; then help; fi
# loop through args
dash_flag=false
start_index=0
end_index=${#CMD[*]}
for ii in "$@";
do
if [[ $ii == "-" ]]; then
dash_flag=true
continue
fi
find_index $ii
if [[ $dash_flag == false ]]; then
start_index=$index
else
end_index=$(($index+1))
fi
done
if [[ $dash_flag == false ]]; then
end_index=$(($start_index + 1))
fi
#loop through the commands
for ((ii=$start_index; ii<$end_index; ii++)); do
${CMD[ii]}
done
echo "$0 - Initial build is done!"
|
15f32371afb95659598247885f167ebd
|
{
"intermediate": 0.3513975143432617,
"beginner": 0.4800179898738861,
"expert": 0.16858452558517456
}
|
13,310
|
how run GPT-3 on colab google
|
77ecdafe5938b91ef107b14969200805
|
{
"intermediate": 0.4177221953868866,
"beginner": 0.13747726380825043,
"expert": 0.4448004961013794
}
|
13,311
|
Hi friends
|
4b7ef5cfc3980f2e01e69cea370cbd8f
|
{
"intermediate": 0.344413697719574,
"beginner": 0.26093894243240356,
"expert": 0.3946473002433777
}
|
13,312
|
what is your version
|
25e5a6e7849c8d7b380438fd65030f59
|
{
"intermediate": 0.34521982073783875,
"beginner": 0.29315704107284546,
"expert": 0.3616231083869934
}
|
13,313
|
what is this and how was it made. its a minecraft mod
package bozoware.impl.module.visual;
import bozoware.base.event.EventConsumer;
import bozoware.base.event.EventListener;
import bozoware.base.module.Module;
import bozoware.base.module.ModuleCategory;
import bozoware.base.module.ModuleData;
import bozoware.base.util.Wrapper;
import bozoware.base.util.visual.RenderUtil;
import bozoware.impl.event.visual.EventRender3D;
import bozoware.impl.property.EnumProperty;
import bozoware.impl.property.ValueProperty;
import net.minecraft.client.renderer.GlStateManager;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.Cylinder;
import org.lwjgl.util.glu.GLU;
@ModuleData(moduleName = "ChinaHat", moduleCategory = ModuleCategory.VISUAL)
public class ChinaHat extends Module {
@EventListener
EventConsumer<EventRender3D> onEventRender3D;
private final EnumProperty<taiwanModes> mode = new EnumProperty<>("Mode", taiwanModes.Normal, this);
private final ValueProperty<Float> Width = new ValueProperty<>("Width", 0.86F, 0F, 1F, this);
private final ValueProperty<Float> Height = new ValueProperty<>("Height", 0.30F, 0F, 1F, this);
private final ValueProperty<Integer> Sides = new ValueProperty<>("Sides", 30, 3, 90, this);
// private final ColorProperty color = new ColorProperty("Color", new Color(0xffff0000), this);
private final ValueProperty<Integer> alpha = new ValueProperty<>("Opacity", 100, 0, 255, this);
public ChinaHat() {
onEventRender3D = (EventRender3D -> {
GlStateManager.pushMatrix();
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GlStateManager.enableBlend();
GlStateManager.disableTexture2D();
GlStateManager.disableDepth();
GlStateManager.depthMask(false);
RenderUtil.setColorWithAlpha(HUD.getInstance().bozoColor, alpha.getPropertyValue());
GlStateManager.disableCull();
switch(mode.getPropertyValue()){
case Normal:
if(!mc.thePlayer.isSneaking()){
GlStateManager.translate(0f, mc.thePlayer.height+0.4F, 0f);
} else{
GlStateManager.translate(0f, mc.thePlayer.height + 0.1F, 0f);
}
GlStateManager.rotate(90f, 1f, 0f, 0f);
GL11.glRotatef(Wrapper.getPlayer().rotationYaw, 0f, 0f, 1f);
//cone
Cylinder cylinder = new Cylinder();
cylinder.setDrawStyle(GLU.GLU_FILL);
cylinder.draw(0.0f, Width.getPropertyValue(), Height.getPropertyValue(), Sides.getPropertyValue(), 1);
//ring
GlStateManager.rotate(-90f, 1f, 0f, 0f);
GlStateManager.translate(0f, Wrapper.getPlayer().height-2-Height.getPropertyValue()+0.2, 0f);
RenderUtil.drawLinesAroundPlayer(Wrapper.getPlayer(), Width.getPropertyValue(), EventRender3D.partialTicks, Sides.getPropertyValue(), 3.0F*2F, 0xff111111);
RenderUtil.drawLinesAroundPlayer(Wrapper.getPlayer(), Width.getPropertyValue(), EventRender3D.partialTicks, Sides.getPropertyValue(), 3.0F, HUD.getInstance().bozoColor);
GlStateManager.translate(0f, Height.getPropertyValue(), 0f);
GlStateManager.rotate(90f, 1f, 0f, 0f);
break;
case WTF:
if(!mc.thePlayer.isSneaking()){
GlStateManager.translate(0f, mc.thePlayer.height+0.4F, 0f);
} else{
GlStateManager.translate(0f, mc.thePlayer.height + 0.1F, 0f);
}
GlStateManager.rotate(0f, 1f, 0f, 0f);
double offset = 1.03;
for(int i=0;i<50;i++){
GlStateManager.translate(0f, 0.01, 0f);
RenderUtil.drawLinesAroundPlayer(Wrapper.getPlayer(), Width.getPropertyValue() / offset, EventRender3D.partialTicks, Sides.getPropertyValue(), 3.0F*2F, 0xff111111);
RenderUtil.drawLinesAroundPlayer(Wrapper.getPlayer(), Width.getPropertyValue() / offset, EventRender3D.partialTicks, Sides.getPropertyValue(), 3.0F, HUD.getInstance().bozoColor);
offset = offset + 0.06;
}
break;
}
GlStateManager.disableColorMaterial();
GlStateManager.enableTexture2D();
GlStateManager.enableDepth();
GlStateManager.depthMask(true);
GlStateManager.enableCull();
GlStateManager.disableBlend();
GlStateManager.color(1, 1, 1, 255);
GlStateManager.popMatrix();
});
}
private enum taiwanModes {
Normal,
WTF
}
}
|
e67bbd4ad54ad8fcd5d60576f93db7ac
|
{
"intermediate": 0.5290966629981995,
"beginner": 0.3417595624923706,
"expert": 0.12914372980594635
}
|
13,314
|
I want a python program that uses google api to download a mail given mail id
|
1fcb5734f5770c6f45b750ebf69b7a16
|
{
"intermediate": 0.6411292552947998,
"beginner": 0.1068849116563797,
"expert": 0.2519857883453369
}
|
13,315
|
please make me a futuristic-looking portfolio website in html and css, for all images put a smoothly color-changing border around them and call the images "placeholder.png", do this for every image on the website, i also want the website to have multiple pages to it, including an about me page, an experience page, and a contact me page, for the buttons where you go from page to page i want it to smoothly hover up a little bit with a glowing smooth shadow at the bottom, also make sure to add a place all the way deep down at the end of the pages that let me add stuff like @copyright, instagram, etc, ty! html and css in different messages please!
|
4cb831e71ab6a2263d89d007aa9916b9
|
{
"intermediate": 0.3681025505065918,
"beginner": 0.30045396089553833,
"expert": 0.3314434289932251
}
|
13,316
|
Install packages we need in the build system required by our scripts.
sudo apt-get install \
binutils \
debootstrap \
squashfs-tools \
xorriso \
grub-pc-bin \
grub-efi-amd64-bin \
mtools
mkdir $HOME/live-ubuntu-from-scratch
|
e7359fcbbb6f43bd87a9fa201330bd56
|
{
"intermediate": 0.48073717951774597,
"beginner": 0.25047269463539124,
"expert": 0.26879018545150757
}
|
13,317
|
in python, how to get number from one string
|
d6a5fc6ce134177a28dfd5aa45a68570
|
{
"intermediate": 0.4194672405719757,
"beginner": 0.3068455755710602,
"expert": 0.2736871540546417
}
|
13,318
|
can you write an example of a c# SpeechToText script using mlnet and Mozilla DeepSpeech
|
e6805d5b821b40d45c8f266d2a144ab9
|
{
"intermediate": 0.4753466248512268,
"beginner": 0.13085906207561493,
"expert": 0.3937942683696747
}
|
13,319
|
Test
|
874267e7fac8231b4c371978f451970a
|
{
"intermediate": 0.34329941868782043,
"beginner": 0.33079785108566284,
"expert": 0.32590270042419434
}
|
13,320
|
Create a website scraping app
|
bb2c1d68af0626aba464331f506b67ae
|
{
"intermediate": 0.3324451148509979,
"beginner": 0.31218430399894714,
"expert": 0.3553706109523773
}
|
13,321
|
In this code, I have added a spinner that should show when an api call is made, but it's not being shown
<div class="overlay-menu">
<div class="spinner-container">
<div class="spinner"></div>
</div>
</div>
<div class="container-fluid">
<div class="row align-items-stretch">
<div class="col-xl-5">
<div class="handle-position">
<div class="logo-section">
<img src="imgs/logo.png" alt="" />
</div>
</div>
</div>
<div class="col-xl-7 pr-0">
<div class="info-section position-relative">
<div class="auth-form">
<div class="w-100">
<h2>Sign Up for an account</h2>
<p class="text-base">
Already have an account? <a href="index.html">Sign In</a>
</p>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item" role="presentation">
<button
class="nav-link active"
id="details-tab"
data-bs-toggle="tab"
data-bs-target="#details-tab-pane"
type="button"
role="tab"
aria-controls="details-tab-pane"
aria-selected="true"
>
User details
</button>
</li>
<li class="nav-item" role="presentation">
<button
class="nav-link"
id="account-tab"
data-bs-toggle="tab"
data-bs-target="#account-tab-pane"
type="button"
role="tab"
aria-controls="account-tab-pane"
aria-selected="false"
>
Account Details
</button>
</li>
<li class="nav-item" role="presentation">
<button
class="nav-link"
id="address-tab"
data-bs-toggle="tab"
data-bs-target="#address-tab-pane"
type="button"
role="tab"
aria-controls="address-tab-pane"
aria-selected="false"
>
Address Details
</button>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div
class="tab-pane fade show active"
id="details-tab-pane"
role="tabpanel"
aria-labelledby="details-tab"
tabindex="0"
>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="fullname">Full name</label>
<input
id="fullname"
type="text"
class="form-control"
placeholder="Enter your full name"
value=""
/>
<div class="invalid-feedback">
Please enter your full name
</div>
</div>
<div class="form-group">
<label for="email"> Email Address</label>
<input
id="email"
type="email"
class="form-control"
placeholder="Enter your email"
value=""
/>
<div class="invalid-feedback">
Please enter your email
</div>
</div>
<div class="form-group">
<label for="phone-number">Phone Number </label>
<input
id="phone-number"
type="text"
class="form-control"
placeholder="Enter your Phone Number"
value=""
/>
<div class="invalid-feedback">
Please enter your Phone Number
</div>
</div>
<div class="text-center">
<button
class="btn btn-primary my-3"
onclick= "switchToNextTab()"
type="button"
>
Next
</button>
</div>
</form>
</div>
<div
class="tab-pane fade"
id="account-tab-pane"
role="tabpanel"
aria-labelledby="account-tab"
tabindex="0"
>
<form class="needs-validation" novalidate>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="account-type"
>Select account type</label
>
<select
id="account-type"
class="form-select form-control1"
>
<option selected disabled value="">
Select the account type
</option>
<option value="local">Local</option>
<option value="government">Government</option>
<option value="international">
International
</option>
</select>
<div class="invalid-feedback">
Please select a valid state.
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<label for="cr-no">CR Number</label>
<div class="form-group position-relative">
<input
id="cr-no"
type="text"
class="form-control"
placeholder="CR Number"
value=""
/>
<button
id="search-btn"
class="search-btn btn btn-primary my-0"
type="button"
>
<img
src="imgs/search-icon-default.svg"
style="width: 14px"
/>
</button>
</div>
</div>
</div>
<div class="row">
<label for="company-ar" class="fw-bold mb-3"
>Company Name</label
>
<div class="col-md-6">
<div class="form-group">
<input
id="company-ar"
type="text"
class="form-control"
placeholder="Company name in Arabic"
value=""
/>
<div class="invalid-feedback">
Please enter company name in Arabic
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input
id="company-en"
type="text"
class="form-control"
placeholder="Company name in English"
value=""
/>
<div class="invalid-feedback">
Please enter company name in English
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="tax-no">Tax Number</label>
<input
id="tax-no"
type="text"
class="form-control"
placeholder="Enter Tax Number"
value=""
/>
<div class="invalid-feedback">
Please enter Tax Number
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="business-no"
>Business Phone Number</label
>
<input
id="business-no"
type="text"
class="form-control"
placeholder="Enter Business Phone Number"
value=""
/>
<div class="invalid-feedback">
Please enter Business Phone Number
</div>
</div>
</div>
</div>
<div class="text-center">
<button
class="btn btn-primary my-3"
onclick= "switchToNextTab()"
type="button"
>
Next
</button>
</div>
</form>
</div>
<div
class="tab-pane fade"
id="address-tab-pane"
role="tabpanel"
aria-labelledby="address-tab"
tabindex="0"
>
<form class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="additional-no"
>Additional Number</label
>
<input
id="additional-no"
type="text"
class="form-control"
placeholder="Enter Additional Number"
value=""
/>
<div class="invalid-feedback">
Please enter Additional number
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="unit-no">Unit Number</label>
<input
id="unit-no"
type="text"
class="form-control"
placeholder="Enter Unit Number"
value=""
/>
<div class="invalid-feedback">
Please enter Unit Number
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="building-no">Building Number</label>
<input
id="building-no"
type="text"
class="form-control"
placeholder="Enter Building Number"
value=""
required
/>
<div class="invalid-feedback">
Please enter Building number
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="zip">Zip Code</label>
<input
id="zip"
type="text"
class="form-control"
placeholder="Enter Zip Code"
value=""
/>
<div class="invalid-feedback">
Please enter Zip Code
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="address">Short Address</label>
<input
id="address"
type="text"
class="form-control"
placeholder="Enter Short Address"
value=""
/>
<div class="invalid-feedback">
Please enter Short Address
</div>
</div>
</div>
</div>
<div class="text-center">
<button
class="btn btn-primary my-3"
onclick="SignUp()"
type="button"
>
Sign Up
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--wrapper-->
<div id="footer">
<div class="container-content footer-container"></div>
<!--container content-->
</div>
<!--footer-->
<script src="js/jquery-3.6.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js?v=1.1"></script>
<!-- <script src="js/Soap.js"></script> -->
<script>
function switchToNextTab() {
// Get references to the button and tabs
var detailsTab = document.getElementById("details-tab");
var accountTab = document.getElementById("account-tab");
var addressTab = document.getElementById("address-tab");
var detailsTabPane = document.getElementById("details-tab-pane");
var accountTabPane = document.getElementById("account-tab-pane");
var addressTabPane = document.getElementById("address-tab-pane");
// Switch to the next tab
if (detailsTab.classList.contains("active")) {
detailsTab.classList.remove("active");
accountTab.classList.add("active");
detailsTabPane.classList.remove("show", "active");
accountTabPane.classList.add("show", "active");
} else if (accountTab.classList.contains("active")) {
accountTab.classList.remove("active");
addressTab.classList.add("active");
accountTabPane.classList.remove("show", "active");
addressTabPane.classList.add("show", "active");
}
}
</script>
<script>
const overlayMenu = document.querySelector('.overlay-menu');
const spinner = document.querySelector('.spinner');
// Function to show the loading spinner
function showLoadingSpinner() {
overlayMenu.style.display = 'block';
spinner.style.display = 'block';
console.log("Show");
}
// Function to hide the loading spinner
function hideLoadingSpinner() {
overlayMenu.style.display = 'none';
spinner.style.display = 'none';
console.log("Hide");
}
// Get references to the input field and search button
var nameInput = document.getElementById("fullname");
var emailInput = document.getElementById("email");
var phoneInput = document.getElementById("phone-number");
var accountTypeInput = document.getElementById("account-type");
var businessPhoneInput = document.getElementById("business-no");
var taxNumberInput = document.getElementById("tax-no");
var crNumberInput = document.getElementById("cr-no");
var searchButton = document.getElementById("search-btn");
var companyEnInput = document.getElementById("company-en");
var companyArInput = document.getElementById("company-ar");
var additionalNoInput = document.getElementById("additional-no");
var unitNoInput = document.getElementById("unit-no");
var zipInput = document.getElementById("zip");
var buildingNumber = document.getElementById("building-no");
var shortAddress = document.getElementById("address");
var CustomerNo;
async function SignUp() {
var accountData = {
Name: nameInput.value,
Email: emailInput.value,
PhoneNumber: phoneInput.value,
CustomerNo: CustomerNo,
AccountType: accountTypeInput.value,
CRNumber: crNumberInput.value,
CompanyArabicName: companyArInput.value,
CompanyEnglishName: companyEnInput.value,
TaxNumber: taxNumberInput.value,
BuildingNumber: buildingNumber.value,
BusinessPhoneNumber: businessPhoneInput.value,
AdditionalNumber: additionalNoInput.value,
UnitNumber: unitNoInput.value,
ZipCode: zipInput.value,
ShortAddress: shortAddress.value
};
var url = "http://10.14.12.3:81/api/account"; // Replace with your API endpoint
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(accountData)
});
if (response.ok) {
// Request succeeded
window.location.href = 'success-page.html';
} else {
// Request failed
console.error("Failed to create account. Error:", response.status);
}
} catch (error) {
console.error("Failed to create account. Error:", error);
}
}
function getNationalAddress() {
var postalCode = zipInput.value;
var additionalNumber = additionalNoInput.value;
var buildingNum = buildingNumber.value;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://10.14.12.3:81/api/GetWasel/GetNationalAddressByXYZ?postalCode=" + postalCode +
"&additionalNumber=" + additionalNumber +
"&buildingNumber=" + buildingNum);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var addressResponse = JSON.parse(xhr.responseText);
shortAddress.value = addressResponse;
// Handle the address response and update the corresponding input fields
} else {
// Handle the error cases
console.error("API request failed with status code " + xhr.status);
}
}
hideLoadingSpinner();
};
xhr.send();
}
// Add click event listener to the search button
searchButton.addEventListener("click", function () {
// Get the CR number from the input field
var crNumber = crNumberInput.value;
showLoadingSpinner();
// Make an AJAX request to the API endpoint
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://10.14.12.3:81/api/GetWasel/GetCustomerDetails?crNumber=" + crNumber);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
companyEnInput.value = response.CustomerNameinEng;
companyArInput.value = response.CustomerNameinAR;
additionalNoInput.value = response.AdditionalNumber;
unitNoInput.value = response.UnitNo;
zipInput.value = response.ZipCode;
buildingNumber.value=response.BuildingNo;
CustomerNo = response.CustomerId;
getNationalAddress();
// Process the response data
} else {
// Handle the error case
console.error("API request failed with status code " + xhr.status);
}
}
};
xhr.send();
});
</script>
</body>
</html>
|
79c6fe97ac11b34e466d9ce6b812408c
|
{
"intermediate": 0.44458889961242676,
"beginner": 0.4356231093406677,
"expert": 0.11978793889284134
}
|
13,322
|
how to use pyopengl tk
|
fbea6df948f19509612c41fa883ad90d
|
{
"intermediate": 0.3672809898853302,
"beginner": 0.2997930347919464,
"expert": 0.332925945520401
}
|
13,323
|
python selenium how can I hot switch from headed to headless browser without closing the open tabs
|
0f6746e6a434a4a7526aafed9266c282
|
{
"intermediate": 0.3927243947982788,
"beginner": 0.20523002743721008,
"expert": 0.4020456373691559
}
|
13,324
|
import requests
from bs4 import BeautifulSoup
from flask import Flask, Response
from feedgen.feed import FeedGenerator
from datetime import datetime
import pytz
import re
import time
# Function to process comments and their replies
def process_comment(comment, work_title, fg):
# Extract relevant information from the comment
comment_id = comment.get("id")
if comment_id is None:
return # Skip comments without an id
comment_author_elem = comment.find("a", href=True)
comment_author = comment_author_elem.text.strip() if comment_author_elem is not None else "Unknown"
comment_text_elem = comment.find("blockquote", class_="userstuff")
if comment_text_elem is not None:
comment_text = comment_text_elem.text.strip()
else:
return # Skip comments without any text
# Extract chapter information if available
chapter_info_elem = comment.find("span", class_="parent")
chapter_info = chapter_info_elem.text.strip() if chapter_info_elem is not None else "Unknown Chapter"
# Extract date and time information
date_elem = comment.find("span", class_="posted").find("abbr", class_="day")
day = date_elem.text.strip() if date_elem is not None else "Unknown"
date_elem = comment.find("span", class_="posted").find("span", class_="date")
date = date_elem.text.strip() if date_elem is not None else "Unknown"
date_elem = comment.find("span", class_="posted").find("abbr", class_="month")
month = date_elem.text.strip() if date_elem is not None else "Unknown"
date_elem = comment.find("span", class_="posted").find("span", class_="year")
year = date_elem.text.strip() if date_elem is not None else "Unknown"
date_elem = comment.find("span", class_="posted").find("span", class_="time")
time_str = date_elem.text.strip() if date_elem is not None else "Unknown"
# Create an RSS entry for the comment with chapter information and date
entry = fg.add_entry()
entry.title(f"{work_title} - [{chapter_info}] Comment by {comment_author}")
entry.description(comment_text)
# Generate URL for the comment
comment_url = f"https://archiveofourown.org/comments/{comment_id.split('_')[1]}" if '_' in comment_id else ""
# Set the GUID value for the comment entry
entry.guid(comment_url, permalink=True)
# Combine date and time strings into a single string
datetime_str = f"{day} {date} {month} {year} {time_str}"
# Parse the datetime string into a timezone-aware datetime object
dt = datetime.strptime(datetime_str, "%a %d %b %Y %I:%M%p")
# Convert the datetime object to UTC if it's not already in UTC
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
dt = pytz.utc.localize(dt)
else:
dt = dt.astimezone(pytz.utc)
formatted_dt = dt.strftime("%a, %d %b %Y %H:%M:%S %z")
entry.pubDate(formatted_dt)
# Function to handle rate limiting (429 errors)
def handle_rate_limiting(response):
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 1))
print(f"Rate limited. Retrying after {retry_after} seconds...")
time.sleep(retry_after)
raise Exception("Rate limited. Stopping the script.")
# Function to extract title and work ID with retry
def extract_title_with_retry(url):
max_retries = 3
retries = 0
while retries < max_retries:
response = requests.get(url)
handle_rate_limiting(response)
soup = BeautifulSoup(response.content, "html.parser")
title_elem = soup.find("title")
if title_elem:
return title_elem.text.strip()
retries += 1
print(f"Title extraction failed. Retrying... Attempt #{retries}")
return "Unknown" # Return default value if extraction fails after maximum retries
# Flask app initialization
app = Flask(__name__)
@app.route("/<work_id>")
def generate_rss_feed(work_id):
# Check if the work ID is in the correct format (8-digit number)
if not re.match(r"^\d{8}$", work_id):
return "Invalid work ID format. Please enter an 8-digit number."
# Create the feed generator object
fg = FeedGenerator()
# Rest of the code remains the same
base_url = f"https://archiveofourown.org/works/{work_id}"
urls = [base_url]
# Process each URL and create RSS feed
for url in urls:
# Extract the title and work ID from the work page URL
work_url = url + "?view_adult=true&view_full_work=true"
work_title = extract_title_with_retry(work_url)
# Set the title of the RSS feed
fg.title(f"{work_title} - AO3 Comments RSS Feed")
# Rest of the code remains the same
fg.link(href=base_url, rel='alternate')
fg.description('RSS feed for AO3 comments')
# Construct the base URL for comments
base_url = url + "/comments?page={}&show_comments=true&view_full_work=true&view_adult=true#comments"
# Extract the title and work ID from the work page URL
work_url = url + "?view_adult=true&view_full_work=true"
work_title = extract_title_with_retry(work_url)
work_id = work_url.split("/")[-1].split("?")[0] # Remove the query parameters from the work ID
# Start with the first page
page = 1
has_comments = True
last_page = 1 # Initialize last_page outside the loop
while has_comments:
# Construct the URL for the current page
url = base_url.format(page)
# Send a GET request to the URL
response = requests.get(url)
# Check if rate limited and handle it
handle_rate_limiting(response)
# Create a BeautifulSoup object from the response content
soup = BeautifulSoup(response.content, "html.parser")
# Find the comments section on the page
comments_section = soup.find("div", id="comments_placeholder")
# Check if comments section exists
if comments_section is not None:
# Find all individual comments
comments = comments_section.find_all("li")
# Loop through each comment and process it
for comment in comments:
process_comment(comment, work_title, fg) # Pass the respective fg instance
# Find the pagination links
pagination = comments_section.find("ol", class_="pagination actions")
# Check if there are multiple pages of comments
if pagination is not None:
# Find the last page number
last_page = int(pagination.find_all("li")[-2].text)
# Update page after processing the current page
page += 1
else:
print("Comments section not found on the current page.")
break # Stop the script if comments section not found
# Update has_comments based on the presence of more pages
has_comments = page <= last_page
# Generate RSS feed XML
response = Response(fg.rss_str(pretty=True), mimetype='application/xml')
return response
if __name__ == '__main__':
app.run(port=4329)
this is what i want the script to do: want it to extract the number of comments the fic has and saves it as a variable to compare to, so that only when it increases, does it do a full scan of all the comment pages. the current fic i'm looking at has 621 comments currently. if that number goes up, i want the script to scrape all the comments. if it stays the same, no scraping should happen. every time the rss is refreshed (every 5 minutes is the current setting in my rss reader), the only requests being sent out are for the title extraction and comment count extraction to compare to the number to the previous run. if it increases, only THEN scrape all the comments
the comment count scraping should be done on the same function and the same url that's used to extract the title. please post the full modified code with nothing cut.
here's the structure for the the part that shows the number of comments:
<dl class="stats"><div class="published"><dt class="published">Published:</dt><dd class="published">2023-01-16</dd></div><div class="status"><dt class="status">Updated:</dt><dd class="status">2023-06-22</dd></div><div class="words"><dt class="words">Words:</dt><dd class="words" data-ao3e-original="57,715">57 715</dd></div><div class="AO3E"><dt class="reading-time AO3E">Reading time:</dt><dd class="reading-time AO3E">4 hours, 48 mins</dd></div><div class="AO3E"><dt class="finish-at AO3E">Finish reading at:</dt><dd class="finish-at AO3E"><span title="Using current time of 13:25. Click to update." aria-label="18:13. Using current time of 13:25. Click to update." tabindex="0" role="button"><span class="time">18:13</span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="AO3E--icon" role="img"><path fill="currentColor" d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"></path></svg></span></dd></div><div class="chapters"><dt class="chapters">Chapters:</dt><dd class="chapters" data-ao3e-original="18/?">18/?</dd></div><div class="comments"><dt class="comments">Comments:</dt><dd class="comments" data-ao3e-original="621">621</dd></div><div class="kudos"><dt class="kudos">Kudos:</dt><dd class="kudos" data-ao3e-original="1,055">1 055</dd></div><div class="bookmarks"><dt class="bookmarks">Bookmarks:</dt><dd class="bookmarks"><a href="/works/44300110/bookmarks" data-ao3e-original="103">103</a></dd></div><div class="hits"><dt class="hits">Hits:</dt><dd class="hits" data-ao3e-original="19,841">19 841</dd></div><div class="AO3E"><dt class="kudos-hits-ratio AO3E">Kudos/Hits:</dt><dd class="kudos-hits-ratio AO3E">5.32%</dd></div></dl>
|
c1af774a6d7de9f7a83bace8ade11be9
|
{
"intermediate": 0.38312411308288574,
"beginner": 0.4365726411342621,
"expert": 0.18030323088169098
}
|
13,325
|
hey
|
b641b0eb374bc8b43af546e04c780a52
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
13,326
|
python selenium how can I hot switch from headed to headless browser without closing the open tabs
|
a35239bf0699dcb5bda09a4973375c93
|
{
"intermediate": 0.3927243947982788,
"beginner": 0.20523002743721008,
"expert": 0.4020456373691559
}
|
13,327
|
give me open-source repos that use Stable Diffusion v1
|
a542cb248711944f1c4f1f077faedb3b
|
{
"intermediate": 0.4527965784072876,
"beginner": 0.16198121011257172,
"expert": 0.38522225618362427
}
|
13,328
|
pyopengltk supports the modern opengl?
|
124f1d76ad21df93432b8bd8cda8f705
|
{
"intermediate": 0.41187649965286255,
"beginner": 0.1691422462463379,
"expert": 0.41898128390312195
}
|
13,329
|
怎么:Find others who are using TypeScript at [typescriptlang] (https://www.typescriptlang.org/community/)
|
cc8a317127ccc148944a65f594c11045
|
{
"intermediate": 0.2581506371498108,
"beginner": 0.4663713872432709,
"expert": 0.2754780054092407
}
|
13,330
|
A template JavaScript web app using Express.js module
|
36339c7bf1cc36ae7b52d4b8a7f5d762
|
{
"intermediate": 0.3857908844947815,
"beginner": 0.3680257499217987,
"expert": 0.246183380484581
}
|
13,331
|
Build android calculator app
|
720437f03c524fed773b237a544d6ff3
|
{
"intermediate": 0.40405064821243286,
"beginner": 0.327188640832901,
"expert": 0.2687607407569885
}
|
13,332
|
how to pass some data to subprocess called by python and also call some method in subprocess
|
6fd606290fe3cb0ff03ea56df8ce7c9e
|
{
"intermediate": 0.6496864557266235,
"beginner": 0.10517632961273193,
"expert": 0.24513722956180573
}
|
13,333
|
4096
|
fe22ee4ba87a676eba97663c0b397d1d
|
{
"intermediate": 0.34254738688468933,
"beginner": 0.2909409701824188,
"expert": 0.3665117025375366
}
|
13,334
|
can you write me a excel vbr formula to calcualte the pressure at the top of a gas bubble while circulating out a gas influx during a kick
|
80af498e3a15cd3778eaae203c40fdf3
|
{
"intermediate": 0.19949626922607422,
"beginner": 0.1060032919049263,
"expert": 0.6945004463195801
}
|
13,335
|
what does this code do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int size;
int start;
int end;
int status;
struct node *next;
};
struct node *head = NULL;
void insert(int size)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->size = size;
temp->start = 0;
temp->end = size - 1;
temp->status = 0;
temp->next = NULL;
if (head == NULL)
{
head = temp;
}
else
{
struct node *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
}
}
void display()
{
struct node *p = head;
while (p != NULL)
{
printf("%d\t%d\t%d\t%d\n", p->size, p->start, p->end, p->status);
p = p->next;
}
}
void best_fit(int size)
{
struct node *p = head;
int min = 9999;
struct node *temp = NULL;
while (p != NULL)
{
if (p->status == 0 && p->size >= size)
{
if (p->size < min)
{
min = p->size;
temp = p;
}
}
p = p->next;
}
if (temp != NULL)
{
temp->status = 1;
printf("Allocated memory of size %d at %d\n", size, temp->start);
}
else
{
printf("No memory available\n");
}
}
int main()
{
int n, size;
printf("Enter the number of memory blocks: ");
scanf("%d", &n);
printf("Enter the size of each block: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &size);
insert(size);
}
printf("Enter the size of the process: ");
scanf("%d", &size);
best_fit(size);
display();
return 0;
}
|
862ad956613189a712eb1c29f6ab3ec7
|
{
"intermediate": 0.416855126619339,
"beginner": 0.43581274151802063,
"expert": 0.147332102060318
}
|
13,336
|
create wordpress theme boilerplate code. pls provide code
|
fb9e3be299a64dc845a3808eb8ffefa4
|
{
"intermediate": 0.34002622961997986,
"beginner": 0.39401373267173767,
"expert": 0.2659600079059601
}
|
13,337
|
#include <WiFi.h>
#include <HTTPClient.h>
#include "ArduinoJson.h"
#include "SD.h"
#include "SPI.h"
// Pin configuration
#define SD_CS_PIN 5
#define SPEAKER_PIN 25
// SD card file
File audioFile;
bool azan = false;
// User WiFi details
const char* WIFI_SSID = "ooredooBA902F"; // Replace with your Wi-Fi network name (SSID)
const char* WIFI_PASSWORD = "P@SWRD4WIFIEZ123"; // Replace with your Wi-Fi network password
const char* dataTimingsFajr;
const char* dataTimingsSunrise;
const char* dataTimingsDhuhr;
const char* dataTimingsAsr;
const char* dataTimingsMaghrib;
const char* dataTimingsIsha;
// User defined location details
String USER_LATITUDE = "33.88";
String USER_LONGITUDE = "10.08";
// Will be updated with JSON
String CURRENT_TIMEZONE = "Africa/Tunis";
String CURRENT_DATE = "01-01-2000";
String CURRENT_TIME = "00:00:00";
unsigned int CURRENT_MINUTE;
unsigned int CURRENT_HOUR;
// Function prototypes
void initializeSDCard();
void openAudioFile();
void playAudioFile();
void connectToWiFi();
void getTimezone();
void getPrayerTimes();
void checkAzan();
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200); // Start serial communication at 115200 baud
while (!Serial) {
// wait for serial port to connect.
}
// Initialize SD card
initializeSDCard();
// Open audio file
openAudioFile();
// Set speaker pin as output
pinMode(SPEAKER_PIN, OUTPUT);
digitalWrite(SPEAKER_PIN, LOW);
Serial.println(" * Prayer Time * "); // Print once
connectToWiFi();
}
void loop() {
if (azan == false) {
if (WiFi.status() == WL_CONNECTED) {
getTimezone();
getPrayerTimes();
checkTime();
checkAzan();
delay(10000); // Wait for 10 seconds before sending the next request
} else {
Serial.println("Lost connection!");
delay(300);
}
} else {
playAudioFile();
// When End of audio file reached
// azan = false
// Re-connect to wifi
// Take a look at playAudioFile()
}
}
void connectToWiFi() {
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wi-Fi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void getTimezone() {
WiFiClient client;
HTTPClient http;
// Make request to the URL
String url = "http://worldtimeapi.org/api/timezone/" + CURRENT_TIMEZONE;
http.begin(client, url);
// Send the GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
StaticJsonDocument<768> doc;
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
const char* datetime = doc["datetime"]; // "2023-06-22T12:22:35.847564+01:00"
// Extract date
char dateBuffer[11];
strncpy(dateBuffer, datetime, 10);
dateBuffer[10] = '\0';
CURRENT_DATE = dateBuffer;
// Extract time
char timeBuffer[6]; // Buffer to hold time component (HH:MM + null terminator)
strncpy(timeBuffer, datetime + 11, 5);
timeBuffer[5] = '\0'; // Add null terminator
CURRENT_TIME = timeBuffer;
// Extract hour
char hourBuffer[3]; // Buffer to hold hour component (HH + null terminator)
strncpy(hourBuffer, datetime + 11, 2);
hourBuffer[2] = '\0'; // Add null terminator
CURRENT_HOUR = (int)hourBuffer;
// Extract minute
char minuteBuffer[3]; // Buffer to hold minute component (MM + null terminator)
strncpy(minuteBuffer, datetime + 14, 2);
minuteBuffer[2] = '\0'; // Add null terminator
CURRENT_MINUTE = (int)minuteBuffer;
JsonObject dataMeta = doc["meta"];
const char* dataMetaTimezone = dataMeta["timezone"];
CURRENT_TIMEZONE = dataMetaTimezone;
Serial.println();
Serial.println(CURRENT_DATE);
Serial.println(CURRENT_TIME);
// Close HTTP connection
http.end();
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
}
void getPrayerTimes() {
WiFiClient client;
HTTPClient http;
// Make request to the URL
String url = "http://api.aladhan.com/v1/timings/" + CURRENT_DATE + "?latitude=" + USER_LATITUDE + "&longitude=" + USER_LONGITUDE + "&method=1";
http.begin(client, url);
// Send the GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
DynamicJsonDocument doc(3072);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
int code = doc["code"];
const char* status = doc["status"];
JsonObject data = doc["data"];
JsonObject dataTimings = data["timings"];
//dataTimingsFajr = dataTimings["Fajr"];
dataTimingsSunrise = dataTimings["Sunrise"];
dataTimingsDhuhr = dataTimings["Dhuhr"];
dataTimingsAsr = dataTimings["Asr"];
dataTimingsMaghrib = dataTimings["Maghrib"];
dataTimingsIsha = dataTimings["Isha"];
dataTimingsFajr = "07:49";
JsonObject dataMeta = data["meta"];
const char* dataMetaTimezone = dataMeta["timezone"];
CURRENT_TIMEZONE = dataMetaTimezone;
// Print prayer times for the current date and location (RAW data)
Serial.println();
Serial.print("Prayer ");
Serial.print("Time ");
Serial.println();
Serial.println("----------------");
Serial.print("Fajr ");
Serial.print(dataTimingsFajr);
Serial.println();
Serial.print("Sunrise ");
Serial.print(dataTimingsSunrise);
Serial.println();
Serial.print("Dhuhr ");
Serial.print(dataTimingsDhuhr);
Serial.println();
Serial.print("Asr ");
Serial.print(dataTimingsAsr);
Serial.println();
Serial.print("Maghrib ");
Serial.print(dataTimingsMaghrib);
Serial.println();
Serial.print("Isha ");
Serial.print(dataTimingsIsha);
Serial.println();
// Close HTTP connection
http.end();
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
}
// Initialize the SD card
void initializeSDCard() {
if (!SD.begin(SD_CS_PIN)) {
Serial.println("SD card initialization failed!");
while (1)
;
}
}
// Open the audio file
void openAudioFile() {
audioFile = SD.open("/path/to/audio_8.wav");
if (!audioFile) {
Serial.println("Error opening audio file!");
while (1)
;
}
}
// Play audio data from the file
void playAudioFile() {
int audioSample = audioFile.read();
if (audioSample == -1) {
// End of audio file reached
Serial.println("End of audio file reached!");
audioFile.close();
// get back to normal mode
azan = false;
connectToWiFi();
}
// Repeat outputing sound for better quality
for (int i = 0; i < 10; i++) {
// Write audio sample to speaker pin
dacWrite(SPEAKER_PIN, audioSample);
}
}
void checkAzan() {
if (CURRENT_TIME == dataTimingsFajr || CURRENT_TIME == dataTimingsDhuhr || CURRENT_TIME == dataTimingsAsr || CURRENT_TIME == dataTimingsMaghrib || CURRENT_TIME == dataTimingsIsha) {
// Play audio data from SD card file
azan = true;
Serial.println("Azan is playing");
} else {
digitalWrite(SPEAKER_PIN, LOW);
}
}
void extractHourMinute(const char* prayerTime, char* hourBuffer, char* minuteBuffer) {
strncpy(minuteBuffer, prayerTime + 3, 2);
minuteBuffer[2] = '\0';
strncpy(hourBuffer, prayerTime + 0, 2);
hourBuffer[2] = '\0';
}
void checkTime() {
char fajrHourBuffer[3];
char fajrMinuteBuffer[3];
extractHourMinute(dataTimingsFajr, fajrHourBuffer, fajrMinuteBuffer);
int fajrHour = atoi(fajrHourBuffer);
int fajrMinute = atoi(fajrMinuteBuffer);
Serial.println();
Serial.print("Fajr hour: ");
Serial.print(fajrHour);
Serial.print(" minute: ");
Serial.println(fajrMinute);
char dhuhrHourBuffer[3];
char dhuhrMinuteBuffer[3];
extractHourMinute(dataTimingsDhuhr, dhuhrHourBuffer, dhuhrMinuteBuffer);
int dhuhrHour = atoi(dhuhrHourBuffer);
int dhuhrMinute = atoi(dhuhrMinuteBuffer);
Serial.print("Dhuhr hour: ");
Serial.print(dhuhrHour);
Serial.print(" minute: ");
Serial.println(dhuhrMinute);
char asrHourBuffer[3];
char asrMinuteBuffer[3];
extractHourMinute(dataTimingsAsr, asrHourBuffer, asrMinuteBuffer);
int asrHour = atoi(asrHourBuffer);
int asrMinute = atoi(asrMinuteBuffer);
Serial.print("Asr hour: ");
Serial.print(asrHour);
Serial.print(" minute: ");
Serial.println(asrMinute);
char maghribHourBuffer[3];
char maghribMinuteBuffer[3];
extractHourMinute(dataTimingsMaghrib, maghribHourBuffer, maghribMinuteBuffer);
int maghribHour = atoi(maghribHourBuffer);
int maghribMinute = atoi(maghribMinuteBuffer);
Serial.print("Maghrib hour: ");
Serial.print(maghribHour);
Serial.print(" minute: ");
Serial.println(maghribMinute);
char ishaHourBuffer[3];
char ishaMinuteBuffer[3];
extractHourMinute(dataTimingsIsha, ishaHourBuffer, ishaMinuteBuffer);
int ishaHour = atoi(ishaHourBuffer);
int ishaMinute = atoi(ishaMinuteBuffer);
Serial.print("Isha hour: ");
Serial.print(ishaHour);
Serial.print(" minute: ");
Serial.println(ishaMinute);
}
Serial print a 30-minute count-down before prayer times and a 30-minute count-up after prayer times. don't use delay() you can use mills() or you can check time from the code.
display a -00:30 to -00:00 and +00:00 to +00:30
You need to know the closet prayer time (next prayer time (count up) and then (current time = prayer time) display (count up)).
|
aea2adc97c751e81aa190eaa80284f82
|
{
"intermediate": 0.3180607259273529,
"beginner": 0.5182512402534485,
"expert": 0.1636880338191986
}
|
13,338
|
#include <WiFi.h>
#include <HTTPClient.h>
#include "ArduinoJson.h"
#include "SD.h"
#include "SPI.h"
// Pin configuration
#define SD_CS_PIN 5
#define SPEAKER_PIN 25
// SD card file
File audioFile;
bool azan = false;
// User WiFi details
const char* WIFI_SSID = "ooredooBA902F"; // Replace with your Wi-Fi network name (SSID)
const char* WIFI_PASSWORD = "P@SWRD4WIFIEZ123"; // Replace with your Wi-Fi network password
const char* dataTimingsFajr;
const char* dataTimingsSunrise;
const char* dataTimingsDhuhr;
const char* dataTimingsAsr;
const char* dataTimingsMaghrib;
const char* dataTimingsIsha;
// User defined location details
String USER_LATITUDE = "33.88";
String USER_LONGITUDE = "10.08";
// Will be updated with JSON
String CURRENT_TIMEZONE = "Africa/Tunis";
String CURRENT_DATE = "01-01-2000";
String CURRENT_TIME = "00:00:00";
unsigned int CURRENT_MINUTE;
unsigned int CURRENT_HOUR;
// Function prototypes
void initializeSDCard();
void openAudioFile();
void playAudioFile();
void connectToWiFi();
void getTimezone();
void getPrayerTimes();
void checkAzan();
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200); // Start serial communication at 115200 baud
while (!Serial) {
// wait for serial port to connect.
}
// Initialize SD card
initializeSDCard();
// Open audio file
openAudioFile();
// Set speaker pin as output
pinMode(SPEAKER_PIN, OUTPUT);
digitalWrite(SPEAKER_PIN, LOW);
Serial.println(" * Prayer Time * "); // Print once
connectToWiFi();
}
void loop() {
if (azan == false) {
if (WiFi.status() == WL_CONNECTED) {
getTimezone();
getPrayerTimes();
checkTime();
checkAzan();
delay(10000); // Wait for 10 seconds before sending the next request
} else {
Serial.println("Lost connection!");
delay(300);
}
} else {
playAudioFile();
// When End of audio file reached
// azan = false
// Re-connect to wifi
// Take a look at playAudioFile()
}
}
void connectToWiFi() {
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wi-Fi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void getTimezone() {
WiFiClient client;
HTTPClient http;
// Make request to the URL
String url = "http://worldtimeapi.org/api/timezone/" + CURRENT_TIMEZONE;
http.begin(client, url);
// Send the GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
StaticJsonDocument<768> doc;
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
const char* datetime = doc["datetime"]; // "2023-06-22T12:22:35.847564+01:00"
// Extract date
char dateBuffer[11];
strncpy(dateBuffer, datetime, 10);
dateBuffer[10] = '\0';
CURRENT_DATE = dateBuffer;
// Extract time
char timeBuffer[6]; // Buffer to hold time component (HH:MM + null terminator)
strncpy(timeBuffer, datetime + 11, 5);
timeBuffer[5] = '\0'; // Add null terminator
CURRENT_TIME = timeBuffer;
// Extract hour
char hourBuffer[3]; // Buffer to hold hour component (HH + null terminator)
strncpy(hourBuffer, datetime + 11, 2);
hourBuffer[2] = '\0'; // Add null terminator
CURRENT_HOUR = (int)hourBuffer;
// Extract minute
char minuteBuffer[3]; // Buffer to hold minute component (MM + null terminator)
strncpy(minuteBuffer, datetime + 14, 2);
minuteBuffer[2] = '\0'; // Add null terminator
CURRENT_MINUTE = (int)minuteBuffer;
JsonObject dataMeta = doc["meta"];
const char* dataMetaTimezone = dataMeta["timezone"];
CURRENT_TIMEZONE = dataMetaTimezone;
Serial.println();
Serial.println(CURRENT_DATE);
Serial.println(CURRENT_TIME);
// Close HTTP connection
http.end();
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
}
void getPrayerTimes() {
WiFiClient client;
HTTPClient http;
// Make request to the URL
String url = "http://api.aladhan.com/v1/timings/" + CURRENT_DATE + "?latitude=" + USER_LATITUDE + "&longitude=" + USER_LONGITUDE + "&method=1";
http.begin(client, url);
// Send the GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
DynamicJsonDocument doc(3072);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
int code = doc["code"];
const char* status = doc["status"];
JsonObject data = doc["data"];
JsonObject dataTimings = data["timings"];
//dataTimingsFajr = dataTimings["Fajr"];
dataTimingsSunrise = dataTimings["Sunrise"];
dataTimingsDhuhr = dataTimings["Dhuhr"];
dataTimingsAsr = dataTimings["Asr"];
dataTimingsMaghrib = dataTimings["Maghrib"];
dataTimingsIsha = dataTimings["Isha"];
dataTimingsFajr = "07:49";
JsonObject dataMeta = data["meta"];
const char* dataMetaTimezone = dataMeta["timezone"];
CURRENT_TIMEZONE = dataMetaTimezone;
// Print prayer times for the current date and location (RAW data)
Serial.println();
Serial.print("Prayer ");
Serial.print("Time ");
Serial.println();
Serial.println("----------------");
Serial.print("Fajr ");
Serial.print(dataTimingsFajr);
Serial.println();
Serial.print("Sunrise ");
Serial.print(dataTimingsSunrise);
Serial.println();
Serial.print("Dhuhr ");
Serial.print(dataTimingsDhuhr);
Serial.println();
Serial.print("Asr ");
Serial.print(dataTimingsAsr);
Serial.println();
Serial.print("Maghrib ");
Serial.print(dataTimingsMaghrib);
Serial.println();
Serial.print("Isha ");
Serial.print(dataTimingsIsha);
Serial.println();
// Close HTTP connection
http.end();
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
}
// Initialize the SD card
void initializeSDCard() {
if (!SD.begin(SD_CS_PIN)) {
Serial.println("SD card initialization failed!");
while (1)
;
}
}
// Open the audio file
void openAudioFile() {
audioFile = SD.open("/path/to/audio_8.wav");
if (!audioFile) {
Serial.println("Error opening audio file!");
while (1)
;
}
}
// Play audio data from the file
void playAudioFile() {
int audioSample = audioFile.read();
if (audioSample == -1) {
// End of audio file reached
Serial.println("End of audio file reached!");
audioFile.close();
// get back to normal mode
azan = false;
connectToWiFi();
}
// Repeat outputing sound for better quality
for (int i = 0; i < 10; i++) {
// Write audio sample to speaker pin
dacWrite(SPEAKER_PIN, audioSample);
}
}
void checkAzan() {
if (CURRENT_TIME == dataTimingsFajr || CURRENT_TIME == dataTimingsDhuhr || CURRENT_TIME == dataTimingsAsr || CURRENT_TIME == dataTimingsMaghrib || CURRENT_TIME == dataTimingsIsha) {
// Play audio data from SD card file
azan = true;
Serial.println("Azan is playing");
} else {
digitalWrite(SPEAKER_PIN, LOW);
}
}
void extractHourMinute(const char* prayerTime, char* hourBuffer, char* minuteBuffer) {
strncpy(minuteBuffer, prayerTime + 3, 2);
minuteBuffer[2] = '\0';
strncpy(hourBuffer, prayerTime + 0, 2);
hourBuffer[2] = '\0';
}
void checkTime() {
char fajrHourBuffer[3];
char fajrMinuteBuffer[3];
extractHourMinute(dataTimingsFajr, fajrHourBuffer, fajrMinuteBuffer);
int fajrHour = atoi(fajrHourBuffer);
int fajrMinute = atoi(fajrMinuteBuffer);
Serial.println();
Serial.print("Fajr hour: ");
Serial.print(fajrHour);
Serial.print(" minute: ");
Serial.println(fajrMinute);
char dhuhrHourBuffer[3];
char dhuhrMinuteBuffer[3];
extractHourMinute(dataTimingsDhuhr, dhuhrHourBuffer, dhuhrMinuteBuffer);
int dhuhrHour = atoi(dhuhrHourBuffer);
int dhuhrMinute = atoi(dhuhrMinuteBuffer);
Serial.print("Dhuhr hour: ");
Serial.print(dhuhrHour);
Serial.print(" minute: ");
Serial.println(dhuhrMinute);
char asrHourBuffer[3];
char asrMinuteBuffer[3];
extractHourMinute(dataTimingsAsr, asrHourBuffer, asrMinuteBuffer);
int asrHour = atoi(asrHourBuffer);
int asrMinute = atoi(asrMinuteBuffer);
Serial.print("Asr hour: ");
Serial.print(asrHour);
Serial.print(" minute: ");
Serial.println(asrMinute);
char maghribHourBuffer[3];
char maghribMinuteBuffer[3];
extractHourMinute(dataTimingsMaghrib, maghribHourBuffer, maghribMinuteBuffer);
int maghribHour = atoi(maghribHourBuffer);
int maghribMinute = atoi(maghribMinuteBuffer);
Serial.print("Maghrib hour: ");
Serial.print(maghribHour);
Serial.print(" minute: ");
Serial.println(maghribMinute);
char ishaHourBuffer[3];
char ishaMinuteBuffer[3];
extractHourMinute(dataTimingsIsha, ishaHourBuffer, ishaMinuteBuffer);
int ishaHour = atoi(ishaHourBuffer);
int ishaMinute = atoi(ishaMinuteBuffer);
Serial.print("Isha hour: ");
Serial.print(ishaHour);
Serial.print(" minute: ");
Serial.println(ishaMinute);
}
Serial print a 30-minute count-down before prayer times and a 30-minute count-up after prayer times. don't use delay() you can use mills() or you can check time from the code.
display a -00:30 to -00:00 and +00:00 to +00:30
You need to know the closet prayer time (next prayer time (count up) and then (current time = prayer time) display (count up)).
|
8764159084a28b9f6458e99857b4d2d0
|
{
"intermediate": 0.3180607259273529,
"beginner": 0.5182512402534485,
"expert": 0.1636880338191986
}
|
13,339
|
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
type TokenType int
const (
Number TokenType = iota
Operator
Variable
Function
ArgumentSeparator
)
type Token struct {
Type TokenType
Value string
}
var variables = make(map[string]float64)
func parseExpression(expression string) ([]Token, error) {
tokens := []Token{}
var buffer strings.Builder
for _, ch := range expression {
if ch == ' ' {
continue
}
if strings.ContainsRune("+-/^()!", ch) {
if buffer.Len() > 0 {
token, err := createToken(buffer.String())
if err != nil {
return nil, err
}
tokens = append(tokens, token)
buffer.Reset()
}
tokens = append(tokens, Token{Type: Operator, Value: string(ch)})
} else if ch == ',' {
if buffer.Len() > 0 {
token, err := createToken(buffer.String())
if err != nil {
return nil, err
}
tokens = append(tokens, token)
buffer.Reset()
}
tokens = append(tokens, Token{Type: ArgumentSeparator, Value: string(ch)})
} else {
buffer.WriteRune(ch)
}
}
if buffer.Len() > 0 {
token, err := createToken(buffer.String())
if err != nil {
return nil, err
}
tokens = append(tokens, token)
}
return tokens, nil
}
func createToken(value string) (Token, error) {
if _, err := strconv.ParseFloat(value, 64); err == nil {
return Token{Type: Number, Value: value}, nil
}
if _, ok := variables[value]; ok {
return Token{Type: Variable, Value: value}, nil
}
if value == "root" {
return Token{Type: Function, Value: value}, nil
}
return Token{}, fmt.Errorf("неизвестный токен: %s", value)
}
func compute(tokens []Token) (float64, []Token, error) {
if len(tokens) == 0 {
return 0, tokens, fmt.Errorf("ожидался токен")
}
token := tokens[0]
tokens = tokens[1:]
switch token.Type {
case Number:
value, _ := strconv.ParseFloat(token.Value, 64)
return value, tokens, nil
case Variable:
value := variables[token.Value]
return value, tokens, nil
case Operator:
left, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
tokens = leftoverTokens
if token.Value == "+" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left + right, leftoverTokens, nil
} else if token.Value == "-" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left - right, leftoverTokens, nil
} else if token.Value == "" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left * right, leftoverTokens, nil
} else if token.Value == "/" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left / right, leftoverTokens, nil
} else if token.Value == "^" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return math.Pow(left, right), leftoverTokens, nil
} else if token.Value == ")" {
return left, tokens, fmt.Errorf("неожиданная закрывающая скобка")
}
case Function:
if token.Value == "root" {
if len(tokens) == 0 {
return 0, tokens, fmt.Errorf("ожидался аргумент функции")
}
base, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
if len(leftoverTokens) == 0 || leftoverTokens[0].Type != ArgumentSeparator {
return 0, tokens, fmt.Errorf("ожидался разделитель аргументов ','")
}
expTokens := leftoverTokens[1:]
exponent, leftoverTokens, err := compute(expTokens)
if err != nil {
return 0, tokens, err
}
return math.Pow(base, 1/exponent), leftoverTokens, nil
}
case ArgumentSeparator:
return 0, tokens, fmt.Errorf("неожиданный разделитель аргументов ','")
}
return 0, tokens, fmt.Errorf("необработанный токен: %v", token)
}
func main() {
variables["x"] = 5
expression := "root(27, 3)"
// expression := "3 ^ 2 + root(27, 3) + x"
tokens, err := parseExpression(expression)
if err != nil {
fmt.Printf("Ошибка при парсинге выражения: %v\n", err)
return
}
result, _, err := compute(tokens)
if err != nil {
fmt.Printf("Ошибка при вычислении выражения: %v\n", err)
} else {
fmt.Printf("Результат вычисления: %.2f\n", result)
}
}
Написал простенький интерпретатор.
при выполнении появляется ошибка Ошибка при вычислении выражения: необработанный токен: {1 (}
|
6a108a8fff0f437ce4a7f2f5a9cde304
|
{
"intermediate": 0.25681284070014954,
"beginner": 0.4968041777610779,
"expert": 0.2463829219341278
}
|
13,340
|
I ran this code in R: PCA_model <- attr(PCA_params, "model")
object.size.my_data
PCs <- predict(PCA_model, newdata = my_data) # returns all PCs
my_data$WADD = WADD_C
PCs_df$WADD = data.frame(PCs)
PCs_df$WADD =WADD_C
PCs_df = PCs_df[, c('WADD', 'PC1', 'PC2')]
# 1) Split to train and test. use 0.7 for the train data
set.seed(1234)
splits <- initial_split(PCs_df, prop = 0.7)
my_data.train_PCA <- training(splits)
my_data.test_PCA <- testing(splits)
rec <- recipe(~., data = my_data.train_PCA) |>
step_range(all_numeric_predictors())
tg <- expand.grid(alpha = c(seq(0, 1, length.out = 25)),
lambda = exp(seq(-6, -1, length.out = 40)))
tc <- trainControl(method = "cv", number = 5)
##################### net
mod.elastic_PCA <- train(
x = rec,
data = my_data.train_PCA,
method = "glmnet",
tuneGrid = tg,
trControl = tc
) and got this note: Error in `object[[name, exact = TRUE]]`:
! Can't extract column with `name`.
✖ Subscript `name` must be size 1, not 0.
Run `rlang::last_trace()` to see where the error occurred.
|
1b26f6bc33e89b7fb27336bff67a917b
|
{
"intermediate": 0.4746512770652771,
"beginner": 0.18424201011657715,
"expert": 0.34110674262046814
}
|
13,341
|
Write Love2D code that shuffles all subvariables of a variable
|
18ba60576ce2099f6ee9a3a4f4f058a9
|
{
"intermediate": 0.28306251764297485,
"beginner": 0.25001394748687744,
"expert": 0.4669235646724701
}
|
13,342
|
How do I shuffle Love2D lists formatted like this? example = { one=1 two=2 }
|
8065e473449b6d319e2511f69f2216dc
|
{
"intermediate": 0.41091546416282654,
"beginner": 0.16250866651535034,
"expert": 0.4265759289264679
}
|
13,343
|
How do I shuffle Love2D lists formatted like this, but make the function work for any list like that one? example = { one=1 two=2 }
|
d8cdcf32b23a8cd6b3d32ffb18cde48c
|
{
"intermediate": 0.41187891364097595,
"beginner": 0.30018165707588196,
"expert": 0.2879394292831421
}
|
13,344
|
How would I shuffle only the asterisked part of this list in Love2D, but make it work for any of this kind? example = {one=*1* two=*2*}
|
fbb1a462a120ff28f1bcdad653972e85
|
{
"intermediate": 0.32650071382522583,
"beginner": 0.41052472591400146,
"expert": 0.2629745304584503
}
|
13,345
|
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
type TokenType int
const (
Number TokenType = iota
Operator
Variable
Function
ArgumentSeparator
)
type Token struct {
Type TokenType
Value string
}
var variables = make(map[string]float64)
func parseExpression(expression string) ([]Token, error) {
tokens := []Token{}
var buffer strings.Builder
for _, ch := range expression {
if ch == ' ' {
continue
}
if strings.ContainsRune("+-/^()!", ch) {
if buffer.Len() > 0 {
token, err := createToken(buffer.String())
if err != nil {
return nil, err
}
tokens = append(tokens, token)
buffer.Reset()
}
tokens = append(tokens, Token{Type: Operator, Value: string(ch)})
} else if ch == ',' {
if buffer.Len() > 0 {
token, err := createToken(buffer.String())
if err != nil {
return nil, err
}
tokens = append(tokens, token)
buffer.Reset()
}
tokens = append(tokens, Token{Type: ArgumentSeparator, Value: string(ch)})
} else {
buffer.WriteRune(ch)
}
}
if buffer.Len() > 0 {
token, err := createToken(buffer.String())
if err != nil {
return nil, err
}
tokens = append(tokens, token)
}
return tokens, nil
}
func createToken(value string) (Token, error) {
if _, err := strconv.ParseFloat(value, 64); err == nil {
return Token{Type: Number, Value: value}, nil
}
if _, ok := variables[value]; ok {
return Token{Type: Variable, Value: value}, nil
}
if value == "root" {
return Token{Type: Function, Value: value}, nil
}
return Token{}, fmt.Errorf("неизвестный токен: %s", value)
}
func compute(tokens []Token) (float64, []Token, error) {
if len(tokens) == 0 {
return 0, tokens, fmt.Errorf("ожидался токен")
}
token := tokens[0]
tokens = tokens[1:]
switch token.Type {
case Number:
value, _ := strconv.ParseFloat(token.Value, 64)
return value, tokens, nil
case Variable:
value := variables[token.Value]
return value, tokens, nil
case Operator:
left, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
tokens = leftoverTokens
if token.Value == "(" {
value, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
if len(leftoverTokens) == 0 || leftoverTokens[0].Value != ")" {
return 0, tokens, fmt.Errorf("ожидалась закрывающая скобка")
}
tokens = leftoverTokens[1:]
return value, tokens, nil
}
if token.Value == "+" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left + right, leftoverTokens, nil
} else if token.Value == "-" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left - right, leftoverTokens, nil
} else if token.Value == "" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left * right, leftoverTokens, nil
} else if token.Value == "/" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return left / right, leftoverTokens, nil
} else if token.Value == "^" {
right, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
return math.Pow(left, right), leftoverTokens, nil
} else if token.Value == ")" {
return left, tokens, fmt.Errorf("неожиданная закрывающая скобка")
}
case Function:
if token.Value == "root" {
if len(tokens) == 0 {
return 0, tokens, fmt.Errorf("ожидался аргумент функции")
}
if tokens[0].Value != "(" {
return 0, tokens, fmt.Errorf("ожидалась открывающая скобка")
}
tokens = tokens[1:]
base, leftoverTokens, err := compute(tokens)
if err != nil {
return 0, tokens, err
}
if len(leftoverTokens) == 0 || leftoverTokens[0].Type != ArgumentSeparator {
return 0, tokens, fmt.Errorf("ожидался разделитель аргументов ‘,’")
}
expTokens := leftoverTokens[1:]
exponent, leftoverTokens, err := compute(expTokens)
if err != nil {
return 0, tokens, err
}
if len(leftoverTokens) == 0 || leftoverTokens[0].Value != ")" {
return 0, tokens, fmt.Errorf("ожидалась закрывающая скобка")
}
tokens = leftoverTokens[1:]
return math.Pow(base, 1/exponent), tokens, nil
}
case ArgumentSeparator:
return 0, tokens, fmt.Errorf("неожиданный разделитель аргументов ','")
}
return 0, tokens, fmt.Errorf("необработанный токен: %v", token)
}
func main() {
variables["x"] = 5
expression := "3 ^ 2 + root(27, 3) + x"
tokens, err := parseExpression(expression)
if err != nil {
fmt.Printf("Ошибка при парсинге выражения: %v\n", err)
return
}
result, _, err := compute(tokens)
if err != nil {
fmt.Printf("Ошибка при вычислении выражения: %v\n", err)
} else {
fmt.Printf("Результат вычисления: %.4f\n", result)
}
}
При вычислении "3 ^ 2 + root(27, 3) + x" результат вычисления: 3.0000 что не корректно
|
aa3b6bb28393d1fea4cb6801d7ea46a3
|
{
"intermediate": 0.2739761769771576,
"beginner": 0.4960998594760895,
"expert": 0.22992396354675293
}
|
13,346
|
help me, access-list extenred cisco
|
966dd7138135644e29c9b52e8f6a4ce9
|
{
"intermediate": 0.4818866550922394,
"beginner": 0.22188755869865417,
"expert": 0.2962258458137512
}
|
13,347
|
Write code to find every boolean in Love2D and flip it so true is false and false is true
|
eb638369d5e8c653082e192c05eaf85f
|
{
"intermediate": 0.39495232701301575,
"beginner": 0.12076473236083984,
"expert": 0.484282910823822
}
|
13,348
|
Write code to find every boolean in Lua automatically and flip it so true is false and false is true
|
0ab3cd62254a643fc707ccdf7404f467
|
{
"intermediate": 0.4474315643310547,
"beginner": 0.17122994363307953,
"expert": 0.38133853673934937
}
|
13,349
|
write python code for seperating vocal and music from a audio file
|
ce98886c38acc66ac03887dd0bd7defc
|
{
"intermediate": 0.4232000708580017,
"beginner": 0.18578125536441803,
"expert": 0.39101868867874146
}
|
13,350
|
this is the question I was asked to doi in sql: Show the products, name and ID, which do not have reviews in the review table
Database: OrderDB
Table: Product
and this is the could I rought: select p.productid, title
from product p
right join review r
on r.productid = p.productid
where r.reviewid is null but it got me no resuls. this is the code from the book: select p.productid, p.title
from
review r
right join
product p
on p.productid=r.productid
where r.productid is null please tell me what did i do wrong?
|
9c0d357533644e39a557dd48ea77347e
|
{
"intermediate": 0.3815649449825287,
"beginner": 0.35546743869781494,
"expert": 0.26296767592430115
}
|
13,351
|
How to shuffle all strings loaded with getstring() in Love2D?
|
030bc703941c25a52dd4ab311a9725a8
|
{
"intermediate": 0.4941890239715576,
"beginner": 0.11394502967596054,
"expert": 0.39186596870422363
}
|
13,352
|
How to shuffle all strings that were loaded with getstring() in Love2D?
|
8406a7fe3ede04a5b2f523c69907e3a8
|
{
"intermediate": 0.47022745013237,
"beginner": 0.10965736955404282,
"expert": 0.4201151728630066
}
|
13,353
|
How do I shuffle all loaded textures in Love2D?
|
3f141389c1ce74afece436ffc478e8ed
|
{
"intermediate": 0.47033607959747314,
"beginner": 0.2693939507007599,
"expert": 0.26026999950408936
}
|
13,354
|
program to macy a copy of a selected range of page in pdf file using python
|
b6989a93995f44d38eda8724f22b3aeb
|
{
"intermediate": 0.35683849453926086,
"beginner": 0.19584961235523224,
"expert": 0.4473118484020233
}
|
13,355
|
Top 10 Blackpink song and MV
|
a2d25bb2d4c60de48b9c63f9c1e2b98e
|
{
"intermediate": 0.36145803332328796,
"beginner": 0.2909729778766632,
"expert": 0.34756895899772644
}
|
13,356
|
what does this program seem to do?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *block_size, *process_size, *flags, *allocation;
int m, n, i, j, temp, largest, count=0;
printf("\n Enter the number of memory blocks: ");
scanf("%d", &m);
block_size = (int *) malloc(m * sizeof(int));
for(i=0; i<m; i++)
{
printf("\n Enter the size of block %d: ", i+1);
scanf("%d", &block_size[i]);
}
printf("\n Enter the number of processes: ");
scanf("%d", &n);
process_size = (int *) malloc(n * sizeof(int));
flags = (int *) malloc(n * sizeof(int));
allocation = (int *) malloc(n * sizeof(int));
for(i=0; i<n; i++)
{
printf("\n Enter the size of process %d: ", i+1);
scanf("%d", &process_size[i]);
}
for(i=0; i<n; i++)
{
flags[i] = 0;
allocation[i] = -1;
}
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
if(flags[j] == 0 && block_size[j] >= process_size[i])
{
allocation[j] = i;
flags[j] = 1;
break;
}
}
}
for(i=0; i<n; i++)
{
if(allocation[i] != -1)
{
printf("\n Process %d is allocated to Block %d", i+1, allocation[i]+1);
}
else
{
printf("\n Process %d is not allocated", i+1);
}
}
return 0;
}
|
9f5f191f8dc56df718b08b7892cbb740
|
{
"intermediate": 0.45529061555862427,
"beginner": 0.48283568024635315,
"expert": 0.06187369301915169
}
|
13,357
|
Hello, I need your help writing a Java function iusing hte nterpret scan results of a virus total scan via version v3 of its API. By the end of the scan this is what the request looks like:
{
"data": {
"type": "analysis",
"id": "NDRkODg2MTJmZWE4YThmMzZkZTgyZTEyNzhhYmIwMmY6MTY4NzU5NDIyNQ==",
"links": {
"self": "https://www.virustotal.com/api/v3/analyses/NDRkODg2MTJmZWE4YThmMzZkZTgyZTEyNzhhYmIwMmY6MTY4NzU5NDIyNQ=="
}
}
}
|
9c6d7f82158ab5b5fae4e0d501e422b8
|
{
"intermediate": 0.6264788508415222,
"beginner": 0.18218736350536346,
"expert": 0.1913338154554367
}
|
13,358
|
how to teach harmonic motion
|
47c3412b8243bec0b469dabfcbcd3985
|
{
"intermediate": 0.2952219247817993,
"beginner": 0.33113521337509155,
"expert": 0.37364286184310913
}
|
13,359
|
give me some basic smem and valgrind commands to run in ubuntu
|
80d911ad3d26578d6f595a663251924d
|
{
"intermediate": 0.4530627131462097,
"beginner": 0.3876974582672119,
"expert": 0.15923982858657837
}
|
13,360
|
wget -qO- https://github.com/retorquere/zotero-deb/releases/download/apt-get/install.sh | sudo bash
sudo: unable to resolve host ludovic: Name or service not known
sudo: unable to allocate pty: No such device
je suis en chroot
|
a39820adce4e507ab913f24f67446607
|
{
"intermediate": 0.41678908467292786,
"beginner": 0.28268352150917053,
"expert": 0.3005273640155792
}
|
13,361
|
Hey I am using the virustotal v3 API, I need your help writing a java function that interprets the results of a virus total analysis. First here are list of imports, please keep the same one to avoid having other dependencies:
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import okhttp3.*;
When writing the method called getIfMalicious which has as input the String of the server's reponse. To help you maker it here is AN EXTRACT of the request (I don't have enough characters to send it entirely)
{
"meta": {
"file_info": {
"sha256": "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f",
"sha1": "3395856ce81f2b7382dee72602f798b642f14140",
"md5": "44d88612fea8a8f36de82e1278abb02f",
"size": 68
}
},
"data": {
"attributes": {
"date": 1687594225,
"status": "completed",
"stats": {
"harmless": 0,
"type-unsupported": 9,
"suspicious": 0,
"confirmed-timeout": 0,
"timeout": 0,
"failure": 0,
"malicious": 62,
"undetected": 3
},
"results": {
"Bkav": {
"category": "malicious",
"engine_name": "Bkav",
"engine_version": "2.0.0.1",
"result": "W32.EicarTest.Trojan",
"method": "blacklist",
"engine_update": "20230622"
},
"Lionic": {
"category": "malicious",
"engine_name": "Lionic",
"engine_version": "7.5",
"result": "Test.File.EICAR.y",
"method": "blacklist",
"engine_update": "20230624"
},
"Elastic": {
"category": "malicious",
"engine_name": "Elastic",
"engine_version": "4.0.95",
"result": "eicar",
"method": "blacklist",
"engine_update": "20230620"
},
"MicroWorld-eScan": {
"category": "malicious",
"engine_name": "MicroWorld-eScan",
"engine_version": "14.0.409.0",
"result": "EICAR-Test-File",
"method": "blacklist",
"engine_update": "20230624"
},
"CMC": {
"category": "undetected",
"engine_name": "CMC",
"engine_version": "2.4.2022.1",
"result": null,
"method": "blacklist",
"engine_update": "20230619"
},
"CAT-QuickHeal": {
"category": "malicious",
"engine_name": "CAT-QuickHeal",
"engine_version": "22.00",
"result": "EICAR.TestFile",
"method": "blacklist",
"engine_update": "20230623"
},
"McAfee": {
"category": "malicious",
"engine_name": "McAfee",
"engine_version": "6.0.6.653",
"result": "EICAR test file",
"method": "blacklist",
"engine_update": "20230624"
},
"Malwarebytes": {
"category": "malicious",
"engine_name": "Malwarebytes",
"engine_version": "4.5.5.54",
"result": "EICAR-AV-Test",
"method": "blacklist",
"engine_update": "20230624"
},
"VIPRE": {
"category": "malicious",
"engine_name": "VIPRE",
"engine_version": "6.0.0.35",
"result": "EICAR-Test-File (not a virus)",
"method": "blacklist",
"engine_update": "20230623"
},
"Paloalto": {
"category": "type-unsupported",
"engine_name": "Paloalto",
"engine_version": "0.9.0.1003",
"result": null,
"method": "blacklist",
"engine_update": "20230624"
},
"Sangfor": {
"category": "malicious",
"engine_name": "Sangfor",
"engine_version": "2.23.0.0",
"result": "EICAR-Test-File (not a virus)",
"method": "blacklist",
"engine_update": "20230616"
},
}
},
"type": "analysis",
"id": "NDRkODg2MTJmZWE4YThmMzZkZTgyZTEyNzhhYmIwMmY6MTY4NzU5NDIyNQ==",
"links": {
"item": "https://www.virustotal.com/api/v3/files/275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f",
"self": "https://www.virustotal.com/api/v3/analyses/NDRkODg2MTJmZWE4YThmMzZkZTgyZTEyNzhhYmIwMmY6MTY4NzU5NDIyNQ=="
}
}
}
|
715b2a2cc60de43065ab23108a808e24
|
{
"intermediate": 0.4286070764064789,
"beginner": 0.36371108889579773,
"expert": 0.2076817899942398
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.