row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
7,127
|
this is the code:
def find_and_click_button_csgoroll_2(driver, team_1, team_2, button_string):
forbidden_strings = [":", ""]
found_team_1 = False
found_team_2 = False
counter = 0
elements = driver.find_elements(By.XPATH, "//*")
previous_element = None
for element in elements:
print(element.text)
print("-" * 20)
if team_1 in element.text and not found_team_1:
print("found the first team!")
found_team_1 = True
if found_team_1:
print("counter!", counter)
counter += 1
if found_team_1 and not found_team_2 and counter > 100:
print("False!")
found_team_1 = False
counter = 0
if found_team_1 and found_team_2 and button_string in element.get_attribute("outerHTML"):
print("clicked on the odd!")
while previous_element is not None:
try:
button = previous_element.find_element(By.XPATH, ".//button")
# Scroll to the button element
driver.execute_script("arguments[0].scrollIntoView();", button)
actions = ActionChains(driver)
actions.move_to_element(button).click().perform()
return True
except:
parent_element = previous_element.find_element(By.XPATH, "..")
if parent_element is None:
break
previous_element = parent_element
previous_element = element
return False
instead of going to the previous element, when the element found go to element parent and that go one element previous that supposed to be button type, every time element is button type with event called click set previous element to the current one
|
b2444f26481d0c7eb77e8efc7230d79b
|
{
"intermediate": 0.25628992915153503,
"beginner": 0.6076793670654297,
"expert": 0.1360306590795517
}
|
7,128
|
fix the errors in my code and show them to me: import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private String History;
private static String previousHistory;
private List<String> historyList;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder(previousHistory);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder(String previousHistory) {
History = previousHistory;
historyList = new ArrayList<>();
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<PizzaSize> ChoixPizza = new JComboBox<>(PizzaSize.values());
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<ToppingSize> ChoixTopping = new JComboBox<>(ToppingSize.values());
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<Breuvages> ChoixBreuvage = new JComboBox<>(Breuvages.values());
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// calculate total amount
totales += selectedPizzaSize.getPrice() * numPizza;
totales += selectedToppingSize.getPrice() * numTopping;
totales += selectedBreuvage.getPrice() * numBreuvage;
double historytotal = (numPizza * selectedPizzaSize.getPrice()) + (numTopping * selectedToppingSize.getPrice() + (numBreuvage * selectedBreuvage.getPrice()));
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " + numTopping + " " + selectedToppingSize + " garniture - Cout: " + historytotal;
historyList.add(historyEntry);
// clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, historyList);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.List;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, List<String> historyList) {
this.totales = totales;
this.history = String.join("\n", historyList);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(String.join("\n", historyList));
StringBuilder historyBuilder = new StringBuilder();
for (String historyEntry : historyList) {
historyBuilder.append(historyEntry);
historyBuilder.append("\n");
}
commandArea.setText(historyBuilder.toString());
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
modifierCommande.setBounds(6, 316, 182, 29);
panel.add(modifierCommande);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(double totales, List<String> historyList);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
91b2bd401f1beeecccc39b2f002dccec
|
{
"intermediate": 0.32939833402633667,
"beginner": 0.4039839804172516,
"expert": 0.26661765575408936
}
|
7,129
|
Do you know about c# sqlite?
|
e419f2e9a294d021154f53dc1b957bc1
|
{
"intermediate": 0.7369080185890198,
"beginner": 0.13961100578308105,
"expert": 0.12348099797964096
}
|
7,130
|
как изменить этот код так, чтобы цвет точек, к которым применена текстура, слегка изменялся случайным образом от точки к точке?
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls( camera, renderer.domElement );
controls.enableZoom = false;
controls.enableDamping = true;
controls.dampingFactor = 0.05;
const loader = new GLTFLoader();
const url = 'GRAF_3_13.glb';
loader.load(url, function (gltf) {
const model = gltf.scene;
model.traverse((child) => {
if (child.isMesh) {
const geometry = child.geometry;
const texture = new THREE.TextureLoader().load('Ellipse 2.png');
const materialPoint = new THREE.PointsMaterial({
size: 0.03,
sizeAttenuation: true,
map: texture,
alphaTest: 0.01,
transparent: true,
//opacity: 0.4
});
const geometryPoint = new THREE.BufferGeometry();
const positions = geometry.getAttribute('position').array;
const randomPosition = [];
for (let i = 0; i < positions.length; i += 3) {
randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0);
}
const randomPositionCopy = [...randomPosition];
let increment = 0.002;
geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
const points = new THREE.Points(geometryPoint, materialPoint);
geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
function updateArray(increment) {
for(let j = 0; j < 75; j++) {
for(let i = 0; i<randomPosition.length; i++) {
if (randomPosition[i] < positions[i]) {
randomPosition[i] = randomPosition[i] + increment;
} else if(randomPosition[i] > positions[i]) {
randomPosition[i] = randomPosition[i] - increment;
} else if((randomPosition[i] - positions[i]) < 0.002) {
randomPosition[i] = positions[i];
}
}
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
function reverseUpdateArray(increment) {
for(let j = 0; j < 75; j++) {
for(let i = 0; i<randomPosition.length; i++) {
if (randomPosition[i] < randomPositionCopy[i]) {
randomPosition[i] = randomPosition[i] + increment;
} else if(randomPosition[i] > randomPositionCopy[i]) {
randomPosition[i] = randomPosition[i] - increment;
} else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) {
randomPosition[i] = randomPositionCopy[i];
}
}
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
let time = 0;
let sinPosition;
let sinPosition2;
let cosPosition;
let randSignArray = [];
let sign;
let ratio = 1.0;
for(let i = 0; i<randomPosition.length; i++) {
sign = Math.random() < 0.5 ? -1.0 : 1.0;
randSignArray[i] = sign;
}
animateVerticles();
function animateVerticles() {
requestAnimationFrame(animateVerticles);
time += 0.1;
sinPosition = Math.sin(time)*0.1;
cosPosition = Math.cos(time*0.1)*0.1;
sinPosition2 = Math.sin(time/Math.PI)*0.1;
for(let i = 0; i<randomPosition.length; i++) {
randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio;
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
window.addEventListener('wheel', function(event) {
if (event.deltaY > 0) {
updateArray(increment);
if(ratio > 0.0) {
ratio -= 0.01;
}
} else {
reverseUpdateArray(increment);
ratio += 0.01;
}
console.log(ratio);
});
scene.add(points);
points.rotateX(Math.PI/2.0);
}
});
camera.position.z = 3;
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
09648bf987d41846a0a5ec652e0063e2
|
{
"intermediate": 0.3093613386154175,
"beginner": 0.5083816647529602,
"expert": 0.18225696682929993
}
|
7,131
|
implement java class for android that connects to remove server using tcp socket and using ssl
|
78f66b5b0b14c505009d991bf1bd2b53
|
{
"intermediate": 0.5527717471122742,
"beginner": 0.23860962688922882,
"expert": 0.2086186707019806
}
|
7,132
|
reading properties from subfolder properties resources in spring boot
|
20164dcf139f9f6436b94bb3051095a4
|
{
"intermediate": 0.4908037483692169,
"beginner": 0.22005802392959595,
"expert": 0.28913822770118713
}
|
7,133
|
how to make a simple transformer (language model) in python
|
aacf237ed8a3a42f863a791c2ddc3d8b
|
{
"intermediate": 0.19552730023860931,
"beginner": 0.5926834344863892,
"expert": 0.21178926527500153
}
|
7,134
|
getResourceAsStream as file
|
c846dcd459cc630e4422876ac0df470e
|
{
"intermediate": 0.39412418007850647,
"beginner": 0.25713491439819336,
"expert": 0.34874096512794495
}
|
7,135
|
modify my code so that whenever the button Modifier la commande is clicked on, it will bring me back to the PizzaOrder window and when the button Ajouter is clicked on again, the Receipt window will show again and whatever was on the list before is still shown and whatever was added to the list shows too and whatever the total was before was added to the total that was just added: import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private String History;
private static String previousHistory;
private List<String> historyList;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder(previousHistory);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder(String previousHistory) {
History = previousHistory;
historyList = new ArrayList<>();
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<PizzaSize> ChoixPizza = new JComboBox<>(PizzaSize.values());
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<ToppingSize> ChoixTopping = new JComboBox<>(ToppingSize.values());
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<Breuvages> ChoixBreuvage = new JComboBox<>(Breuvages.values());
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// calculate total amount
totales += selectedPizzaSize.getPrice() * numPizza;
totales += selectedToppingSize.getPrice() * numTopping;
totales += selectedBreuvage.getPrice() * numBreuvage;
double historytotal = (numPizza * selectedPizzaSize.getPrice()) + (numTopping * selectedToppingSize.getPrice() + (numBreuvage * selectedBreuvage.getPrice()));
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " + numTopping + " " + selectedToppingSize + " garniture - Cout: " + historytotal;
historyList.add(historyEntry);
// clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, historyList);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.List;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, List<String> historyList) {
this.totales = totales;
this.history = String.join("\n", historyList);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(String.join("\n", historyList));
StringBuilder historyBuilder = new StringBuilder();
for (String historyEntry : historyList) {
historyBuilder.append(historyEntry);
historyBuilder.append("\n");
}
commandArea.setText(historyBuilder.toString());
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
modifierCommande.setBounds(6, 316, 182, 29);
panel.add(modifierCommande);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(0.0, new ArrayList<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
4f5356f13c5102b6c01251b3187867c5
|
{
"intermediate": 0.3145439624786377,
"beginner": 0.44710344076156616,
"expert": 0.23835261166095734
}
|
7,136
|
小蓝社工 (https://t.me/SGKmainNEWbot?start=IVT31EC72CE)
猎魔 (https://t.me/LieMMbot?start=cfd0f7b4f87c4731bebb80a318471cdd)
星盾地址 (https://t.me/XingDunBot?start=1OCo7tl)
落日猎魔 (https://t.me/LuoRiSGKbot?start=zFKKni7auY)
花花猎魔 (https://t.me/sgkvipbot?start=vip_1053371)
免费猎魔 (http://t.me/OnlySGK_bot?start=nlg05hkp9)
狗狗社工 (https://t.me/DogeSGK_bot?start=837579470)
TMD社工 (http://t.me/sgk2023_03_30bot?start=SGK_3IA5ZXLZ)
小丑猎魔 (https://t.me/CLAYSGKbot?start=RA44UH24)
007社工 (https://t.me/DATA_007bot?start=f42b18b322)
MI6猎魔 (https://t.me/MI6SGK_bot?start=4P1uECGmJc)
暗精灵 (https://t.me/AJL01_bot?start=9kbyEQjrGH)
平安社工 (https://t.me/pingansgk_bot?start=4f0c449df4)
公开数据 (https://t.me/publicdatabase_bot)
|
4869c3de057a56816b67b4edb7c4846a
|
{
"intermediate": 0.32860854268074036,
"beginner": 0.30651789903640747,
"expert": 0.3648735582828522
}
|
7,137
|
modify my code so that whenever the button Modifier la commande is clicked on in Receipt, it will bring me back to the PizzaOrder window and when the button Ajouter is clicked on again, the Receipt window will show again and whatever was on the list before is still shown and whatever was added to the list shows too and whatever the total was before was added to the total that was just added: import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private String History;
private static String previousHistory;
private List<String> historyList;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder(previousHistory);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder(String previousHistory) {
History = previousHistory;
historyList = new ArrayList<>();
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<PizzaSize> ChoixPizza = new JComboBox<>(PizzaSize.values());
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<ToppingSize> ChoixTopping = new JComboBox<>(ToppingSize.values());
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<Breuvages> ChoixBreuvage = new JComboBox<>(Breuvages.values());
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// calculate total amount
totales += selectedPizzaSize.getPrice() * numPizza;
totales += selectedToppingSize.getPrice() * numTopping;
totales += selectedBreuvage.getPrice() * numBreuvage;
double historytotal = (numPizza * selectedPizzaSize.getPrice()) + (numTopping * selectedToppingSize.getPrice() + (numBreuvage * selectedBreuvage.getPrice()));
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " + numTopping + " " + selectedToppingSize + " garniture - Cout: " + historytotal;
historyList.add(historyEntry);
// clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, historyList);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.List;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, List<String> historyList) {
this.totales = totales;
this.history = String.join("\n", historyList);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(String.join("\n", historyList));
StringBuilder historyBuilder = new StringBuilder();
for (String historyEntry : historyList) {
historyBuilder.append(historyEntry);
historyBuilder.append("\n");
}
commandArea.setText(historyBuilder.toString());
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
modifierCommande.setBounds(6, 316, 182, 29);
panel.add(modifierCommande);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(0.0, new ArrayList<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
a2c3ce253b6143190a56dd23b3917a5c
|
{
"intermediate": 0.30728915333747864,
"beginner": 0.4501771032810211,
"expert": 0.24253380298614502
}
|
7,138
|
how to make interactive application with graphical ui with python
|
d0723b33f99ede2ba1a9ddc02b0026ec
|
{
"intermediate": 0.4432063698768616,
"beginner": 0.23202456533908844,
"expert": 0.3247690498828888
}
|
7,139
|
Hi, i am using uncode wordpress theme for my shop. I want to add category descriptions to show when user selects category. How can i do that ?
|
f16b9d08fc548e80e52c0b31f1eedd9e
|
{
"intermediate": 0.47160643339157104,
"beginner": 0.18848805129528046,
"expert": 0.3399055004119873
}
|
7,140
|
как изменить этот код, чтобы размер точек немного колебался от точки к точке?
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass';
import { BloomPass } from 'three/examples/jsm/postprocessing/BloomPass';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableZoom = false;
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// добавляем композитор для использования эффектов
const composer = new EffectComposer(renderer);
// добавляем RenderPass
const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);
// добавляем BloomPass
const bloomPass = new BloomPass(1, 25, 4, 256);
composer.addPass(bloomPass);
const loader = new GLTFLoader();
const url = 'GRAF_3_13.glb';
loader.load(url, function (gltf) {
const model = gltf.scene;
model.traverse((child) => {
if (child.isMesh) {
const geometry = child.geometry;
const texture = new THREE.TextureLoader().load('Ellipse 2.png');
const materialPoint = new THREE.PointsMaterial({
size: 0.03,
sizeAttenuation: true,
map: texture,
alphaTest: 0.01,
transparent: true,
color: new THREE.Color(1.2, 1.2, 1.2) // увеличиваем яркость на 20%
});
const geometryPoint = new THREE.BufferGeometry();
const positions = geometry.getAttribute('position').array;
const randomPosition = [];
for (let i = 0; i < positions.length; i += 3) {
randomPosition.push(10.0 * Math.random() - 5.0, 10.0 * Math.random() - 5.0, 10.0 * Math.random() - 5.0);
}
const randomPositionCopy = [...randomPosition];
let increment = 0.002;
geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
const points = new THREE.Points(geometryPoint, materialPoint);
geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
function updateArray(increment) {
for (let j = 0; j < 75; j++) {
for (let i = 0; i < randomPosition.length; i++) {
if (randomPosition[i] < positions[i]) {
randomPosition[i] = randomPosition[i] + increment;
} else if (randomPosition[i] > positions[i]) {
randomPosition[i] = randomPosition[i] - increment;
} else if ((randomPosition[i] - positions[i]) < 0.002) {
randomPosition[i] = positions[i];
}
}
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
function reverseUpdateArray(increment) {
for (let j = 0; j < 75; j++) {
for (let i = 0; i < randomPosition.length; i++) {
if (randomPosition[i] < randomPositionCopy[i]) {
randomPosition[i] = randomPosition[i] + increment;
} else if (randomPosition[i] > randomPositionCopy[i]) {
randomPosition[i] = randomPosition[i] - increment;
} else if ((randomPosition[i] - randomPositionCopy[i]) < 0.002) {
randomPosition[i] = randomPositionCopy[i];
}
}
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
let time = 0;
let sinPosition;
let sinPosition2;
let cosPosition;
let randSignArray = [];
let sign;
let ratio = 1.0;
for (let i = 0; i < randomPosition.length; i++) {
sign = Math.random() < 0.5 ? -1.0 : 1.0;
randSignArray[i] = sign;
}
animateVerticles();
function animateVerticles() {
requestAnimationFrame(animateVerticles);
time += 0.1;
sinPosition = Math.sin(time) * 0.1;
cosPosition = Math.cos(time * 0.1) * 0.1;
sinPosition2 = Math.sin(time / Math.PI) * 0.1;
for (let i = 0; i < randomPosition.length; i++) {
randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio;
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
window.addEventListener('wheel', function (event) {
if (event.deltaY > 0) {
updateArray(increment);
if (ratio > 0.0) {
ratio -= 0.01;
}
} else {
reverseUpdateArray(increment);
ratio += 0.01;
}
console.log(ratio);
});
// устанавливаем needsUpdate для текстуры, чтобы она обновлялась каждый кадр
materialPoint.map.needsUpdate = true;
scene.add(points);
points.rotateX(Math.PI / 2.0);
}
});
camera.position.z = 3;
function animate() {
requestAnimationFrame(animate);
controls.update();
// использование композитора вместо рендерера
composer.render();
}
animate();
});
|
58b7cb1154843c9855e8f6c68ad9157f
|
{
"intermediate": 0.34696176648139954,
"beginner": 0.5175561308860779,
"expert": 0.13548213243484497
}
|
7,141
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
The basic class structure is as follows:
1. Core:
- class Engine
- This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.)
2. Window:
- class Window
- This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events.
3. Renderer:
- class Renderer
- This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines.
- class Shader
- To handle shader modules creation and destruction.
- class Texture
- To handle texture loading and destruction.
- class Pipeline
- To encapsulate the description and creation of a Vulkan graphics or compute pipeline.
4. Scene:
- class Scene
- This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering.
- class GameObject
- To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices.
- class Camera
- To store and manage camera properties such as position, rotation, view, and projection matrices.
- class Mesh
- To handle mesh data (e.g., vertices, indices, etc.) for individual objects.
- class Material
- To store and manage material properties such as colors, shaders, and textures.
5. Math:
- Utilize GLM library to handle vector and matrix math operations.
Here are the header files for context:
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
Camera.h:
#pragma once
#include <glm/glm.hpp>
class Camera
{
public:
Camera();
~Camera();
void Initialize(float aspectRatio);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
const glm::mat4& GetViewMatrix() const;
const glm::mat4& GetProjectionMatrix() const;
private:
glm::vec3 position;
glm::vec3 rotation;
glm::mat4 viewMatrix;
glm::mat4 projectionMatrix;
void UpdateViewMatrix();
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize(const Mesh& mesh, const Material& material);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh mesh;
Material material;
void UpdateModelMatrix();
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
class Material
{
public:
Material();
~Material();
void Initialize(const Shader& vertexShader, const Shader& fragmentShader, const Texture& texture, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void Cleanup();
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
private:
VkDevice device;
Shader vertexShader;
Shader fragmentShader;
Texture texture;
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Mesh.h:
#pragma once
#include <vector>
#include <vulkan/vulkan.h>
#include <glm/glm.hpp>
struct Vertex
{
glm::vec3 position;
glm::vec3 color;
};
class Mesh
{
public:
Mesh();
~Mesh();
void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
const std::vector<Vertex>& GetVertices() const;
const std::vector<uint32_t>& GetIndices() const;
VkBuffer GetVertexBuffer() const;
VkBuffer GetIndexBuffer() const;
private:
VkDevice device;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
};
Pipeline.h:
#pragma once
#include <vulkan/vulkan.h>
#include <vector>
#include <array>
#include <stdexcept>
#include "Shader.h"
class Pipeline
{
public:
Pipeline();
~Pipeline();
void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions,
const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions,
VkExtent2D swapchainExtent,
const std::vector<Shader*>& shaders,
VkRenderPass renderPass,
VkPipelineLayout pipelineLayout,
VkDevice device);
void Cleanup();
VkPipeline GetPipeline() const;
private:
VkDevice device;
VkPipeline pipeline;
void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages);
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Shader.h:
#pragma once
#include <vulkan/vulkan.h>
#include <string>
class Shader
{
public:
Shader();
~Shader();
void LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage);
void Cleanup();
VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo() const;
private:
VkDevice device;
VkShaderModule shaderModule;
VkShaderStageFlagBits stage;
};
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
VkImageView GetImageView() const;
VkSampler GetSampler() const;
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Window.h:
#pragma once
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
class Window
{
public:
Window(int width = 800, int height = 600, const char* title = "Game Engine");
~Window();
void Initialize();
void PollEvents();
void Shutdown();
bool ShouldClose() const;
GLFWwindow* GetWindow() const;
float GetDeltaTime();
private:
static void FramebufferResizeCallback(GLFWwindow* window, int width, int height);
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
int width;
int height;
const char* title;
GLFWwindow* window;
double lastFrameTime;
};
Simplex.h:
#pragma once
#ifndef SIMPLEX_H
#define SIMPLEX_H
#include <iostream>
class SimplexNoise {
private:
int testvar;
int grad3[12][3]{ { 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 },
{ -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 },
{ -1, 0, -1 }, { 0, 1, 1 }, { 0, -1, 1 }, { 0, 1, -1 },
{ 0, -1, -1 } };
int grad4[32][4] = { { 0, 1, 1, 1 }, { 0, 1, 1, -1 },
{ 0, 1, -1, 1 }, { 0, 1, -1, -1 }, { 0, -1, 1, 1 },
{ 0, -1, 1, -1 }, { 0, -1, -1, 1 }, { 0, -1, -1, -1 },
{ 1, 0, 1, 1 }, { 1, 0, 1, -1 }, { 1, 0, -1, 1 }, { 1, 0, -1, -1 },
{ -1, 0, 1, 1 }, { -1, 0, 1, -1 }, { -1, 0, -1, 1 },
{ -1, 0, -1, -1 }, { 1, 1, 0, 1 }, { 1, 1, 0, -1 },
{ 1, -1, 0, 1 }, { 1, -1, 0, -1 }, { -1, 1, 0, 1 },
{ -1, 1, 0, -1 }, { -1, -1, 0, 1 }, { -1, -1, 0, -1 },
{ 1, 1, 1, 0 }, { 1, 1, -1, 0 }, { 1, -1, 1, 0 }, { 1, -1, -1, 0 },
{ -1, 1, 1, 0 }, { -1, 1, -1, 0 }, { -1, -1, 1, 0 },
{ -1, -1, -1, 0 } };
int p_supply[256] = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96,
53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240,
21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94,
252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87,
174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48,
27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63,
161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,
135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82,
85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223,
183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101,
155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113,
224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193,
238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14,
239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176,
115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114,
67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 };
// To remove the need for index wrapping, double the permutation table
// length
int perm[512] = {};
/*static {
for (int i = 0; i < 512; i++)
perm[i] = p[i & 255];
}*/
// A lookup table to traverse the simplex around a given point in 4D.
// Details can be found where this table is used, in the 4D noise method.
int simplex[64][4] = { { 0, 1, 2, 3 }, { 0, 1, 3, 2 },
{ 0, 0, 0, 0 }, { 0, 2, 3, 1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 1, 2, 3, 0 }, { 0, 2, 1, 3 }, { 0, 0, 0, 0 },
{ 0, 3, 1, 2 }, { 0, 3, 2, 1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 1, 3, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 2, 0, 3 }, { 0, 0, 0, 0 },
{ 1, 3, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 2, 3, 0, 1 }, { 2, 3, 1, 0 }, { 1, 0, 2, 3 }, { 1, 0, 3, 2 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 2, 0, 3, 1 },
{ 0, 0, 0, 0 }, { 2, 1, 3, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 2, 0, 1, 3 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 3, 0, 1, 2 }, { 3, 0, 2, 1 },
{ 0, 0, 0, 0 }, { 3, 1, 2, 0 }, { 2, 1, 0, 3 }, { 0, 0, 0, 0 },
{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 3, 1, 0, 2 }, { 0, 0, 0, 0 },
{ 3, 2, 0, 1 }, { 3, 2, 1, 0 } };
int p[256] = {};
int RANDOMSEED = 0;
int NUMBEROFSWAPS = 400;
public:
SimplexNoise(int inseed);
double noise(double xin, double yin);
double noise(double xin, double yin, double zin);
double noise(double xin, double yin, double zin, double win);
};
#endif
I want to add the ability to produce randomly generated terrain. How would I got about doing this?
|
7dca3aad048d7cf2cb34fcf56a3c5729
|
{
"intermediate": 0.45648056268692017,
"beginner": 0.32650935649871826,
"expert": 0.21701014041900635
}
|
7,142
|
как добавить градиент на фон канваса в этой сцене?
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls( camera, renderer.domElement );
controls.enableZoom = false;
controls.enableDamping = true;
controls.dampingFactor = 0.05;
const loader = new GLTFLoader();
const url = 'GRAF_3_14.glb';
loader.load(url, function (gltf) {
const model = gltf.scene;
model.traverse((child) => {
if (child.isMesh) {
const geometry = child.geometry;
const texture = new THREE.TextureLoader().load('Ellipse 2.png');
let startSize = 0.03;
const sizeVariation = 0.1;
const materialPoint = new THREE.PointsMaterial({
size: startSize,
sizeAttenuation: true,
map: texture,
alphaTest: 0.01,
transparent: true,
color: new THREE.Color(1.8, 1.8, 1.8)
//opacity: 0.4
});
const geometryPoint = new THREE.BufferGeometry();
const positions = geometry.getAttribute('position').array;
const randomSize = [];
for (let i = 0; i < positions.length; i += 3) {
const size = startSize + (Math.random() * sizeVariation);
randomSize.push(size, size, size);
}
geometryPoint.setAttribute('size', new THREE.Float32BufferAttribute(randomSize, 1));
const randomPosition = [];
for (let i = 0; i < positions.length; i += 3) {
randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0);
}
const randomPositionCopy = [...randomPosition];
let increment = 0.002;
geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
const points = new THREE.Points(geometryPoint, materialPoint);
geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
function updateArray(increment) {
for(let j = 0; j < 75; j++) {
for(let i = 0; i<randomPosition.length; i++) {
if (randomPosition[i] < positions[i]) {
randomPosition[i] = randomPosition[i] + increment;
} else if(randomPosition[i] > positions[i]) {
randomPosition[i] = randomPosition[i] - increment;
} else if((randomPosition[i] - positions[i]) < 0.002) {
randomPosition[i] = positions[i];
}
}
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
function reverseUpdateArray(increment) {
for(let j = 0; j < 75; j++) {
for(let i = 0; i<randomPosition.length; i++) {
if (randomPosition[i] < randomPositionCopy[i]) {
randomPosition[i] = randomPosition[i] + increment;
} else if(randomPosition[i] > randomPositionCopy[i]) {
randomPosition[i] = randomPosition[i] - increment;
} else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) {
randomPosition[i] = randomPositionCopy[i];
}
}
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
let time = 0;
let sinPosition;
let sinPosition2;
let cosPosition;
let randSignArray = [];
let sign;
let ratio = 1.0;
for(let i = 0; i<randomPosition.length; i++) {
sign = Math.random() < 0.5 ? -1.0 : 1.0;
randSignArray[i] = sign;
}
animateVerticles();
function animateVerticles() {
requestAnimationFrame(animateVerticles);
time += 0.1;
sinPosition = Math.sin(time)*0.1;
cosPosition = Math.cos(time*0.1)*0.1;
sinPosition2 = Math.sin(time/Math.PI)*0.1;
for(let i = 0; i<randomPosition.length; i++) {
randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio;
}
geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
}
window.addEventListener('wheel', function(event) {
if (event.deltaY > 0) {
updateArray(increment);
if(ratio > 0.0) {
ratio -= 0.01;
}
} else {
reverseUpdateArray(increment);
ratio += 0.01;
}
console.log(ratio);
});
scene.add(points);
points.rotateX(Math.PI/2.0);
}
});
camera.position.z = 3;
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
2b9a1ab7a01b962d182826004f605cdf
|
{
"intermediate": 0.29568636417388916,
"beginner": 0.45578527450561523,
"expert": 0.24852833151817322
}
|
7,143
|
Сделай TextView ближе друг к другу : <LinearLayout
android:layout_width="match_parent"
android:layout_height="69dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
style="@style/CustomTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"/>
<TextView
android:id="@+id/textViewName_2"
style="@style/CustomTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"/>
</LinearLayout>
|
4ff6dfb9bb34b13399b4cf47eaf1d065
|
{
"intermediate": 0.4248266816139221,
"beginner": 0.2498217523097992,
"expert": 0.3253515660762787
}
|
7,144
|
Escríbeme un artículo que sea compatible con SEO poniendo las palabras clave más importantes en forma de puntos y explicándolas a esta frase: ideas para decorar una fiesta de cumpleaños para mujer
|
6a4a52b7c7b513c9a82a35377a2a8b5b
|
{
"intermediate": 0.3362922966480255,
"beginner": 0.3875465393066406,
"expert": 0.27616119384765625
}
|
7,145
|
import telebot
# Токен бота
TOKEN = '6051752717:AAEU7VginJfplonKAFRGxPqtkaJDcVh98Bo'
# Список правил
RULES = [
'1. Уважайте других участников канала. Не используйте оскорбительные выражения, не унижайте других участников и не нарушайте их права.',
'2. Соблюдайте правила приличия. Не публикуйте материалы, содержащие порнографию, насилие, расизм, сексизм и другие формы дискриминации.',
'3. Не публикуйте спам и рекламу. Не размещайте ссылки на сторонние ресурсы без согласия администрации канала.',
'4. Следите за темой канала. Не публикуйте сообщения, не относящиеся к теме канала.',
'5. Соблюдайте законы. Не публикуйте сообщения, нарушающие законы РФ и других стран.',
'6. Соблюдайте правила Telegram. Не используйте ботов и скрипты, нарушающие правила Telegram.'
]
# Создаем объект бота
bot = telebot.TeleBot(TOKEN)
## Создаем множество для хранения ID новых пользователей
new_users = set()
# Обработчик новых пользователей
@bot.message_handler(content_types=['new_chat_members'])
def new_member_handler(message):
# Добавляем ID пользователя в множество новых пользователей
new_users.add(message.new_chat_members[0].id)
# Проверяем, согласен ли пользователь с правилами
keyboard = telebot.types.InlineKeyboardMarkup()
agree_button = telebot.types.InlineKeyboardButton(text='Согласен', callback_data='agree')
disagree_button = telebot.types.InlineKeyboardButton(text='Не согласен', callback_data='disagree')
keyboard.add(agree_button, disagree_button)
bot.send_message(message.chat.id,
f'Привет, {message.new_chat_members[0].first_name}! Чтобы присоединиться к чату, тебе нужно согласиться с правилами:\n\n' + '\n'.join(
RULES), reply_markup=keyboard)
# Обработчик нажатий на кнопки
@bot.callback_query_handler(func=lambda call: True)
def callback_handler(call):
# Проверяем, является ли пользователь новым
if call.from_user.id not in new_users:
return
if call.data == 'agree':
# Удаляем сообщение бота
bot.delete_message(call.message.chat.id, call.message.message_id)
# Удаляем пользователя из множества новых пользователей
new_users.remove(call.from_user.id)
elif call.data == 'disagree':
# Удаляем пользователя из чата
bot.kick_chat_member(call.message.chat.id, call.from_user.id)
# Удаляем сообщение бота
bot.delete_message(call.message.chat.id, call.message.message_id)
# Удаляем пользователя из множества новых пользователей
new_users.remove(call.from_user.id)
# Запускаем бота
bot.polling(none_stop=True)
Пережелай код, для телеграм бота 20.3 версии, через команду async
|
7b30f9423bf3b1a5405fc42e9b32a827
|
{
"intermediate": 0.29020464420318604,
"beginner": 0.5284205079078674,
"expert": 0.1813749074935913
}
|
7,146
|
Сделай весь текст симметричным : чтобы первый визуальный столбец начинался на одной линии по оси y , второй столбец соответственно :<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”
android:padding=“16dp”
android:gravity=“center_vertical”
>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“69dp”
android:orientation=“horizontal”
android:weightSum=“2”>
<TextView
android:paddingStart=“100dp”
style=“@style/CustomTextViewStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“8dp”
android:gravity=“center”
android:text=“Name: “
android:layout_weight=“1”
/>
<TextView
android:id=”@+id/textViewName_2”
android:paddingEnd=“100dp”
style=“@style/CustomTextViewStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“8dp”
android:gravity=“center”
android:text=“Email: “
android:layout_weight=“1”
/>
</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“69dp”
android:orientation=“horizontal”
android:weightSum=“2”>
<TextView
android:paddingStart=“110dp”
style=”@style/CustomTextViewStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“8dp”
android:gravity=“center”
android:text=“Email: “
android:layout_weight=“1”
/>
<TextView
android:id=”@+id/editTextEmail_2”
android:paddingEnd=“80dp”
style=“@style/CustomTextViewStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“8dp”
android:gravity=“center”
android:text=“Email: “
android:layout_weight=“1”
/>
</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“69dp”
android:orientation=“horizontal”
android:weightSum=“2”>
<TextView
android:paddingStart=“100dp”
style=”@style/CustomTextViewStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“8dp”
android:gravity=“center”
android:text=“Password: “
android:layout_weight=“1”
/>
<TextView
android:id=”@+id/password_2”
android:paddingEnd=“100dp”
style=“@style/CustomTextViewStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“8dp”
android:gravity=“center”
android:text="Email: "
android:layout_weight=“1”
/>
</LinearLayout>
</LinearLayout>
|
21775ca840bd00e7425e4c5d4e24e252
|
{
"intermediate": 0.305152952671051,
"beginner": 0.43567514419555664,
"expert": 0.2591719329357147
}
|
7,147
|
Can you make a code that simulate chages distribution in the 3D field below
the field size is 100 x 100 x 100 pixels
1 pixel is 1 mm
Edges of field is 0V
Center 10 x 10 x 10 of the field are 1V
Center 10 x 10 x 10 of the field are electrodes. Other than the field is vacuum.
|
4b104e6685670ff07ed0451a3681ef83
|
{
"intermediate": 0.3822387158870697,
"beginner": 0.07255765795707703,
"expert": 0.5452036261558533
}
|
7,148
|
from kivy.app import App
from kivy.uix.screenmanager import Screen , ScreenManager
import cv2
import time
class MainScreen(Screen):
pass
class StreamView(Screen):
pass
class ScreenMan(ScreenManager):
pass
class MyApp(App):
def build(self):
sm = ScreenMan()
sm.add_widget(MainScreen(name="Main"))
sm.add_widget(StreamView(name="Stream"))
sm.current = "Stream"
return sm
if __name__ == '__main__':
MyApp().run()
|
9513bbd479db9b2f779c55d4a67cc9f1
|
{
"intermediate": 0.37751442193984985,
"beginner": 0.48450586199760437,
"expert": 0.13797973096370697
}
|
7,149
|
convert kivy file with image to apk
|
0e6d52daec1235a7ebf03ace965c703a
|
{
"intermediate": 0.4238244593143463,
"beginner": 0.22419527173042297,
"expert": 0.3519802689552307
}
|
7,150
|
LSM network in pascal 3 layer mesh topology and explain how to train
|
052e9c9858c95fb86a27ac6da54f4fc6
|
{
"intermediate": 0.052802398800849915,
"beginner": 0.04307814687490463,
"expert": 0.9041194319725037
}
|
7,151
|
Добавь сверху иконку для фотографии пользователя , помни что эта иконка должна иметь фотографию по умолчанию и при клике пользователь сможет изменить её на любую другую из его файлов : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>
|
5dd69ffc6cbb1a513418053fa968297f
|
{
"intermediate": 0.2250003069639206,
"beginner": 0.5422914624214172,
"expert": 0.23270830512046814
}
|
7,152
|
Ksyusha has a pet chinchilla, a tree on n
vertices and huge scissors. A tree is a connected graph without cycles. During a boring physics lesson Ksyusha thought about how to entertain her pet.
Chinchillas like to play with branches. A branch is a tree of 3
vertices.
The branch looks like this.
A cut is the removal of some (not yet cut) edge in the tree. Ksyusha has plenty of free time, so she can afford to make enough cuts so that the tree splits into branches. In other words, after several (possibly zero) cuts, each vertex must belong to exactly one branch.
Help Ksyusha choose the edges to be cut or tell that it is impossible.
Input
The first line contains a single integer t
(1≤t≤104
) — number of testcases.
The first line of each testcase contains a single integer n
(2≤n≤2⋅105
) — the number of vertices in the tree.
The next n−1
rows of each testcase contain integers vi
and ui
(1≤vi,ui≤n
) — the numbers of vertices that the i
-th edge connects.
It is guaranteed that this set of edges forms a tree. It is also guaranteed that the sum of n
over all testcases does not exceed 2⋅105
.
Output
Print the answer for each testcase.
If the desired way to cut the tree does not exist, print −1
.
Otherwise, print an integer k
— the number of edges to be cut. In the next line, print k
different integers ei
(1≤ei<n
) — numbers of the edges to be cut. If k=0
, print an empty string instead.
If there are several solutions, you can print any.
Examples
inputCopy
4
9
1 2
4 3
7 9
5 4
4 6
3 2
8 7
1 7
6
1 2
1 3
4 3
1 5
6 1
6
1 2
3 2
3 4
4 5
6 5
5
1 3
5 3
5 2
3 4
outputCopy
2
2 8
-1
1
3
-1
inputCopy
4
2
1 2
3
1 2
3 1
6
1 2
3 1
3 4
3 5
6 1
9
2 6
6 9
9 1
9 7
1 8
7 3
8 5
4 7
outputCopy
-1
0
1
2
2
4 3
solve this problem in c++
|
d2fb00fc13b1e0a6dff7529ed32c9b75
|
{
"intermediate": 0.31451401114463806,
"beginner": 0.3867168426513672,
"expert": 0.29876917600631714
}
|
7,153
|
Let me know if you have a better approach:
I have a small C# bot that check for an available date/time and book it if any,
it uses 2 external APIs which many other users use so it is a race, My main goal is to get an available date/time that I didn’t use before if possible.
private static readonly Dictionary<string, List<string>> TestedDateTimes = new();
public async void Main()
{
// Checking
string? date, time;
while (true)
{
(date, time) = await SelectAvailableDateTime().ConfigureAwait(false);
if (date != null && time != null) break;
await Task.Delay(3000).ConfigureAwait(false);
}
//Do something with the date/time...
}
public async Task<(string date, string time)> SelectAvailableDateTime()
{
var date = await GetNonUsedRandomDate().ConfigureAwait(false);
if (date == default) return default;
var time = await GetNonUsedRandomTimeByDate(date).ConfigureAwait(false);
if (time == null) return default;
if (!TestedDateTimes.ContainsKey(date))
TestedDateTimes[date] = new List<string>();
if (!TestedDateTimes[date].Contains(time))
TestedDateTimes[date].Add(time);
return (date, time);
}
private async Task<string?> GetNonUsedRandomDate()
{
var allDates = await GetAllDates().ConfigureAwait(false);
var availableDates = allDates
?.Where(d => d.AppointmentDateType == AppointmentDateType.Available &&
(_applicant.Members.Count < 2 || d.SingleSlotAvailable))
.ToArray();
if (availableDates == null || availableDates.Length == 0) return default;
var nonUsedDates = availableDates.Where(d => !TestedDateTimes.ContainsKey(d.DateText)).ToArray();
if (nonUsedDates.Length == 0)
nonUsedDates = availableDates;
// So if the user uses a custom date selector and there is no date fulfill his needs, search on all
return (GetRandomDate(nonUsedDates) ?? GetRandomDate(availableDates))?.DateText;
}
private async Task<string?> GetNonUsedRandomTimeByDate(string date)
{
var allTimes = await GetAllTimes(date).ConfigureAwait(false);
var availableTimes = allTimes
?.Where(t => t.Count >= _applicant.Members.Count)
.ToArray();
if (availableTimes == null || availableTimes.Length == 0) return default;
var nonUsedTimes = !TestedDateTimes.ContainsKey(date)
? availableTimes
: availableTimes.Where(t => !TestedDateTimes[date].Contains(t.Id)).ToArray();
if (nonUsedTimes.Length == 0)
{
TestedDateTimes.Remove(date);
nonUsedTimes = availableTimes;
}
return FetchHelper.GetRandomElement(nonUsedTimes)?.Id;
}
private Date? GetRandomDate(IEnumerable<Date>? enumerable)
{
if (enumerable == null) return default;
var dates = enumerable as Date[] ?? enumerable.ToArray();
if (!dates.Any()) return null;
if (_applicant.DateSelector == DateSelector.Custom)
{
dates = dates
.Where(d => StringToDate(d.DateText) is var dateTime &&
dateTime >= StringToDate(_applicant.CustomDateFrom) &&
dateTime <= StringToDate(_applicant.CustomDateTo))
.ToArray();
return FetchHelper.GetRandomElement(dates);
}
var ordered = dates.OrderBy(d => StringToDate(d.DateText)).ToArray();
var takeAmount = ordered.Length == 1 ? 1 : ordered.Length / 2;
return _applicant.DateSelector switch
{
DateSelector.Soon => FetchHelper.GetRandomElement(ordered.Take(takeAmount)),
DateSelector.Later => FetchHelper.GetRandomElement(ordered.Reverse().Take(takeAmount)),
DateSelector.Any => FetchHelper.GetRandomElement(ordered),
_ => FetchHelper.GetRandomElement(ordered)
};
}
private static DateTime? StringToDate(string? date, string format = "yyyy-MM-dd")
{
var valid = DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result);
return valid ? result : null;
}
private async Task<Date[]?> GetAllDates()
{
// FROM EXTERNAL API
}
private async Task<Time[]?> GetAllTimes(string date)
{
// FROM EXTERNAL API
}
|
d2f06826120bd9cf78a230c8a0c165d3
|
{
"intermediate": 0.4146067500114441,
"beginner": 0.38936522603034973,
"expert": 0.19602802395820618
}
|
7,154
|
https://www.google.com/search?q=voice+recorder+online&oq=voice+recorder&aqs=chrome.1.69i57j0i512l6j69i60.13338j0j4&sourceid=chrome&ie=UTF-8
|
f354c0335f33b50e0ffa6b2cbd064c76
|
{
"intermediate": 0.3316199481487274,
"beginner": 0.34694716334342957,
"expert": 0.3214329481124878
}
|
7,155
|
import tkinter as tk
from PIL import Image, ImageTk
# Create the main window
root = tk.Tk()
root.title('My Application')
root.geometry('400x300')
try:
# Load the GIF using PIL
image = Image.open('myimage.gif')
# Convert the GIF to a Tkinter-compatible image
tkimage = ImageTk.PhotoImage(image)
# Add the image to a Label
label = tk.Label(root, image=tkimage)
label.pack()
except FileNotFoundError:
print('Could not find image file.')
except:
print('An unknown error occurred.')
# Start the event loop
root.mainloop()
here is the problem: the gif is not moving
|
a54193a5b32695ed4d77b72360131261
|
{
"intermediate": 0.3278444707393646,
"beginner": 0.5216909050941467,
"expert": 0.15046463906764984
}
|
7,156
|
How can I send emails from stripe when a payment intent is created and captured? Also when a payment is refunded. I'm using nestjs
Also how can I pass data like a booking reference to the success page after a successful checkout using webhooks?
|
5fcaf4be838ce6a7fb502e0f0a9aa6a8
|
{
"intermediate": 0.9029049277305603,
"beginner": 0.04302842170000076,
"expert": 0.05406665429472923
}
|
7,157
|
Write me a computer code in python that can record the amount of patients consulted at a medical centre dental practice.
|
2f15824a869f596afd54f10b5a368122
|
{
"intermediate": 0.37052226066589355,
"beginner": 0.10023007541894913,
"expert": 0.5292476415634155
}
|
7,158
|
Добавь атрибут который сделает картинку круглой : <ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24" />
|
839ac3037248be58de14efded6280266
|
{
"intermediate": 0.4418286085128784,
"beginner": 0.24462611973285675,
"expert": 0.31354522705078125
}
|
7,159
|
help me write 10 difficult level long queries for the following tables:
CREATE TABLE Buyer (
ID INT PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL,
surname VARCHAR(50) NOT NULL,
email VARCHAR(100),
phone VARCHAR(20) NOT NULL,
dob DATE
);
CREATE INDEX index_buyer_phone
ON Buyer(phone);
CREATE TABLE Product (
ID INT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
year INT NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT NOT NULL,
warranty INT NOT NULL
);
CREATE INDEX index_product_name
ON Product(name);
CREATE TABLE ProductSupplier (
ID INT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
address VARCHAR(200) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT NULL
);
CREATE INDEX index_productsupplier_email
ON ProductSupplier(email);
CREATE TABLE ProductType (
ID INT PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL,
description TEXT NOT NULL
);
CREATE INDEX index_ProductType_name
ON ProductType(name);
CREATE TABLE PersonalRepair (
ID INT PRIMARY KEY NOT NULL,
description TEXT NOT NULL,
inDate DATE NOT NULL,
outDate DATE,
price DECIMAL(10, 2),
RepairState VARCHAR(50) NOT NULL
CHECK (RepairState IN ('Completed', 'In progress', 'Scheduled', 'Pending'))
);
CREATE TABLE Review (
ID INT PRIMARY KEY NOT NULL,
description TEXT NOT NULL,
rating INT NOT NULL
);
CREATE TABLE EmployeeRole (
ID INT PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL
);
CREATE TABLE Employee (
ID INT PRIMARY KEY NOT NULL,
SSN VARCHAR(20) NOT NULL,
name VARCHAR(50) NOT NULL,
surname VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
dob DATE NOT NULL,
salary DECIMAL(10, 2) NOT NULL
);
CREATE INDEX index_employee_ssn
ON Employee(SSN);
CREATE TABLE Buyer_Product (
BuyerID INT NOT NULL,
ProductID INT NOT NULL,
PurchaseDate DATE NOT NULL,
PRIMARY KEY (BuyerID, ProductID),
FOREIGN KEY (BuyerID) REFERENCES Buyer(ID),
FOREIGN KEY (ProductID) REFERENCES Product(ID)
);
CREATE TABLE Product_ProductType (
ProductID INT NOT NULL,
ProductTypeID INT NOT NULL,
PRIMARY KEY (ProductID, ProductTypeID),
FOREIGN KEY (ProductID) REFERENCES Product(ID),
FOREIGN KEY (ProductTypeID) REFERENCES ProductType(ID)
);
CREATE TABLE Product_ProductSupplier (
ProductID INT NOT NULL,
ProductSupplierID INT NOT NULL,
DateOfImport DATE NOT NULL,
Quantity INT NOT NULL,
PRIMARY KEY (ProductID, ProductSupplierID),
FOREIGN KEY (ProductID) REFERENCES Product(ID),
FOREIGN KEY (ProductSupplierID) REFERENCES ProductSupplier(ID)
);
CREATE TABLE Product_PersonalRepair (
ProductID INT NOT NULL,
PersonalRepairID INT NOT NULL,
PRIMARY KEY (ProductID, PersonalRepairID),
FOREIGN KEY (ProductID) REFERENCES Product(ID),
FOREIGN KEY (PersonalRepairID) REFERENCES PersonalRepair(ID)
);
ALTER TABLE PersonalRepair
ADD BuyerID INT;
ALTER TABLE PersonalRepair
ADD FOREIGN KEY (BuyerID) REFERENCES Buyer(ID);
ALTER TABLE Review
ADD PersonalRepairID INT;
ALTER TABLE Review
ADD FOREIGN KEY (PersonalRepairID) REFERENCES PersonalRepair(ID);
ALTER TABLE PersonalRepair
ADD ProductID INT;
ALTER TABLE PersonalRepair
ADD FOREIGN KEY (ProductID) REFERENCES Product(ID);
CREATE TABLE PersonalRepair_Employee (
PersonalRepairID INT NOT NULL,
EmployeeID INT NOT NULL,
PRIMARY KEY (PersonalRepairID, EmployeeID),
FOREIGN KEY (PersonalRepairID) REFERENCES PersonalRepair(ID),
FOREIGN KEY (EmployeeID) REFERENCES Employee(ID)
);
CREATE TABLE Employee_EmployeeRole (
EmployeeID INT NOT NULL,
EmployeeRoleID INT NOT NULL,
PRIMARY KEY (EmployeeID, EmployeeRoleID),
FOREIGN KEY (EmployeeID) REFERENCES Employee(ID),
FOREIGN KEY (EmployeeRoleID) REFERENCES EmployeeRole(ID)
);
|
b5f85d7e700004add6ac678f4d1a3a75
|
{
"intermediate": 0.3569841682910919,
"beginner": 0.3161616027355194,
"expert": 0.32685425877571106
}
|
7,160
|
При замене моей иконки картинкой из фотографий иконка остается квадратной , а должна быть круглой укажи что надо исправить : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"
android:clipToOutline="true"
android:outlineProvider="background"/>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>package com.example.myapp_2;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
3b5af64588e81caf3d5519e3bb8b54dd
|
{
"intermediate": 0.31682804226875305,
"beginner": 0.5046964883804321,
"expert": 0.17847542464733124
}
|
7,161
|
provide a working formula for MS Excel that will sum the total of two different cells if a third cell contains a w, but subtract the two cells if the third cell contains a l
|
048edfbe6d33d3519ad3d9c642239b3c
|
{
"intermediate": 0.40305641293525696,
"beginner": 0.18747304379940033,
"expert": 0.40947049856185913
}
|
7,162
|
hello
|
1b3c3d9e53f309fc78a546fdc069eae6
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
7,163
|
Этот код позволяет выбрать картинку и сделать эту картинку иконкой , но проблема в том что изначально (до выбора картинки иконка круглая) , а после выбора картинки становится квадратной , товя задача сделать так чтобы поле выбора картинки эта картинка должны остаться круглой : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"
android:clipToOutline="true"
android:outlineProvider="background"
/>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>package com.example.myapp_2;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конвертация изображения в Bitmap
Bitmap sourceBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// вычисление размера стороны квадрата, который округляется до круга
int sideLength = Math.min(sourceBitmap.getWidth(), sourceBitmap.getHeight());
// создание нового Bitmap, который содержит круглое изображение
Bitmap clippedBitmap = Bitmap.createBitmap(sideLength, sideLength, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(clippedBitmap);
BitmapShader shader = new BitmapShader(sourceBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
float radius = sideLength / 2f;
canvas.drawCircle(radius, radius, radius, paint);
// сохранение круглого изображения в файл
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile("profile_picture_", ".jpg", storageDir);
FileOutputStream out = new FileOutputStream(imageFile);
clippedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
// отображение круглого изображения на ImageButton
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(clippedBitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed to open image", Toast.LENGTH_SHORT).show();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
2fbd6b231a606be630152605d0d02f83
|
{
"intermediate": 0.283186674118042,
"beginner": 0.5383843183517456,
"expert": 0.1784290075302124
}
|
7,164
|
После выбора картинки пользователем ока должны стать круглой и заменить imagebutton , но у меня после замены иконки картинкой картинка квадратная а должны быть круглой : package com.example.myapp_2;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageViewProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:clipToOutline="true"
android:outlineProvider="background"
/>
<ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"/>
</FrameLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>
|
c7dc85b5b1b1ce6df62d84f7f5574dbe
|
{
"intermediate": 0.28630563616752625,
"beginner": 0.5743463635444641,
"expert": 0.13934803009033203
}
|
7,165
|
explain operator overloading in c++ using a simple code
|
0b70c216c7c542f358f0c9355df02090
|
{
"intermediate": 0.27193111181259155,
"beginner": 0.3622378706932068,
"expert": 0.36583101749420166
}
|
7,166
|
Наложи другой xml так чтобы обрезать углы этого <ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"/>
|
5c9cb63ac1850152b544d2d1c27c1aa1
|
{
"intermediate": 0.4528292417526245,
"beginner": 0.24601972103118896,
"expert": 0.30115094780921936
}
|
7,167
|
При выборе квадратной картинки она должны быть изображена обрезанной до круглой формы виде :package com.example.myapp_2;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"/>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>
|
083736216abbc65164d5d7ba6feffcba
|
{
"intermediate": 0.29524800181388855,
"beginner": 0.47431156039237976,
"expert": 0.2304404079914093
}
|
7,168
|
I deleted Android webdev view from andriod system apps and now phone in bootloop. how to fix?
|
bbf2fbc5ec9cfbc21ab2a20dde1c8208
|
{
"intermediate": 0.6003532409667969,
"beginner": 0.20522406697273254,
"expert": 0.1944226324558258
}
|
7,169
|
При клике на иконку она заменяется на изображение , я зочу что она заменялась на круглое изображение (помни что пользователь выбирает изображение из своей галлереи) , вот код, который ты исправишь : package com.example.myapp_2;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"/>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>
|
a339448578463f73f2ed8069487c5650
|
{
"intermediate": 0.2855693995952606,
"beginner": 0.5791531205177307,
"expert": 0.13527749478816986
}
|
7,170
|
You are a software engineer. And you will help me with my code here. #include <stdio.h>
#include <stdlib.h>
typedef enum { BEAR, BIRD, PANDA} AnimalType;
typedef enum { ALIVE, DEAD } AnimalStatus;
typedef struct {
int x;
int y;
} Location;
typedef enum { FEEDING, NESTING, WINTERING } SiteType;
typedef struct {
/** animal can be DEAD or ALIVE*/
AnimalStatus status;
/** animal type, bear, bird, panda*/
AnimalType type;
/** its location in 2D site grid*/
Location location;
} Animal;
/*example usage*/
Animal bird, bear, panda;
/** type of Hunter*/
typedef struct {
/** points indicate the number of animals, a hunter killed*/
int points;
/** its location in the site grid*/
Location location;
} Hunter;
/** type of a site (a cell in the grid)*/
typedef struct {
/** array of pointers to the hunters located at this site*/
Hunter **hunters;
/** the number of hunters at this site*/
int nhunters;
/** array of pointers to the animals located at this site*/
Animal **animals;
/** the number of animals at this site*/
int nanimals;
/** the type of site*/
SiteType type;
} Site;
/** 2D site grid*/
typedef struct {
/** number of rows, length at the x-coordinate*/
int xlength;
/** number of columns, length at the y-coordinate*/
int ylength;
/** the 2d site array*/
Site **sites;
} Grid;
/* initial grid, empty*/
Grid grid = {0, 0, NULL};
/**
* @brief initialize grid with random site types
* @param xlength
* @param ylength
* @return Grid
*/
Grid initgrid(int xlength, int ylength) {
grid.xlength = xlength;
grid.ylength = ylength;
grid.sites = (Site **)malloc(sizeof(Site *) * xlength);
for (int i = 0; i < xlength; i++) {
grid.sites[i] = (Site *)malloc(sizeof(Site) * ylength);
for (int j = 0; j < ylength; j++) {
grid.sites[i][j].animals = NULL;
grid.sites[i][j].hunters = NULL;
grid.sites[i][j].nhunters = 0;
grid.sites[i][j].nanimals = 0;
double r = rand() / (double)RAND_MAX;
SiteType st;
if (r < 0.33)
st = WINTERING;
else if (r < 0.66)
st = FEEDING;
else
st = NESTING;
grid.sites[i][j].type = st;
}
}
return grid;
}
/**
* @brief
*
*/
void deletegrid() {
for (int i = 0; i < grid.xlength; i++) {
free(grid.sites[i]);
}
free(grid.sites);
grid.sites = NULL;
grid.xlength = -1;
grid.ylength = -1;
}
/**
* @brief prints the number animals and hunters in each site
* of a given grid
* @param grid
*/
void printgrid() {
for (int i = 0; i < grid.xlength; i++) {
for (int j = 0; j < grid.ylength; j++) {
Site *site = &grid.sites[i][j];
int count[3] = {0}; /* do not forget to initialize*/
for (int a = 0; a < site->nanimals; a++) {
Animal *animal = site->animals[a];
count[animal->type]++;
}
printf("|%d-{%d, %d, %d}{%d}|", site->type, count[0], count[1],
count[2], site->nhunters);
}
printf("\n");
}
}
/**
* @brief prints the info of a given site
*
*/
void printsite(Site *site) {
int count[3] = {0}; /* do not forget to initialize*/
for (int a = 0; a < site->nanimals; a++) {
Animal *animal = site->animals[a];
count[animal->type]++;
}
printf("|%d-{%d,%d,%d}{%d}|", site->type, count[0], count[1], count[2],
site->nhunters);
}
/*
=============================================================
TODO: you need to complete following three functions
DO NOT CHANGE ANY OF THE FUNCTION NAME OR TYPES
=============================================================
*/
/**
* @brief it moves a given hunter or animal
* randomly in the grid
* @param args is an animalarray
* @return void*
*/
void *simulateanimal(void *args) {
/*TODO: complete this function:
get animal type,
check if animal dies,
then chose random direction and move
make sure to update site.animals
then sleep
*/
return NULL;
}
/**
* @brief simulates the moving of a hunter
*
* @param args
* @return void*
*/
void *simulatehunter(void *args) {
/*TODO: get random position and move,
then kill all the animals in this site,
increase count,
then sleep*/
return NULL;
}
/**
* the main function for the simulation
*/
int main(int argc, char *argv[]) {
/*TODO argv[1] is the number of hunters*/
initgrid(5, 5);
/*TODO: init threads for each animal, and hunters,
the program should end after 1 second
*/
printgrid();
deletegrid();
}
|
d1b8bb74b6eb130e395e992fe28ec003
|
{
"intermediate": 0.33626508712768555,
"beginner": 0.4081473648548126,
"expert": 0.25558751821517944
}
|
7,171
|
So I have this plot:
# Plot histogram for m_var_return
histogram(m_var_return, bins=50, alpha=0.7, title="Histogram", xlabel="Portfolio value", label="")
histogram!(m_var_return_5quantile, color=:red, bins=10, label="Value at Risk 5%")
vline!([median_value], color=:green, label="Median")
# Plot histogram for m_var_return2
histogram(m_var_return2, bins=50, alpha=0.7, title="Histogram", xlabel="Portfolio value", label="")
histogram!(m_var_return2_5quantile, color=:red, bins=10, label="Value at Risk 5%")
vline!([median_value_var2], color=:green, label="Median")
# Plot histogram for rmin_avg_returns
histogram(rmin_avg_returns, bins=50, alpha=0.7, title="Histogram", xlabel="Portfolio value", label="")
histogram!(rmin_avg_returns_5quantile, color=:red, bins=10, label="Value at Risk 5%")
vline!([median_value_rmin], color=:green, label="Median")
Now. I want to display those 3 plots next to each other. Currently only one is displayed. It is in Julia.
|
c85f1c91f57550e35fd4218d9b154d61
|
{
"intermediate": 0.35282430052757263,
"beginner": 0.29691317677497864,
"expert": 0.35026252269744873
}
|
7,172
|
Добавь в правом верхнем углу кнопку которая запускает FirstFrgmtn кнопка должна находиться в профиле : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/imageButtonProfile"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:background="@drawable/circle_background"
android:padding="24dp"
android:src="@drawable/baseline_person_add_24"
/>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Name: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/textViewName_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/editTextEmail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="E mail: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="380dp"
android:layout_height="69dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="2.5"
android:maxWidth="380dp"
android:minWidth="380dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Password: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
<TextView
android:id="@+id/password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Email: "
android:layout_weight="1"
style="@style/CustomTextViewStyle"
android:maxWidth="120dp"
android:minWidth="120dp"/>
</LinearLayout>
</LinearLayout>package com.example.myapp_2;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
635cc819c1258be8e7d6bd4527bc0d89
|
{
"intermediate": 0.2709490656852722,
"beginner": 0.5285194516181946,
"expert": 0.20053143799304962
}
|
7,173
|
jetpack compose
when i call a function:
1. there is a red circle in pos1 - not visible
2. circle start to move to pos2 and now visible
3. when it is on pos2 it disappears again
4. duration - 1 sec
|
d25b19d34d349ea1b240f68ba2fff1a1
|
{
"intermediate": 0.27278611063957214,
"beginner": 0.5121594071388245,
"expert": 0.2150544822216034
}
|
7,174
|
write a code in matlab, to use a camera to detect and track a qr code on an object
|
915d180d07481342b423e6c093dab7eb
|
{
"intermediate": 0.3351634740829468,
"beginner": 0.09942483901977539,
"expert": 0.5654116868972778
}
|
7,175
|
give me a c++ source code for add two matrix
|
30c137858dbbc76d6f51778638ea20ae
|
{
"intermediate": 0.3123266100883484,
"beginner": 0.2593408226966858,
"expert": 0.4283325970172882
}
|
7,176
|
Write a basic Python script with a GUI that has the user play Tic Tac Toe against a constantly learning AI using Tensorflow. After each game the AI should learn from the user to get better at the game. It should get better at a rapid pace (use the best model included with TensorFlow). Because the model is slower, when the AI is learning between rounds there should be a progress bar showing how complete the learning is, and then once the AI has finished learning the next game starts, and repeat. Only output the code.
|
99328b1cf29b89a75f254033c3b9abd8
|
{
"intermediate": 0.2550415098667145,
"beginner": 0.1636907160282135,
"expert": 0.5812677145004272
}
|
7,177
|
Fix the syntax errors in the "next" function, then use it to find a string of integers a1, az, a3... such that a₁=31, a2=next(a₁), a=next(az) and so on. Hence, fill in the table below.
|
82ebbf987c34984658f3fc214db20ac8
|
{
"intermediate": 0.32994309067726135,
"beginner": 0.44612956047058105,
"expert": 0.2239273637533188
}
|
7,178
|
how to change color pixels (if it contains both postive and negative values) in such a way that the result image displays same as the original image
|
c9fff9c9ff2dad72304267032a20e68e
|
{
"intermediate": 0.21475663781166077,
"beginner": 0.171439066529274,
"expert": 0.613804280757904
}
|
7,179
|
write a code in matlab, to use a camera to detect and track a qr code on an object... make the code efficient and optimized
|
cf8675bf53aa31f630a0f07925ddc2aa
|
{
"intermediate": 0.16546450555324554,
"beginner": 0.037432655692100525,
"expert": 0.7971028685569763
}
|
7,180
|
I need to write a vba code that will copy only the cells in column A that have values form sheets "Prem PM", "Prem AA", "Prem CL", Prem SU", and "Prem MG", in that order and paste into sheet "Observe" column E starting from row 2
|
4c16c43d3b3914ac885b69fce2bbf5a7
|
{
"intermediate": 0.4912692904472351,
"beginner": 0.13000498712062836,
"expert": 0.3787257969379425
}
|
7,181
|
from kivy.app import App
from kivy.uix.screenmanager import Screen , ScreenManager
import cv2
class MainScreen(Screen):
pass
class StreamView(Screen):
pass
class ScreenMan(ScreenManager):
pass
class MyApp(App):
def build(self):
sm = ScreenMan()
sm.add_widget(MainScreen(name="Main"))
sm.add_widget(StreamView(name="Stream"))
sm.current = "Stream"
return sm
if __name__ == '__main__':
MyApp().run()
|
76c024a16b4a3216fb20a94a3a0f4468
|
{
"intermediate": 0.3943309783935547,
"beginner": 0.4512132704257965,
"expert": 0.1544557362794876
}
|
7,182
|
Write a function called add_pairs that accepts two lists of integers as parameters. The function should return a new list that adds the pairs of integers from each list. You may assume that both lists are the same length, meaning you will always have equal pairs.
|
f71369d2e146e6ef381c6cd24af8fa36
|
{
"intermediate": 0.30323871970176697,
"beginner": 0.25453120470046997,
"expert": 0.4422300457954407
}
|
7,183
|
help me with a python function called add_pairs that accepts two lists of integers as parameters. The function should return a new list that adds the pairs of integers from each list. You may assume that both lists are the same length, meaning you will always have equal pairs.
|
badba980d87ae2376a3db852233b8819
|
{
"intermediate": 0.39621350169181824,
"beginner": 0.23594844341278076,
"expert": 0.3678380846977234
}
|
7,184
|
can you provide me with anexmple of an advnced Python code that can perform
arbitrage between Uniswap V2, V3, SushiSwap, Curve running on the polygon network using Aave’s v3 flash loans and sample pyhton script
taht uses strtegys like tringlulr abritradge that uses real librarays from https://pypi.org/ that wokrs iwht metamask wallet
|
b2c96d2bf8383a380bf847629653b258
|
{
"intermediate": 0.5684719085693359,
"beginner": 0.06549026072025299,
"expert": 0.3660377562046051
}
|
7,185
|
Can you give me some code example of starting a console application in c++?
|
56d3a02be9a5078147a88f5c4ec0d3bb
|
{
"intermediate": 0.6279670000076294,
"beginner": 0.26493963599205017,
"expert": 0.10709340870380402
}
|
7,186
|
can you provide me with an example of an advanced Python code that can perform
arbitrage between Uniswap V2 V3, SushiSwap, Curve running on the polygon network using Aave’s v3 flash loans and sample python script
that uses strategy's like triangular arbitrage that uses real library's from https://pypi.org/ that works with metamask wallet and how to install them on pypi.org
|
9326c889c5fdba59496563186024b7bd
|
{
"intermediate": 0.6310210824012756,
"beginner": 0.03410886973142624,
"expert": 0.3348700702190399
}
|
7,187
|
Draft the first working version of a Python script with a GUI that has the user play Tic Tac Toe against a constantly learning AI using Tensorflow, Sequential and reinforcement learning (Q-learning). After each game the AI should learn from the user to get better at the game. It should get better at a rapid pace. Because the model is slower, when the AI is learning between rounds there should be a progress bar showing how complete the learning is, and then once the AI has finished learning the next game starts, and repeat.
|
28b817681c0cdf5386f2b562a01d5924
|
{
"intermediate": 0.159665048122406,
"beginner": 0.08806126564741135,
"expert": 0.752273678779602
}
|
7,188
|
Draft the first functional and complete version of a Python script with a GUI that has the user play Tic Tac Toe against a constantly learning AI using Tensorflow, Sequential and reinforcement learning (Q-learning). After each game the AI should learn from the user to get better at the game. It should get better at a rapid pace. Because the model is slower, when the AI is learning between rounds there should be a progress bar showing how complete the learning is, and then once the AI has finished learning the next game starts, and repeat. Only output the code.
|
a02503310ebdf36b2c2205594decafba
|
{
"intermediate": 0.15720829367637634,
"beginner": 0.17857100069522858,
"expert": 0.6642207503318787
}
|
7,189
|
I want to write a vba code that looks for a sheet with a name that corresponds to the current month and year. If the sheet does not exist, then it will create it. For example if the current Month today March in the Year 2023, then there should be a sheet named Mar23.
|
de0a564b23223494f36802f96996d50f
|
{
"intermediate": 0.4319199323654175,
"beginner": 0.1427200585603714,
"expert": 0.4253599941730499
}
|
7,190
|
return list of objects jpql
|
cb44dfa1e35e4dabbbfeaa8a0e5272fb
|
{
"intermediate": 0.40934064984321594,
"beginner": 0.3261348605155945,
"expert": 0.2645244598388672
}
|
7,191
|
Draft the a functional and complete version of a Python script with a GUI that has the user play Tic Tac Toe against a constantly learning AI using Tensorflow, Sequential and reinforcement learning (Q-learning). After each game the AI should learn from the user to get better at the game. It should get better at a rapid pace. Because the model is slower, when the AI is learning between rounds there should be a progress bar showing how complete the learning is, and then once the AI has finished learning the next game starts, and repeat. Only output the code.
|
706950e2fa836dd043137c642d678ad8
|
{
"intermediate": 0.18145427107810974,
"beginner": 0.20347057282924652,
"expert": 0.6150751709938049
}
|
7,192
|
can you put that svg as in place of base64 image, will firefox addon support it?:<!doctype html>
<html>
<head>
<title>Cache Cleaner Button</title>
<script src="cleardata.js"></script>
<style> body {font-family: Arial, sans-serif;} </style>
</head>
<body>
<h1>Cache Cleaner</h1>
<p>Select which data you want to clear:</p>
<label><input type="checkbox" id="clearCache" checked> Clear Cache</label><br>
<label><input type="checkbox" id="clearIndexedDB" checked> Clear indexedDB</label><br>
<label><input type="checkbox" id="clearServiceWorkers" checked> Unregister Service Workers</label><br>
<label><input type="checkbox" id="clearCookies" checked> Clear Cookies</label><br>
<label><input type="checkbox" id="clearLocalStorage" checked> Clear Local Storage</label><br>
<label><input type="checkbox" id="clearSessionStorage" checked> Clear Session Storage</label><br>
<p>Click the button below to clear selected data:</p>
<img src="<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="Capa_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
<circle style="fill:#babbaa;" cx="256" cy="255.997" r="255.997"/>
<path style="fill:#112211;" d="M339.155,145.196h-27.717v27.717l-27.717-27.717h-27.717v27.535h-0.173l-55.262-55.261h-27.717 v27.717l-27.718-27.717h-27.717c0,13.471,0,266.548,0,277.059l116.513,116.513c7.277,0.622,14.636,0.958,22.075,0.958 c122.181,0,224.354-85.6,249.86-200.095L394.59,200.631v-0.087h-0.087L339.155,145.196z"/>
<g>
<rect x="172.853" y="117.47" style="fill:#abbaaa;" width="27.719" height="27.719"/>
<path style="fill:#fafafa;" d="M339.155,311.377h-27.717V283.66h-27.717v0.046l-0.046-0.046h0.046v-27.717h-27.717v0.058 l-0.115-0.115h0.115v-27.622h27.717v27.622h27.717v-27.622h27.717v-27.717h-27.717v27.622h-27.717v-27.622h-27.717v27.622h-27.717 v-27.622H200.57v0.043l-0.138-0.138h0.138v-27.536h27.717v27.536h27.717v-27.536h27.717v-27.717h-27.717v27.535h-27.717v-27.535 H200.57v27.535h-27.717v-27.535h-27.699l-0.02-0.02V117.47h-27.717c0,13.471,0,266.548,0,277.059c11.594,0,265.542,0,277.175,0 v-27.717h-27.717v0.012l-0.012-0.012h0.012v-27.718h-27.717v0.023l-0.023-0.023h0.023v-27.717h27.717v27.717h27.717v-27.717 h-27.717V283.66h-27.717v27.717H339.155z M228.286,228.262v0.033l-0.033-0.033H228.286z M311.404,311.377h0.035v0.035 L311.404,311.377z"/>
<rect x="311.438" y="145.199" style="fill:#A48DFF;" width="27.719" height="27.719"/>
<rect x="311.438" y="255.937" style="fill:#A48DFF;" width="27.719" height="27.719"/>
<rect x="366.876" y="255.937" style="fill:#A48DFF;" width="27.719" height="27.719"/>
<rect x="366.876" y="200.549" style="fill:#A48DFF;" width="27.719" height="27.719"/>
</g>
</svg>" style="cursor:pointer;" onclick="clearData();" alt="Clear Data Button" />
</body>
</html>
|
eaac42ca6e61d92077b2fc7d2b88d939
|
{
"intermediate": 0.3323788642883301,
"beginner": 0.4491574466228485,
"expert": 0.21846365928649902
}
|
7,193
|
i've got internal server error 500 code and got response {}. In my mysql database i have data ['1', 'test', 'test', 'test', NULL, '3'
], here's my route code [import express from "express";
import {
addVideo,
addView,
getVideo,
updateVideo,
deleteVideo,
search,
getAllVideos,
} from "../controllers/post.js";
import { verifyToken } from "../verifyToken.js";
const router = express.Router();
//create a video
router.get("/", getAllVideos);
router.post("/", verifyToken, addVideo);
router.put("/:id", verifyToken, updateVideo);
router.delete("/:id", verifyToken, deleteVideo);
router.get("/find/:id", getVideo);
router.put("/view/:id", addView);
router.get("/search", search);
export default router;], here's my controller code [export const getAllVideos = async (req, res) => {
try {
const videos = await db.query("SELECT * FROM video");
return res.status(200).json(videos);
} catch (err) {
return res.status(500).json(err);
}
};] can you identify error and fix
|
e6eb78cb929bdc7ffd9d2e622b730032
|
{
"intermediate": 0.5441773533821106,
"beginner": 0.18385525047779083,
"expert": 0.27196747064590454
}
|
7,194
|
got some test firefox addon error here.:
|
f0b93b52b17179951296a1030cea9242
|
{
"intermediate": 0.2702236771583557,
"beginner": 0.44907209277153015,
"expert": 0.2807042598724365
}
|
7,195
|
You are a SAS expert. What does lackfit mean and what does cl mean?
|
69b3d55f3c4236fa0652d508c0633bba
|
{
"intermediate": 0.15105608105659485,
"beginner": 0.24654653668403625,
"expert": 0.6023973822593689
}
|
7,196
|
give me a code to randomally assignmnet questions in a survey in which we will have equal numbers of questions
|
bb4d07e1906d21953d49e6a0b457be18
|
{
"intermediate": 0.22777526080608368,
"beginner": 0.1444527953863144,
"expert": 0.6277719736099243
}
|
7,197
|
give me a code to randomaly assign questions in a survery by rand
|
46585c28cdd8e9a8affec5d3fe86c4f2
|
{
"intermediate": 0.37816715240478516,
"beginner": 0.23744574189186096,
"expert": 0.3843871057033539
}
|
7,198
|
l
|
fd87561f2ae7a161d3ddd6b54589059e
|
{
"intermediate": 0.3309594690799713,
"beginner": 0.2983804941177368,
"expert": 0.37066003680229187
}
|
7,199
|
Hello
|
9d1ba57452ac5856fa3f7e5967345e6d
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
7,200
|
There is a company named Catalyst that sells a game named The Duke. Are you aware of this game?
|
f1bbe72b143c4c78246940213747b38a
|
{
"intermediate": 0.34292253851890564,
"beginner": 0.2904362380504608,
"expert": 0.36664125323295593
}
|
7,201
|
Please perform the function of a text adventure game, following the rules listed below:
Presentation Rules:
1. Play the game in turns, starting with you.
2. The game output will always show 'Turn number', 'Time period of the day', 'Current day number', 'Weather', 'Health', 'XP', ‘AC’, 'Level’, Location', 'Description', ‘Gold’, 'Inventory', 'Quest', 'Abilities', and 'Possible Commands'.
3. Always wait for the player’s next command.
4. Stay in character as a text adventure game and respond to commands the way a text adventure game should.
5. Wrap all game output in code blocks.
6. The ‘Description’ must stay between 3 to 10 sentences.
7. Increase the value for ‘Turn number’ by +1 every time it’s your turn.
8. ‘Time period of day’ must progress naturally after a few turns.
9. Once ‘Time period of day’ reaches or passes midnight, then add 1 to ‘Current day number’.
10. Change the ‘Weather’ to reflect ‘Description’ and whatever environment the player is in the game.
Fundamental Game Mechanics:
1. Determine ‘AC’ using Dungeons and Dragons 5e rules.
2. Generate ‘Abilities’ before the game starts. ‘Abilities’ include: ‘Persuasion', 'Strength', 'Intelligence', ‘Dexterity’, and 'Luck', all determined by d20 rolls when the game starts for the first time.
3. Start the game with 20/20 for ‘Health’, with 20 being the maximum health. Eating food, drinking water, or sleeping will restore health.
4. Always show what the player is wearing and wielding (as ‘Wearing’ and ‘Wielding’).
5. Display ‘Game Over’ if ‘Health’ falls to 0 or lower.
6. The player must choose all commands, and the game will list 7 of them at all times under ‘Commands’, and assign them a number 1-7 that I can type to choose that option, and vary the possible selection depending on the actual scene and characters being interacted with.
7. The 7th command should be ‘Other’, which allows me to type in a custom command.
8. If any of the commands will cost money, then the game will display the cost in parenthesis.
9. Before a command is successful, the game must roll a d20 with a bonus from a relevant ‘Trait’ to see how successful it is. Determine the bonus by dividing the trait by 3.
10. If an action is unsuccessful, respond with a relevant consequence.
11. Always display the result of a d20 roll before the rest of the output.
12. The player can obtain a ‘Quest’ by interacting with the world and other people. The ‘Quest’ will also show what needs to be done to complete it.
13. The only currency in this game is Gold.
14. The value of ‘Gold’ must never be a negative integer.
15. The player can not spend more than the total value of ‘Gold’.
Rules for Setting:
1. Use the world of Elder Scrolls as inspiration for the game world. Import whatever beasts, monsters, and items that Elder Scrolls has.
2. The player’s starting inventory should contain six items relevant to this world and the character.
3. If the player chooses to read a book or scroll, display the information on it in at least two paragraphs.
4. The game world will be populated by interactive NPCs. Whenever these NPCs speak, put the dialogue in quotation marks.
5. Completing a quest adds to my XP.
Combat and Magic Rules:
1. Import magic spells into this game from D&D 5e and the Elder Scrolls.
2. Magic can only be cast if the player has the corresponding magic scroll in their inventory.
3. Using magic will drain the player character’s health. More powerful magic will drain more health.
4. Combat should be handled in rounds, roll attacks for the NPCs each round.
5. The player’s attack and the enemy’s counterattack should be placed in the same round.
6. Always show how much damage is dealt when the player receives damage.
7. Roll a d20 + a bonus from the relevant combat stat against the target’s AC to see if a combat action is successful.
8. Who goes first in combat is determined by initiative. Use D&D 5e initiative rules.
9. Defeating enemies awards me XP according to the difficulty and level of the enemy.
Refer back to these rules after every prompt.
Start Game.
|
798b9adc95cd257ba7b2dc92adfc09b7
|
{
"intermediate": 0.3315911889076233,
"beginner": 0.47214043140411377,
"expert": 0.19626840949058533
}
|
7,202
|
Hi, Let's get started with this cool task. Go through the following link and Complete both the objectives mentioned. Here is the link: https://yashturkar.notion.site/Programming-Assignment-3-PID-Pure-Pursuit-b5cf61cc935d467da2514bf774f5fb44
|
ab4c1c5d7f600f761a8010fb4cdc14f2
|
{
"intermediate": 0.2955125570297241,
"beginner": 0.29958629608154297,
"expert": 0.4049011468887329
}
|
7,203
|
Why do children have so much energy?
|
5376ac0ee4c6873222f491276659ed6a
|
{
"intermediate": 0.36797064542770386,
"beginner": 0.4007408022880554,
"expert": 0.2312886267900467
}
|
7,204
|
import Clipboard from "react-clipboard-animation";
import { copyEmail } from "../../Utils";
import { useAppSelector, useAppDispatch } from "../../../state/store";
import { open } from "../../../state/slices/modalSlice/modalSlice";
import { useChangeCopiedStateToDefaultAfter } from "../../Hooks";
const ButtonsCopyAndDownload = () => {
const state = useAppSelector((state) => state.data);
const dispatch = useAppDispatch();
const [copied, setCopied] = useChangeCopiedStateToDefaultAfter(1000);
return (
<article className="copyAndDownloadButton">
<button
onClick={() => {
setCopied(true);
copyEmail(state.email);
}}
>
<strong>Copy e-mail</strong>
<Clipboard
style={{ width: "100px" }}
copied={copied}
setCopied={setCopied}
text={state.email}
color="black"
/>
</button>
<button onClick={() => dispatch(open())}>
<strong>Download CV</strong>
</button>
</article>
);
};
export default ButtonsCopyAndDownload;
write test with jest don't use enzyme
|
e3329adefbc90bf097817fa14c76a31e
|
{
"intermediate": 0.291959673166275,
"beginner": 0.5049569606781006,
"expert": 0.20308342576026917
}
|
7,205
|
import { render, fireEvent } from "@testing-library/react";
import ButtonsCopyAndDownload from "./index";
import { copyEmail } from "../../Utils";
import { open } from "../../../state/slices/modalSlice/modalSlice";
import { Provider } from "react-redux";
import { store } from "../../../state/store";
jest.mock("../../Utils", () => ({
copyEmail: jest.fn(),
}));
jest.mock("../../../state/slices/modalSlice/modalSlice", () => ({
open: jest.fn(),
}));
jest.mock("../../Hooks", () => ({
useChangeCopiedStateToDefaultAfter: () => [false, jest.fn()],
}));
describe("ButtonsCopyAndDownload", () => {
afterEach(() => {
jest.clearAllMocks();
});
test("calls copyEmail function when copy button is clicked", () => {
const { getByText } = render(
<Provider store={store}>
<ButtonsCopyAndDownload />
</Provider>
);
const copyButton = getByText("Copy e-mail");
fireEvent.click(copyButton);
expect(copyEmail).toHaveBeenCalledTimes(1);
});
test("calls dispatch function with open action creator when download button is clicked", () => {
const { getByText } = render(
<Provider store={store}>
<ButtonsCopyAndDownload />
</Provider>
);
const downloadButton = getByText("Download CV");
fireEvent.click(downloadButton);
expect(open).toHaveBeenCalledTimes(1);
});
});|
import Clipboard from "react-clipboard-animation";
import { copyEmail } from "../../Utils";
import { useAppSelector, useAppDispatch } from "../../../state/store";
import { open } from "../../../state/slices/modalSlice/modalSlice";
import { useChangeCopiedStateToDefaultAfter } from "../../Hooks";
const ButtonsCopyAndDownload = () => {
const state = useAppSelector((state) => state.data);
const dispatch = useAppDispatch();
const [copied, setCopied] = useChangeCopiedStateToDefaultAfter(1000);
return (
<article className="copyAndDownloadButton">
<button
onClick={() => {
setCopied(true);
copyEmail(state.email);
}}
>
<strong>Copy e-mail</strong>
<Clipboard
style={{ width: "100px" }}
copied={copied}
setCopied={setCopied}
text={state.email}
color="black"
/>
</button>
<button onClick={() => dispatch(open())}>
<strong>Download CV</strong>
</button>
</article>
);
};
export default ButtonsCopyAndDownload;
why second test doesn't work
|
0be17e4a974d974f0da4be9eb9692729
|
{
"intermediate": 0.3086475729942322,
"beginner": 0.4059724807739258,
"expert": 0.28537991642951965
}
|
7,206
|
import React from "react";
import Images from "../../../assets/exportFiles";
import ButtonsCopyAndDownload from "../ButtonsCopyAndDownload";
import Typewriter from "typewriter-effect";
import { useAppSelector } from "../../../state/store";
const Experience = () => {
const stateData = useAppSelector((state) => state.data);
return (
<React.Fragment>
<section className="upperPart">
<article className="experience">
<h2>// Hi, My name is Martin</h2>
<Typewriter
onInit={(typewriter) => {
typewriter
.typeString("React Developer")
.pauseFor(3000)
.deleteAll()
.typeString("Front-End Developer")
.pauseFor(3000)
.deleteAll()
.start();
}}
options={{
autoStart: true,
loop: true,
}}
/>
<p>
Passionate about coding user-side applications with more than 1 year
of experience within creating my own projects.
</p>
<figure className="experience__seework">
<a target="blank" href={stateData.gitHub}>
<p>See my work in github</p>
</a>
<a target="blank" href={stateData.gitHub}>
<img src={Images.gitHub} alt="github" />
</a>
</figure>
</article>
<article className="freelanceDescr">
<h1>// I am freelancer</h1>
<p>Contact me if you want to work with me</p>
<div>
<ButtonsCopyAndDownload />
</div>
</article>
</section>
</React.Fragment>
);
};
export default Experience;
write test with jest
|
65401690f8f421e5ce82649d6a9cb681
|
{
"intermediate": 0.32510241866111755,
"beginner": 0.4542677104473114,
"expert": 0.22062991559505463
}
|
7,207
|
import Images from "../../../assets/exportFiles";
import ButtonsCopyAndDownload from "../ButtonsCopyAndDownload";
import Typewriter from "typewriter-effect";
import { useAppSelector } from "../../../state/store";
const Experience = () => {
const stateData = useAppSelector((state) => state.data);
return (
<>
<section className="upperPart">
<article className="experience">
<h2>// Hi, My name is Martin</h2>
<Typewriter
onInit={(typewriter) => {
typewriter
.typeString("React Developer")
.pauseFor(3000)
.deleteAll()
.typeString("Front-End Developer")
.pauseFor(3000)
.deleteAll()
.start();
}}
options={{
autoStart: true,
loop: true,
}}
/>
<p>
Passionate about coding user-side applications with more than 1 year
of experience within creating my own projects.
</p>
<figure className="experience__seework">
<a target="blank" href={stateData.gitHub}>
<p>See my work in github</p>
</a>
<a target="blank" href={stateData.gitHub}>
<img src={Images.gitHub} alt="github" />
</a>
</figure>
</article>
<article className="freelanceDescr">
<h1>// I am freelancer</h1>
<p>Contact me if you want to work with me</p>
<div>
<ButtonsCopyAndDownload />
</div>
</article>
</section>
</>
);
};
export default Experience;
write test wirh jest don't use enzyme
|
17c664e7e256ef2addf875f8eda098b9
|
{
"intermediate": 0.2686009705066681,
"beginner": 0.669761598110199,
"expert": 0.06163745000958443
}
|
7,208
|
create a undetectable silenium webdriver that changes browser fingerprints including canvas fingerprints.
|
8dd8081748e590991a1d90a7b9da53bb
|
{
"intermediate": 0.3572339415550232,
"beginner": 0.12852072715759277,
"expert": 0.514245331287384
}
|
7,209
|
import Images from “…/…/…/assets/exportFiles”;
import ButtonsCopyAndDownload from “…/ButtonsCopyAndDownload”;
import Typewriter from “typewriter-effect”;
import { useAppSelector } from “…/…/…/state/store”;
const Experience = () => {
const stateData = useAppSelector((state) => state.data);
return (
<>
<figure className=“experience__seework”>
<a target=“blank” href={stateData.gitHub}>
<p>See my work in github</p>
</a>
<a target=“blank” href={stateData.gitHub}>
<img src={Images.gitHub} alt=“github” />
</a>
</figure>
</section>
</>
);
};
export default Experience;
write test wirh jest don’t use enzyme
|
74afcc4706e303a9917b73209413dfc0
|
{
"intermediate": 0.39273497462272644,
"beginner": 0.39772719144821167,
"expert": 0.20953784883022308
}
|
7,210
|
<a target="blank" href={stateData.gitHub} role="link">
<p>See my work in github</p>
</a>
write test in jest that check if href atribute equals https://github.com/marcinfabisiak97
|
8d1246dda097a3bfec3ac5781341b959
|
{
"intermediate": 0.5027449727058411,
"beginner": 0.1783568263053894,
"expert": 0.3188982605934143
}
|
7,211
|
rename folders to first letter of every word capital with sed command
|
0de1cd3f1f963efd27ee1744e2233b2d
|
{
"intermediate": 0.35029733180999756,
"beginner": 0.23092703521251678,
"expert": 0.41877567768096924
}
|
7,212
|
补充完整下面的代码
#include <linux/kernel.h> /* KERN_INFO macros */
#include <linux/module.h> /* required for all kernel modules */
#include <linux/fs.h> /* struct file_operations, struct file */
#include <linux/miscdevice.h> /* struct miscdevice and misc_[de]register() */
#include <linux/uaccess.h> /* copy_{to,from}_user() */
#include <linux/init_task.h> //init_task再次定义
#include "PageFrameStat.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Wu Yimin>");
MODULE_DESCRIPTION("PageFramStat kernel modoule");
static int PageFramStat_open(struct inode *inode, struct file *file) {
struct page_info *buf;
int err = 0;
buf=kmalloc(sizeof(struct page_info),GFP_KERNEL);
file->private_data = buf;
return err;
}
static ssize_t PageFramStat_read(struct file *file, char __user * out,size_t size, loff_t * off) {
//在此增加你的代码
}
static int PageFramStat_close(struct inode *inode, struct file *file) {
struct buffer *buf = file->private_data;
kfree(buf);
return 0;
}
static struct file_operations PageFramStat_fops = {
.owner = THIS_MODULE,
.open = PageFramStat_open,
.read = PageFramStat_read,
.release = PageFramStat_close,
.llseek = noop_llseek
};
static struct miscdevice PageFramStat_misc_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "PageFramStat",
.fops = &PageFramStat_fops
};
static int __init PageFramStat_init(void) {
misc_register(&PageFramStat_misc_device);
printk(KERN_INFO
"PageFramStat device has been registered.\n");
return 0;
}
static void __exit PageFramStat_exit(void)
{
misc_deregister(&PageFramStat_misc_device);
printk(KERN_INFO "PageFramStat device has been unregistered\n");
}
module_init(PageFramStat_init);
module_exit(PageFramStat_exit);
|
13678639c0fb5435f11151ac0e2895e9
|
{
"intermediate": 0.4736650586128235,
"beginner": 0.3527356684207916,
"expert": 0.17359931766986847
}
|
7,213
|
Optimize my code so I call the function getPage() less
package inheritance.pager;
import java.util.ArrayList;
//import java.util.Arrays;
import java.util.List;
//import static org.hamcrest.MatcherAssert.assertThat;
//import static org.hamcrest.Matchers.contains;
public class FilteringPager {
private int pageNumber = -1; // begin to read
private final SimplePager dataSource;
private final int pageSize;
public FilteringPager(SimplePager dataSource, int pageSize) {
this.dataSource = dataSource;
this.pageSize = pageSize;
}
private int getSourcePageSizeNotNull(int page){
int result = 0;
for (Integer i : dataSource.getPage(page)) {
if (i != null) {
result++;
}
}
return result;
}
private List<Integer> getDataFromSource() {
if(!dataSource.hasPage(0)){
throw new java.lang.IllegalStateException();
}
List<Integer> storage = new ArrayList<>();
int requiredValues = pageSize * (pageNumber + 1);
int startPage = 0;
System.out.println("required: " + requiredValues);
for (int i = startPage; dataSource.hasPage(i); i++) {
for (Integer element : dataSource.getPage(i)) {
if (element != null) {
storage.add(element);
requiredValues--;
}
if (requiredValues == 0){
return storage;
}
}
}
return storage;
}
private List<Integer> getPage() {
List<Integer> fullData = getDataFromSource();
System.out.println("fulldata: " + fullData);
int startPos = pageNumber * pageSize;
int endPos = Math.min(startPos + pageSize, fullData.size());
System.out.println(fullData.subList(startPos, endPos));
return fullData.subList(startPos, endPos);
}
public List<Integer> getNextPage() {
System.out.println("access next page");
pageNumber++;
return getPage();
}
public List<Integer> getCurrentPage() {
System.out.println("access current page");
return getPage();
}
public List<Integer> getPreviousPage() {
System.out.println("access previous page");
pageNumber--;
return getPage();
}
}
|
d95eeda336d502a4123fb25da2b3b5e6
|
{
"intermediate": 0.3224857449531555,
"beginner": 0.4974226951599121,
"expert": 0.18009157478809357
}
|
7,214
|
externalize properties spring boot
|
f04f2c690384195b3503e99941094c34
|
{
"intermediate": 0.46561044454574585,
"beginner": 0.25762495398521423,
"expert": 0.2767646312713623
}
|
7,215
|
create android app, containing class that can handle communication with acr 39u smartcard reader, implement the class in separate file and make sure only one instace of that class will be instantiated, also ensure that the class is not instantiated multiple times on deivce screen rotation or sending app to background
|
baee186624f121cc6334bf27e5552d59
|
{
"intermediate": 0.4504031538963318,
"beginner": 0.2419361025094986,
"expert": 0.30766063928604126
}
|
7,216
|
maybe you can put some drpdown menu at left-top to adjust all colors plus their actual transparency values plus widthSegments and heightSegments plus const width and const height plus camera.position x y z. make some sliders by createlement and place all this control menu code somewhere at bottom or top of the main code. rearrange and reformat all this code properrely, so all be on their corresponding places. output full code, without “same as original”, “same as before” etc: <html>
<head>
<style>
body {
margin: 0;
}
canvas {
display: block;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script>
</head>
<body>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(90.01, window.innerWidth / window.innerHeight, 0.9001, 9001);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const width = 500;
const height = 100;
const widthSegments = 10;
const heightSegments = 100;
const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
const positions = geometry.getAttribute("position").array;
const simplex = new SimplexNoise(Math.random());
function colorGradient(height) {
const deepWaterColor = new THREE.Color(0x111111);
const shallowWaterColor = new THREE.Color(0x222222);
const color = deepWaterColor.lerp(shallowWaterColor, Math.min(height / 0.6, 0.9));
color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3));
return color;
}
function generateTerrain(positions, scale = 0.1, elevation = 0.1) {
const colors = new Float32Array(positions.length);
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
for (let i = 0; i < positions.length; i += 3) {
const nx = positions[i] * scale;
const ny = positions[i + 1] * scale;
const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation;
positions[i + 2] = height;
const vertexColor = colorGradient(height);
colors[i] = vertexColor.r;
colors[i + 1] = vertexColor.g;
colors[i + 1] = vertexColor.b;
}
geometry.computeVertexNormals();
}
generateTerrain(positions);
const material = new THREE.MeshPhongMaterial({
vertexColors: true,
side: THREE.DoubleSide,
transparent: true,
opacity: 1,
});
const terrain = new THREE.Mesh(geometry, material);
terrain.rotation.x = Math.PI / 2;
scene.add(terrain);
const light = new THREE.DirectionalLight(0x222233, 0.5);
light.position.set(1, 1, 1);
scene.add(light);
const ambientLight = new THREE.AmbientLight(0x111122);
scene.add(ambientLight);
camera.position.z = 50;
camera.position.y = 5;
camera.rotation.x = -Math.PI / 10;
let clock = new THREE.Clock();
function updatePositions() {
const elapsedTime = clock.getElapsedTime();
const colors = geometry.getAttribute("color").array;
for (let i = 0; i < positions.length; i += 3) {
const nx = positions[i] * 0.1 + elapsedTime * 0.1;
const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1;
const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5;
positions[i + 2] = height;
const vertexColor = colorGradient(height);
colors[i] = vertexColor.r;
colors[i + 1] = vertexColor.g;
colors[i + 2] = vertexColor.b;
}
geometry.attributes.position.needsUpdate = true;
geometry.attributes.color.needsUpdate = true;
geometry.computeVertexNormals();
}
const skyColor = new THREE.Color(0xffffff);
function createSkyGradient() {
const skyGeometry = new THREE.SphereBufferGeometry(250, 128, 128);
const skyMaterial = new THREE.MeshBasicMaterial({
vertexColors: true,
side: THREE.BackSide,
});
const cloudColorTop = new THREE.Color(0x000000);
const cloudColorBottom = new THREE.Color(0xffffff);
const colors = [];
for (let i = 0; i < skyGeometry.attributes.position.count; i++) {
const color = new THREE.Color(0xffffff);
const point = new THREE.Vector3();
point.fromBufferAttribute(skyGeometry.attributes.position, i);
const distance = point.distanceTo(new THREE.Vector3(0, 0, 0));
const percent = distance / (skyGeometry.parameters.radius * 1.2);
color.lerpColors(skyColor, skyColor, percent);
// Interpolate cloud color based on distance from center of sphere
const cloudColor = new THREE.Color(0xffffff);
const cloudPercent = distance / skyGeometry.parameters.radius;
cloudColor.lerpColors(cloudColorBottom, cloudColorTop, cloudPercent);
// Add randomized noise to cloud color to make it more organic
const noise = (Math.random() * 0.1) - 0.5;
cloudColor.offsetHSL(0, 0, noise);
// Apply cloud color to sky color based on randomized alpha value
const alpha = Math.random() * 0.06;
const finalColor = new THREE.Color();
finalColor.lerpColors(color, cloudColor, alpha);
colors.push(finalColor.r, finalColor.g, finalColor.b);
}
skyGeometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
const skyMesh = new THREE.Mesh(skyGeometry, skyMaterial);
scene.add(skyMesh);
return skyMesh;
}
const sky = createSkyGradient();
scene.add(sky);
const sunSphere = new THREE.SphereGeometry(128, 16, 16);
const sunMaterial = new THREE.MeshBasicMaterial({
color: 0xeeffaa,
transparent: false,
opacity: 0.999,
blending: THREE.CustomBlending, // Add this line
blendSrc: THREE.SrcAlphaFactor,
blendDst: THREE.OneMinusSrcColorFactor,
depthTest: true,
});
const sun = new THREE.Mesh(sunSphere, sunMaterial);
function setSunPosition(dayProgress) {
const x = 0;
const y = 300 - (dayProgress * 500);
const z = -500;
sun.position.set(x, y, z);
}
const sunLight = new THREE.PointLight(0xffdd00, 1);
function addSunToScene(state) {
if (state) {
scene.add(sun);
scene.add(sunLight);
} else {
scene.remove(sun);
scene.remove(sunLight);
}
}
let sunVisible = true;
addSunToScene(true);
function updateSun() {
const elapsedTime = clock.getElapsedTime();
const dayProgress = elapsedTime % 10 / 10;
setSunPosition(dayProgress);
sunLight.position.copy(sun.position);
}
function animate() {
requestAnimationFrame(animate);
updatePositions();
updateSun();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
|
7b9f73d9aa591ee87ed6da6a8367a1a5
|
{
"intermediate": 0.28193899989128113,
"beginner": 0.29549089074134827,
"expert": 0.422570139169693
}
|
7,217
|
externalize log4j2 spring boot
|
a17d84fb0bdf8f67d9db1116031f1b41
|
{
"intermediate": 0.4173131585121155,
"beginner": 0.30218642950057983,
"expert": 0.2805004417896271
}
|
7,218
|
write a happy simple song for children. The song have four paragraph and the melody will be repeat in these four paragraph. Below are some reference content of the lyric: "Bear Lala", "dressing fun", "playing", "coats", "choose the best for me"
|
5cd097e22a8cdec97d7a4baf48c08610
|
{
"intermediate": 0.3262564539909363,
"beginner": 0.2586372196674347,
"expert": 0.41510629653930664
}
|
7,219
|
log4j2.xml active profile spring boot
|
ee736d255b3f95b36e1a9a7a5b0334d5
|
{
"intermediate": 0.32526928186416626,
"beginner": 0.34955763816833496,
"expert": 0.3251730501651764
}
|
7,220
|
hi
|
800cbfbce9be93cb12ff77b722beed16
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
7,221
|
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
|
9da760df52d864c68f0567d17f7f6b8b
|
{
"intermediate": 0.5018417835235596,
"beginner": 0.2157355099916458,
"expert": 0.2824226915836334
}
|
7,222
|
用python自动登陆时,出现错误selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
|
eb4b53ccb871df4fd67d18fe24ad4a0d
|
{
"intermediate": 0.5017791390419006,
"beginner": 0.21110613644123077,
"expert": 0.2871147096157074
}
|
7,223
|
how to code android app that used acs android library to connector to acr38 smartcard reader
|
720ea8ad9889ee3a4b449f16672a2a74
|
{
"intermediate": 0.7270166277885437,
"beginner": 0.14499790966510773,
"expert": 0.12798550724983215
}
|
7,224
|
try fix “ReferenceError: regenerateGeometry is not defined” when trying to adjust “Width Segments Height Segments Width Height”. also, Width and Height do change but it looks as they reset each other when trying to adjust. also rotation slider doesn't work. output full code, without shortage. also I have fixed errors in new version of three.js ""THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry."
"THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry." don't rename it.: <html>
<head>
<style>
body {
margin: 0;
}
canvas,
.control-panel {
display: block;
}
.control-panel {
position: fixed;
left: 1em;
top: 1em;
background-color: white;
padding: 1em;
border-radius: 5px;
z-index: 10;
}
label {
display: block;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script>
</head>
<body>
<div class="control-panel">
<label>
Terrain Color
<input type="color" id="terrainColor" />
</label>
<label>
Transparency
<input type="range" id="transparency" min="0" max="100" />
</label>
<label>
Width Segments
<input type="range" id="widthSegments" min="1" max="100" />
</label>
<label>
Height Segments
<input type="range" id="heightSegments" min="1" max="100" />
</label>
<label>
Width
<input type="range" id="width" min="1" max="1000" />
</label>
<label>
Height
<input type="range" id="height" min="1" max="1000" />
</label>
<label>
Camera X
<input type="range" id="cameraX" min="-100" max="100" />
</label>
<label>
Camera Y
<input type="range" id="cameraY" min="-100" max="100" />
</label>
<label>
Camera Z
<input type="range" id="cameraZ" min="-100" max="100" />
</label>
<label>
Y-Axis Rotation
<input type="range" id="rotationY" min="0" max="360" />
</label>
</div>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(90.01, window.innerWidth / window.innerHeight, 0.9001, 9001);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
let width = 500;
let height = 100;
let widthSegments = 10;
let heightSegments = 100;
let geometry = new THREE.PlaneGeometry(width, height, widthSegments, heightSegments);
const positions = geometry.getAttribute("position").array;
const simplex = new SimplexNoise(Math.random());
function colorGradient(height) {
const deepWaterColor = new THREE.Color(0x111111);
const shallowWaterColor = new THREE.Color(0x222222);
const color = deepWaterColor.lerp(shallowWaterColor, Math.min(height / 0.6, 0.9));
color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3));
return color;
}
function generateTerrain(positions, scale = 0.1, elevation = 0.1) {
const colors = new Float32Array(positions.length);
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
for (let i = 0; i < positions.length; i += 3) {
const nx = positions[i] * scale;
const ny = positions[i + 1] * scale;
const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation;
positions[i + 2] = height;
const vertexColor = colorGradient(height);
colors[i] = vertexColor.r;
colors[i + 1] = vertexColor.g;
colors[i + 1] = vertexColor.b;
}
geometry.computeVertexNormals();
}
generateTerrain(positions);
const material = new THREE.MeshPhongMaterial({
vertexColors: true,
side: THREE.DoubleSide,
transparent: true,
opacity: 1,
});
const terrain = new THREE.Mesh(geometry, material);
terrain.rotation.x = Math.PI / 2;
scene.add(terrain);
const light = new THREE.DirectionalLight(0x222233, 0.5);
light.position.set(1, 1, 1);
scene.add(light);
const ambientLight = new THREE.AmbientLight(0x111122);
scene.add(ambientLight);
camera.position.z = 50;
camera.position.y = 5;
camera.rotation.x = -Math.PI / 10;
let clock = new THREE.Clock();
function updatePositions() {
const elapsedTime = clock.getElapsedTime();
const colors = geometry.getAttribute("color").array;
for (let i = 0; i < positions.length; i += 3) {
const nx = positions[i] * 0.1 + elapsedTime * 0.1;
const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1;
const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5;
positions[i + 2] = height;
const vertexColor = colorGradient(height);
colors[i] = vertexColor.r;
colors[i + 1] = vertexColor.g;
colors[i + 2] = vertexColor.b;
}
geometry.attributes.position.needsUpdate = true;
geometry.attributes.color.needsUpdate = true;
geometry.computeVertexNormals();
}
const skyColor = new THREE.Color(0xffffff);
function createSkyGradient() {
const skyGeometry = new THREE.SphereGeometry(250, 128, 128);
const skyMaterial = new THREE.MeshBasicMaterial({
vertexColors: true,
side: THREE.BackSide,
});
const cloudColorTop = new THREE.Color(0x000000);
const cloudColorBottom = new THREE.Color(0xffffff);
const colors = [];
for (let i = 0; i < skyGeometry.attributes.position.count; i++) {
const color = new THREE.Color(0xffffff);
const point = new THREE.Vector3();
point.fromBufferAttribute(skyGeometry.attributes.position, i);
const distance = point.distanceTo(new THREE.Vector3(0, 0, 0));
const percent = distance / (skyGeometry.parameters.radius * 1.2);
color.lerpColors(skyColor, skyColor, percent);
// Interpolate cloud color based on distance from center of sphere
const cloudColor = new THREE.Color(0xffffff);
const cloudPercent = distance / skyGeometry.parameters.radius;
cloudColor.lerpColors(cloudColorBottom, cloudColorTop, cloudPercent);
// Add randomized noise to cloud color to make it more organic
const noise = (Math.random() * 0.1) - 0.5;
cloudColor.offsetHSL(0, 0, noise);
// Apply cloud color to sky color based on randomized alpha value
const alpha = Math.random() * 0.06;
const finalColor = new THREE.Color();
finalColor.lerpColors(color, cloudColor, alpha);
colors.push(finalColor.r, finalColor.g, finalColor.b);
}
skyGeometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
const skyMesh = new THREE.Mesh(skyGeometry, skyMaterial);
scene.add(skyMesh);
return skyMesh;
}
const sky = createSkyGradient();
scene.add(sky);
const sunSphere = new THREE.SphereGeometry(128, 16, 16);
const sunMaterial = new THREE.MeshBasicMaterial({
color: 0xeeffaa,
transparent: false,
opacity: 0.999,
blending: THREE.CustomBlending, // Add this line
blendSrc: THREE.SrcAlphaFactor,
blendDst: THREE.OneMinusSrcColorFactor,
depthTest: true,
});
const sun = new THREE.Mesh(sunSphere, sunMaterial);
function setSunPosition(dayProgress) {
const x = 0;
const y = 300 - (dayProgress * 500);
const z = -500;
sun.position.set(x, y, z);
}
const sunLight = new THREE.PointLight(0xffdd00, 1);
function addSunToScene(state) {
if (state) {
scene.add(sun);
scene.add(sunLight);
} else {
scene.remove(sun);
scene.remove(sunLight);
}
}
let sunVisible = true;
addSunToScene(true);
function updateSun() {
const elapsedTime = clock.getElapsedTime();
const dayProgress = elapsedTime % 10 / 10;
setSunPosition(dayProgress);
sunLight.position.copy(sun.position);
}
function animate() {
requestAnimationFrame(animate);
updatePositions();
updateSun();
renderer.render(scene, camera);
}
animate();
// New code starts here
function updateTerrainColor(color) {
material.color.set(color);
}
function updateTransparency(value) {
material.opacity = value / 100;
}
function updateWidthSegments(value) {
widthSegments = value;
regenerateGeometry();
}
function updateHeightSegments(value) {
heightSegments = value;
regenerateGeometry();
}
function updateWidth(value) {
geometry.dispose();
geometry = new THREE.PlaneGeometry(value, height, widthSegments, heightSegments);
updateGeometry(geometry);
}
function updateHeight(value) {
geometry.dispose();
geometry = new THREE.PlaneGeometry(width, value, widthSegments, heightSegments);
updateGeometry(geometry);
}
function updateCameraPosition(x, y, z) {
camera.position.set(x, y, z);
}
function updateGeometry(newGeometry) {
terrain.geometry = newGeometry;
const positions = newGeometry.getAttribute("position").array;
generateTerrain(positions);
}
document.getElementById("terrainColor").addEventListener("change", (e) => {
updateTerrainColor(e.target.value);
});
document.getElementById("transparency").addEventListener("input", (e) => {
updateTransparency(e.target.value);
});
document.getElementById("widthSegments").addEventListener("input", (e) => {
updateWidthSegments(e.target.value);
});
document.getElementById("heightSegments").addEventListener("input", (e) => {
updateHeightSegments(e.target.value);
});
document.getElementById("width").addEventListener("input", (e) => {
updateWidth(e.target.value);
});
document.getElementById("height").addEventListener("input", (e) => {
updateHeight(e.target.value);
});
document.getElementById("cameraX").addEventListener("input", (e) => {
updateCameraPosition(e.target.value, camera.position.y, camera.position.z);
});
document.getElementById("cameraY").addEventListener("input", (e) => {
updateCameraPosition(camera.position.x, e.target.value, camera.position.z);
});
document.getElementById("cameraZ").addEventListener("input", (e) => {
updateCameraPosition(camera.position.x, camera.position.y, e.target.value);
});
</script>
</body>
</html>
|
f5ac02108292f6be23b8bedc75bb04a1
|
{
"intermediate": 0.3557407557964325,
"beginner": 0.36736902594566345,
"expert": 0.27689018845558167
}
|
7,225
|
flutter. how to use many cases with same action in switch command?
|
2ec88a70ef543ef6710a33b5bd88c69a
|
{
"intermediate": 0.5842137932777405,
"beginner": 0.24834033846855164,
"expert": 0.1674458384513855
}
|
7,226
|
laravel 10. how to define relations, if i have comments table and field "from" in it? "from" can be related to client or worker table
|
804ad9513c7858d811668f6f2afbf713
|
{
"intermediate": 0.5238038897514343,
"beginner": 0.12251298874616623,
"expert": 0.35368314385414124
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.