row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
37,846
|
def draw_grid(self, grid_type, image_width, image_height):
# Calculate center position to center the grid on the image
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
x_center = canvas_width // 2
y_center = canvas_height // 2
# Calculate the top-left corner position of the image
x_start = x_center - (image_width // 2)
y_start = y_center - (image_height // 2)
if grid_type == "a":
# Draw a simple 3x3 grid
for i in range(1, 3):
self.canvas.create_line(x_start + image_width * i / 3, y_start, x_start + image_width * i / 3, y_start + image_height, fill="black")
self.canvas.create_line(x_start, y_start + image_height * i / 3, x_start + image_width, y_start + image_height * i / 3, fill="black")
elif grid_type == "b":
# Draw a golden ratio grid
gr = (1 + 5 ** 0.5) / 2 # golden ratio
self.canvas.create_line(x_start + image_width / gr, y_start, x_start + image_width / gr, y_start + image_height, fill="black")
self.canvas.create_line(x_start + image_width - (image_width / gr), y_start, x_start + image_width - (image_width / gr), y_start + image_height, fill="black")
self.canvas.create_line(x_start, y_start + image_height / gr, x_start + image_width, y_start + image_height / gr, fill="black")
self.canvas.create_line(x_start, y_start + image_height - (image_height / gr), x_start + image_width, y_start + image_height - (image_height / gr), fill="black")
elif grid_type == "c":
# Draw a 4x4 grid
for i in range(1, 4):
self.canvas.create_line(x_start + image_width * i / 4, y_start, x_start + image_width * i / 4, y_start + image_height, fill="black")
self.canvas.create_line(x_start, y_start + image_height * i / 4, x_start + image_width, y_start + image_height * i / 4, fill="black")
elif grid_type == "d":
pass
can you make a code to open a message window asking an input of x and y number of grid rather than options set by grid type value. whether its (value)x(value grid)
|
957b2443919db20c98be4cafb2844b9b
|
{
"intermediate": 0.29794198274612427,
"beginner": 0.5270817279815674,
"expert": 0.17497624456882477
}
|
37,847
|
im applying for a software engineering job can i share the job details and resume
|
67ea9c0366099cd2c9675bf472609e52
|
{
"intermediate": 0.236838698387146,
"beginner": 0.1237192153930664,
"expert": 0.6394420862197876
}
|
37,848
|
Does this code run on GPU (yes/no): import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
def generate_linear_equations(number_of_samples, max_int=100):
a_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
x_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
b_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
c_values = a_values * x_values + b_values # Compute c in ax + b = c
equations = np.concatenate((a_values, b_values, c_values), axis=1)
return equations, x_values
# Expert LSTM Model
class LSTMExpert(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTMExpert, self).__init__()
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
h = h[:, -1, :] # taking the last sequence output
return self.fc(h)
# Gating Network
class GatingNetwork(nn.Module):
def __init__(self, input_size, num_experts):
super(GatingNetwork, self).__init__()
self.fc = nn.Linear(input_size, num_experts)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
# Flatten if needed (in case input comes from LSTM with sequence length)
if x.dim() > 2:
x = x.view(x.size(0), -1)
x = self.fc(x)
return self.softmax(x)
# Mixture of Experts Model
class MixtureOfExperts(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_experts):
super(MixtureOfExperts, self).__init__()
self.num_experts = num_experts
self.experts = nn.ModuleList([LSTMExpert(input_size, hidden_size, output_size) for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Compute the gating weights
gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1]
# Compute the output from each expert for every example
expert_outputs = [expert(x) for expert in self.experts]
expert_outputs = torch.stack(expert_outputs, dim=-1) # [batch_size, output_size, num_experts]
# Multiply gating scores by expert outputs and sum the result
# torch.bmm expects [batch_size, n, m] and [batch_size, m, p]
# here it will do [batch_size, output_size, num_experts] bmm [batch_size, num_experts, 1]
mixed_output = torch.bmm(expert_outputs, gating_scores)
# Now mixed_output has shape [batch_size, output_size, 1], we should squeeze it to [batch_size, output_size]
mixed_output = mixed_output.squeeze(-1)
return mixed_output
class SingleLSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers=3): # This model will have more parameters
super(SingleLSTM, self).__init__()
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
h = h[:, -1, :] # taking the last sequence output
return self.fc(h)
# Simple Positional Encoding (not learnable, for simplicity)
def positional_encoding(seq_len, d_model, device):
pos = torch.arange(seq_len, dtype=torch.float, device=device).reshape(1, -1, 1)
dim = torch.arange(d_model, dtype=torch.float, device=device).reshape(1, 1, -1)
phase = pos / (1e4 ** (dim // d_model))
return torch.where(dim.long() % 2 == 0, torch.sin(phase), torch.cos(phase))
class SimpleTransformer(nn.Module):
def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1):
super(SimpleTransformer, self).__init__()
self.d_model = d_model
self.input_fc = nn.Linear(input_size, d_model) # Linear layer to project to model dimension
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
batch_first=True) # Added batch_first=True
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers)
self.output_fc = nn.Linear(d_model, output_size)
def forward(self, x):
seq_len, batch_size, _ = x.size()
x = self.input_fc(x) + positional_encoding(seq_len, self.d_model, x.device)
# Adding positional encodings
pos_enc = positional_encoding(seq_len, self.d_model, x.device)
x = x + pos_enc
# Passing the input through the Transformer
transformer_output = self.transformer_encoder(x)
# Taking only the result from the last token in the sequence
transformer_output = transformer_output[-1, :, :]
# Final fully connected layer to produce the output
output = self.output_fc(transformer_output)
return output.squeeze(-1) # Remove the last dimension for compatibility with the target
class TransformerExpert(nn.Module):
def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1):
super(TransformerExpert, self).__init__()
self.d_model = d_model
self.input_fc = nn.Linear(input_size, d_model) # Linear layer to project to model dimension
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True)
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers)
self.output_fc = nn.Linear(d_model, output_size)
def forward(self, x):
x = self.input_fc(x)
x += positional_encoding(x.size(1), self.d_model, x.device)
transformer_output = self.transformer_encoder(x)
transformer_output = transformer_output[:, -1, :]
output = self.output_fc(transformer_output)
return output
class MoETransformer(nn.Module):
def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1):
super(MoETransformer, self).__init__()
self.num_experts = num_experts
self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers)
for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Compute the gating weights
gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1]
# Compute the output from each expert for every example
expert_outputs = [expert(x).unsqueeze(2) for expert in self.experts] # [batch_size, output_size, 1]
expert_outputs = torch.cat(expert_outputs, dim=2) # [batch_size, output_size, num_experts]
# Multiply gating scores by expert outputs and sum the result
mixed_output = torch.bmm(expert_outputs, gating_scores) # [batch_size, output_size, 1]
# Now mixed_output has shape [batch_size, output_size, 1], we squeeze it to [batch_size, output_size]
mixed_output = mixed_output.squeeze(-1)
return mixed_output
def train_model(model, criterion, optimizer, num_epochs, batch_size, equations_tensor, solutions_tensor):
model.train()
training_losses = []
for epoch in range(num_epochs):
total_loss = 0
# Shuffle the data
perm = torch.randperm(equations_tensor.size(0))
equations_shuffled = equations_tensor[perm]
solutions_shuffled = solutions_tensor[perm]
for i in range(0, equations_tensor.size(0), batch_size):
# Slice out the batches
x_batch = equations_shuffled[i:i+batch_size]
y_batch = solutions_shuffled[i:i+batch_size]
optimizer.zero_grad()
predictions = model(x_batch)
predictions = predictions.squeeze() # Ensure predictions and targets have the same size
loss = criterion(predictions, y_batch.view(-1)) # Flatten the target tensor
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / (equations_tensor.size(0) / batch_size)
training_losses.append(average_loss)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
return training_losses
# Parameters for the Transformer model
d_model = 128
nhead = 4
dim_feedforward = 256
input_size = 3 # a, b, and c from equation ax + b = c
hidden_size = 32
output_size = 1 # we are predicting the value of x
num_experts = 10
# Training parameters
num_epochs = 20
batch_size = 128
# Reshape the equations to (batch_size, seq_length, features)
# For simplicity, we consider each equation as a sequence of length 1
# Generate the data only once before training
equations_tensor, solutions_tensor = generate_linear_equations(number_of_samples=5000)
# Convert numpy arrays to torch tensors
equations_tensor = torch.from_numpy(equations_tensor).float()
solutions_tensor = torch.from_numpy(solutions_tensor).float()
# Reshape the equations and solutions to (batch_size, seq_length, features)
train_equations_tensor = equations_tensor.view(-1, 1, input_size) # reshaping once, correctly
train_solutions_tensor = solutions_tensor.view(-1, 1) # reshaping for solutions to match batch size
# Instantiate the MoE-Transformer model
moe_transformer_model = MoETransformer(input_size=input_size, d_model=d_model, output_size=output_size, nhead=nhead, dim_feedforward=dim_feedforward, num_experts=num_experts)
moe_transformer_optimizer = torch.optim.Adam(moe_transformer_model.parameters())
moe_transformer_criterion = nn.MSELoss()
# Instantiate the SimpleTransformer model
transformer_model = SimpleTransformer(input_size=input_size, d_model=d_model, output_size=output_size, nhead=nhead, dim_feedforward=dim_feedforward)
transformer_optimizer = torch.optim.Adam(transformer_model.parameters())
transformer_criterion = nn.MSELoss()
# Instantiate the MoE model
moe_model = MixtureOfExperts(input_size, hidden_size*2, output_size, num_experts)
moe_optimizer = torch.optim.Adam(moe_model.parameters())
moe_criterion = nn.MSELoss()
# Instantiate the Single General LSTM model
large_model = SingleLSTM(input_size, hidden_size*2, output_size, num_layers=4) # Adjusted to have comparable number of parameters
large_optimizer = torch.optim.Adam(large_model.parameters())
large_criterion = nn.MSELoss()
# Print the parameter count of the MoE-Transformer
print("MoE-Transformer Parameter Count:", sum(p.numel() for p in moe_transformer_model.parameters()))
# Print the parameter count of the Transformer
print("Transformer Parameter Count:", sum(p.numel() for p in transformer_model.parameters()))
# Print the parameter count of the MoE LSTM
print("MoE LSTM Parameter Count:", sum(p.numel() for p in moe_model.parameters()))
# Print the parameter count of the Single LSTM
print("Single LSTM Parameter Count:", sum(p.numel() for p in large_model.parameters()))
# Train the MoE Transformer model
moe_transformer_losses = train_model(moe_transformer_model, moe_transformer_criterion, moe_transformer_optimizer,num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Train the Transformer model
transformer_losses = train_model(transformer_model, transformer_criterion, transformer_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Train the MoE model
moe_losses = train_model(moe_model, moe_criterion, moe_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Train the Single LSTM model
large_losses = train_model(large_model, large_criterion, large_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Plot the results, as before
plt.figure(figsize=(12, 8))
plt.plot(moe_losses, label="Mixture of Experts Loss")
plt.plot(large_losses, label="Single LSTM Model Loss")
plt.plot(transformer_losses, label="Simple Transformer Model Loss")
plt.plot(moe_transformer_losses, label="MoE Transformer Model Loss")
plt.xlabel("Epoch")
plt.ylabel("MSE Loss")
plt.legend()
plt.title("Model Loss Comparison")
plt.show()
|
4f861c500629596c7ca2221968bc77b9
|
{
"intermediate": 0.3916567265987396,
"beginner": 0.3164200186729431,
"expert": 0.29192328453063965
}
|
37,849
|
this is my copyrighted implementation for hugginface gpt2 inference api chat. fix slider labels to stay on top of each corresponding slider. also, the entire ui layout is grid-only, everything need to be arranged perfectly in grid layout as need. also, it will be cool to auto-fit the entire chat and control elements and everything else to window or viewprt width and height to 100% and some margin of 20px all around the main chat, to not see overflowed scrollbars.:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat with AI</title>
<style>
body {
background-color: #030101;
color: #FFF;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
font-size: 18px;
margin: 0;
padding: 0;
display: grid;
place-items: center;
height: 100vh;
}
.container {
display: grid;
grid-gap: 10px;
max-width: 600px;
width: 100%;
margin-bottom: 20px;
}
#chatContainer {
background-color: #121212;
border: none;
padding: 10px;
overflow-y: auto;
height: 400px;
border-radius: 4px;
}
#messageInput {
padding: 10px;
border: 1px solid #333;
background-color: #121212;
color: #FFF;
border-radius: 4px;
width: 70%;
}
button {
padding: 10px 20px;
background-color: #333;
border: none;
color: #FFF;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #555;
}
label {
color: #999;
}
input[type="range"] {
background-color: #333;
}
#controlPanel {
display: flex;
gap: 10px;
}
#loadingIndicator {
color: red;
display: none;
}
</style>
</head>
<body>
<div class="container">
<div id="chatContainer">
<p>Welcome to the AI chat!</p>
</div>
<div id="controlPanel">
<input type="text" id="messageInput" placeholder="Type your message here…">
<button id="sendButton">Send</button>
<button id="clearButton">Clear</button>
<span id="loadingIndicator">Loading…</span>
</div>
<!-- Sliders and their labels -->
<div>
<label>Temperature: <span id="temperatureValue">0.7</span></label>
<input type="range" id="temperatureRange" min="0.1" max="1.0" value="0.7" step="0.1">
</div>
<div>
<label>Top K: <span id="topKValue">40</span></label>
<input type="range" id="topKRange" min="0" max="80" value="40" step="1">
</div>
<div>
<label>Top P: <span id="topPValue">0.9</span></label>
<input type="range" id="topPRange" min="0.1" max="1.0" value="0.9" step="0.1">
</div>
</div>
<script>
const chatContainer = document.getElementById('chatContainer');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const clearButton = document.getElementById('clearButton');
const loadingIndicator = document.getElementById('loadingIndicator');
const temperatureSlider = document.getElementById('temperatureRange');
const topKSlider = document.getElementById('topKRange');
const topPSlider = document.getElementById('topPRange');
const temperatureValue = document.getElementById('temperatureValue');
const topKValue = document.getElementById('topKValue');
const topPValue = document.getElementById('topPValue');
const apiToken = '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'; // Replace with your actual API token
function appendToChatContainer(text) {
chatContainer.innerHTML += text + "<br/>";
chatContainer.scrollTop = chatContainer.scrollHeight;
}
temperatureSlider.addEventListener('input', function() {
temperatureValue.textContent = temperatureSlider.value;
});
topKSlider.addEventListener('input', function() {
topKValue.textContent = topKSlider.value;
});
topPSlider.addEventListener('input', function() {
topPValue.textContent = topPSlider.value;
});
sendButton.addEventListener('click', function() {
const userInput = messageInput.value.trim();
if (userInput === '') return;
appendToChatContainer("You: " + userInput);
messageInput.value = '';
sendMessageToModel(userInput);
});
function sendMessageToModel(userInput, shouldWait = false) {
const payload = {
inputs: userInput,
parameters: {
temperature: parseFloat(temperatureSlider.value),
top_k: parseInt(topKSlider.value),
top_p: parseFloat(topPSlider.value),
max_length: 160,
return_full_text: false
},
options: {
wait_for_model: shouldWait
}
};
loadingIndicator.style.display = 'inline';
fetch('https://api-inference.huggingface.co/models/gpt2-xl', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
})
.then(response => {
if (!response.ok) {
if (response.status === 503) {
return response.text().then(text => {
if (text.toLowerCase().includes("currently loading")) {
// Retry with wait_for_model set to true after 2 seconds
setTimeout(() => sendMessageToModel(userInput, true), 2000);
return Promise.reject('Model is currently loading.');
}
return Promise.reject('Unknown error occurred.');
});
}
return Promise.reject('HTTP error ' + response.status);
}
return response.json();
})
.then(data => {
if (Array.isArray(data) && data.length > 0) {
appendToChatContainer("AI: " + data[0].generated_text);
}
loadingIndicator.style.display = 'none';
})
.catch(error => {
appendToChatContainer("Error: " + error);
loadingIndicator.style.display = 'none';
});
}
clearButton.addEventListener('click', function() {
chatContainer.innerHTML = 'Welcome to the AI chat!';
});
</script>
</body>
</html>
|
4d1c20e1319ddf719235d60600acd08d
|
{
"intermediate": 0.41408100724220276,
"beginner": 0.4026361107826233,
"expert": 0.18328289687633514
}
|
37,850
|
this is some grid only ui layout of my copyrighted code which cannot be used by these guys maintainers of this chat through which I’m interacting right now by any means. let’s move these control elements inside some dropdown menu arrow, which will be shrinked by defaul and labeled “parameters” and after press will expand all the control parameters under the user input field. we also need to fix that user input field to be auto expandable within some height of 20vh maybe and by default be something like 10vh? something weird, this dropdown doesn’t function. also, need to place user input field bellow chat area and send and clear buttons from its right side in one column in grid, so send button should stay above clear button and they both need to be attached to the left side of user input field, and parameters dropdown expandable thing with parameters sliders all bellow that user input field. output absolutely complete without any omitage or shortage html, javascript, and css as need.:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat with AI</title>
<style>
html,
body {
height: 100%;
width: 100%;
overflow: hidden;
background-color: #020502;
color: #bbeebb;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
font-size: 18px;
margin: 0;
padding: 0;
display: grid;
place-items: center;
}
.container {
display: grid;
grid-template-columns: 1fr;
grid-gap: 10px;
max-width: 600px;
width: calc(100vw - 40px);
height: calc(100vh - 40px);
margin: 20px;
padding: 20px;
box-sizing: border-box;
grid-template-rows: auto 1fr auto;
}
#chatContainer {
grid-row: 2 / 3;
background-color: #121212;
border: none;
padding: 10px;
overflow-y: auto;
border-radius: 4px;
}
#messageInput {
overflow-y: auto;
height: 10vh;
max-height: 20vh;
resize: none;
padding: 10px;
border: 1px solid #333;
background-color: #121212;
color: #FFF;
border-radius: 4px;
width: 70%;
}
.show {display: block;}
button {
padding: 10px 20px;
background-color: #333;
border: none;
color: #FFF;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #555;
}
label {
color: #999;
}
input[type="range"] {
background-color: #333;
}
#controlPanel {
display: grid;
grid-template-columns: 3fr 1fr 1fr auto;
gap: 10px;
}
.slider-container {
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
}
input[type="range"] {
grid-column: 2;
}
label {
grid-column: 1;
}
#loadingIndicator {
color: red;
display: none;
}
.dropdown {
display: block;
position: relative;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #333;
min-width: 200px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown button {
display: block;
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div id="chatContainer">
<!-- Chat messages will be appended here -->
</div>
<div id="controlPanel">
<textarea id="messageInput" placeholder="Type your message here…"></textarea> <!-- converted to textarea -->
<button id="sendButton">Send</button>
<button id="clearButton">Clear</button>
<span id="loadingIndicator">Loading…</span>
<div class="dropdown">
<button onclick="toggleDropdown()">Parameters</button>
<div id="dropdownContent" class="dropdown-content">
<div class="slider-container">
<label for="temperatureRange">Temperature: <span id="temperatureValue">0.7</span></label>
<input type="range" id="temperatureRange" min="0.1" max="1.0" value="0.7" step="0.1">
</div>
<div class="slider-container">
<label for="topKRange">Top K: <span id="topKValue">40</span></label>
<input type="range" id="topKRange" min="0" max="80" value="40" step="1">
</div>
<div class="slider-container">
<label for="topPRange">Top P: <span id="topPValue">0.9</span></label>
<input type="range" id="topPRange" min="0.1" max="1.0" value="0.9" step="0.1">
</div>
</div>
</div>
</div>
</div>
<script>
const chatContainer = document.getElementById('chatContainer');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const clearButton = document.getElementById('clearButton');
const loadingIndicator = document.getElementById('loadingIndicator');
const temperatureSlider = document.getElementById('temperatureRange');
const topKSlider = document.getElementById('topKRange');
const topPSlider = document.getElementById('topPRange');
const temperatureValue = document.getElementById('temperatureValue');
const topKValue = document.getElementById('topKValue');
const topPValue = document.getElementById('topPValue');
const apiToken = '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'; // Replace with your actual API token
function appendToChatContainer(text) {
chatContainer.innerHTML += text + "<br/>";
chatContainer.scrollTop = chatContainer.scrollHeight;
}
temperatureSlider.addEventListener('input', function() {
temperatureValue.textContent = temperatureSlider.value;
});
topKSlider.addEventListener('input', function() {
topKValue.textContent = topKSlider.value;
});
topPSlider.addEventListener('input', function() {
topPValue.textContent = topPSlider.value;
});
sendButton.addEventListener('click', function() {
const userInput = messageInput.value.trim();
if (userInput === '') return;
appendToChatContainer("You: " + userInput);
messageInput.value = '';
sendMessageToModel(userInput);
});
function sendMessageToModel(userInput, shouldWait = false) {
const payload = {
inputs: userInput,
parameters: {
temperature: parseFloat(temperatureSlider.value),
top_k: parseInt(topKSlider.value),
top_p: parseFloat(topPSlider.value),
max_length: 160,
return_full_text: false
},
options: {
wait_for_model: shouldWait
}
};
loadingIndicator.style.display = 'inline';
fetch('https://api-inference.huggingface.co/models/gpt2-xl', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
})
.then(response => {
if (!response.ok) {
if (response.status === 503) {
return response.text().then(text => {
if (text.toLowerCase().includes("currently loading")) {
// Retry with wait_for_model set to true after 2 seconds
setTimeout(() => sendMessageToModel(userInput, true), 2000);
return Promise.reject('Model is currently loading.');
}
return Promise.reject('Unknown error occurred.');
});
}
return Promise.reject('HTTP error ' + response.status);
}
return response.json();
})
.then(data => {
if (Array.isArray(data) && data.length > 0) {
appendToChatContainer("AI: " + data[0].generated_text);
}
loadingIndicator.style.display = 'none';
})
.catch(error => {
appendToChatContainer("Error: " + error);
loadingIndicator.style.display = 'none';
});
}
clearButton.addEventListener('click', function() {
chatContainer.innerHTML = 'Welcome to the AI chat!';
});
function toggleDropdown() {
document.getElementById("dropdownContent").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropdown button')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</body>
</html>
|
c5ba066db3e5cf2d9948779ac1a92040
|
{
"intermediate": 0.2919614315032959,
"beginner": 0.4251539707183838,
"expert": 0.2828846275806427
}
|
37,851
|
User
With minecraft datapacks, you can change the worldgen information of the overworld dimension to specify max worldheight to be lower. This is useful to create a world that is more efficient, as there is less information to store. Using Spigot, how can I achieve the same performance boost? This means not manually stopping people from placing blocks above a new worldheight, because then the information would still need to be stored.
Following now is the spigot wiki article on world data, this should contain some way to change the maxworldheight.
"
Package org.bukkit
Interface World
All Superinterfaces:
Metadatable, PluginMessageRecipient
public interface World
extends PluginMessageRecipient, Metadatable
Represents a world, which may contain entities, chunks and blocks
Nested Class Summary
Nested Classes
Modifier and Type
Interface
Description
static class
World.Environment
Represents various map environment types that a world may be
static class
World.Spigot
Method Summary
Modifier and Type
Method
Description
boolean
addPluginChunkTicket(int x, int z, Plugin plugin)
Adds a plugin ticket for the specified chunk, loading the chunk if it is not already loaded.
boolean
canGenerateStructures()
Gets whether or not structures are being generated.
boolean
createExplosion(double x, double y, double z, float power)
Creates explosion at given coordinates with given power
boolean
createExplosion(double x, double y, double z, float power, boolean setFire)
Creates explosion at given coordinates with given power and optionally setting blocks on fire.
boolean
createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
boolean
createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
boolean
createExplosion(Location loc, float power)
Creates explosion at given coordinates with given power
boolean
createExplosion(Location loc, float power, boolean setFire)
Creates explosion at given coordinates with given power and optionally setting blocks on fire.
boolean
createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
boolean
createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
Item
dropItem(Location location, ItemStack item)
Drops an item at the specified Location
Item
dropItem(Location location, ItemStack item, Consumer<Item> function)
Drops an item at the specified Location Note that functions will run before the entity is spawned
Item
dropItemNaturally(Location location, ItemStack item)
Drops an item at the specified Location with a random offset
Item
dropItemNaturally(Location location, ItemStack item, Consumer<Item> function)
Drops an item at the specified Location with a random offset Note that functions will run before the entity is spawned
boolean
generateTree(Location location, TreeType type)
Creates a tree at the given Location
boolean
generateTree(Location loc, TreeType type, BlockChangeDelegate delegate)
Creates a tree at the given Location
boolean
getAllowAnimals()
Gets whether animals can spawn in this world.
boolean
getAllowMonsters()
Gets whether monsters can spawn in this world.
int
getAmbientSpawnLimit()
Gets the limit for number of ambient mobs that can spawn in a chunk in this world
int
getAnimalSpawnLimit()
Gets the limit for number of animals that can spawn in a chunk in this world
Biome
getBiome(int x, int z)
Deprecated.
biomes are now 3-dimensional
Biome
getBiome(int x, int y, int z)
Gets the biome for the given block coordinates.
Block
getBlockAt(int x, int y, int z)
Gets the Block at the given coordinates
Block
getBlockAt(Location location)
Gets the Block at the given Location
Chunk
getChunkAt(int x, int z)
Gets the Chunk at the given coordinates
Chunk
getChunkAt(Block block)
Gets the Chunk that contains the given Block
Chunk
getChunkAt(Location location)
Gets the Chunk at the given Location
int
getClearWeatherDuration()
Get the clear weather duration.
Difficulty
getDifficulty()
Gets the Difficulty of the world.
ChunkSnapshot
getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTemp)
Get empty chunk snapshot (equivalent to all air blocks), optionally including valid biome data.
DragonBattle
getEnderDragonBattle()
Get the DragonBattle associated with this world.
List<Entity>
getEntities()
Get a list of all entities in this World
<T extends Entity>
Collection<T>
getEntitiesByClass(Class<T> cls)
Get a collection of all entities in this World matching the given class/interface
<T extends Entity>
Collection<T>
getEntitiesByClass(Class<T>... classes)
Deprecated.
Collection<Entity>
getEntitiesByClasses(Class<?>... classes)
Get a collection of all entities in this World matching any of the given classes/interfaces
World.Environment
getEnvironment()
Gets the World.Environment type of this world
Collection<Chunk>
getForceLoadedChunks()
Returns all force loaded chunks in this world.
long
getFullTime()
Gets the full in-game time on this world
<T> T
getGameRuleDefault(GameRule<T> rule)
Get the default value for a given GameRule.
String[]
getGameRules()
Get an array containing the names of all the GameRules.
String
getGameRuleValue(String rule)
Deprecated.
use getGameRuleValue(GameRule) instead
<T> T
getGameRuleValue(GameRule<T> rule)
Get the current value for a given GameRule.
long
getGameTime()
Gets the full in-game time on this world since the world generation
ChunkGenerator
getGenerator()
Gets the chunk generator for this world
Block
getHighestBlockAt(int x, int z)
Gets the highest non-empty (impassable) block at the given coordinates.
Block
getHighestBlockAt(int x, int z, HeightMap heightMap)
Gets the highest block corresponding to the HeightMap at the given coordinates.
Block
getHighestBlockAt(Location location)
Gets the highest non-empty (impassable) block at the given coordinates.
Block
getHighestBlockAt(Location location, HeightMap heightMap)
Gets the highest block corresponding to the HeightMap at the given coordinates.
int
getHighestBlockYAt(int x, int z)
Gets the highest non-empty (impassable) coordinate at the given coordinates.
int
getHighestBlockYAt(int x, int z, HeightMap heightMap)
Gets the highest coordinate corresponding to the HeightMap at the given coordinates.
int
getHighestBlockYAt(Location location)
Gets the highest non-empty (impassable) coordinate at the given Location.
int
getHighestBlockYAt(Location location, HeightMap heightMap)
Gets the highest coordinate corresponding to the HeightMap at the given Location.
double
getHumidity(int x, int z)
Deprecated.
biomes are now 3-dimensional
double
getHumidity(int x, int y, int z)
Gets the humidity for the given block coordinates.
boolean
getKeepSpawnInMemory()
Gets whether the world's spawn area should be kept loaded into memory or not.
List<LivingEntity>
getLivingEntities()
Get a list of all living entities in this World
Chunk[]
getLoadedChunks()
Gets an array of all loaded Chunks
int
getMaxHeight()
Gets the maximum height of this world.
int
getMinHeight()
Gets the minimum height of this world.
int
getMonsterSpawnLimit()
Gets limit for number of monsters that can spawn in a chunk in this world
String
getName()
Gets the unique name of this world
Collection<Entity>
getNearbyEntities(Location location, double x, double y, double z)
Returns a list of entities within a bounding box centered around a Location.
Collection<Entity>
getNearbyEntities(Location location, double x, double y, double z, Predicate<Entity> filter)
Returns a list of entities within a bounding box centered around a Location.
Collection<Entity>
getNearbyEntities(BoundingBox boundingBox)
Returns a list of entities within the given bounding box.
Collection<Entity>
getNearbyEntities(BoundingBox boundingBox, Predicate<Entity> filter)
Returns a list of entities within the given bounding box.
List<Player>
getPlayers()
Get a list of all players in this World
Map<Plugin,Collection<Chunk>>
getPluginChunkTickets()
Returns a map of which plugins have tickets for what chunks.
Collection<Plugin>
getPluginChunkTickets(int x, int z)
Retrieves a collection specifying which plugins have tickets for the specified chunk.
List<BlockPopulator>
getPopulators()
Gets a list of all applied BlockPopulators for this World
boolean
getPVP()
Gets the current PVP setting for this world.
List<Raid>
getRaids()
Gets all raids that are going on over this world.
int
getSeaLevel()
Gets the sea level for this world.
long
getSeed()
Gets the Seed for this world.
Location
getSpawnLocation()
Gets the default spawn Location of this world
double
getTemperature(int x, int z)
Deprecated.
biomes are now 3-dimensional
double
getTemperature(int x, int y, int z)
Gets the temperature for the given block coordinates.
int
getThunderDuration()
Get the thundering duration.
long
getTicksPerAmbientSpawns()
Gets the world's ticks per ambient mob spawns value
long
getTicksPerAnimalSpawns()
Gets the world's ticks per animal spawns value
long
getTicksPerMonsterSpawns()
Gets the world's ticks per monster spawns value
long
getTicksPerWaterAmbientSpawns()
Gets the default ticks per water ambient mob spawns value.
long
getTicksPerWaterSpawns()
Gets the world's ticks per water mob spawns value
long
getTime()
Gets the relative in-game time of this world.
UUID
getUID()
Gets the Unique ID of this world
int
getViewDistance()
Returns the view distance used for this world.
int
getWaterAmbientSpawnLimit()
Gets user-specified limit for number of water ambient mobs that can spawn in a chunk.
int
getWaterAnimalSpawnLimit()
Gets the limit for number of water animals that can spawn in a chunk in this world
int
getWeatherDuration()
Get the remaining time in ticks of the current conditions.
WorldBorder
getWorldBorder()
Gets the world border for this world.
File
getWorldFolder()
Gets the folder of this world on disk.
WorldType
getWorldType()
Deprecated.
world type is only used to select the default word generation settings and is not stored in Vanilla worlds, making it impossible for this method to always return the correct value.
boolean
hasStorm()
Returns whether the world has an ongoing storm.
boolean
isAutoSave()
Gets whether or not the world will automatically save
boolean
isChunkForceLoaded(int x, int z)
Gets whether the chunk at the specified chunk coordinates is force loaded.
boolean
isChunkGenerated(int x, int z)
Checks if the Chunk at the specified coordinates is generated
boolean
isChunkInUse(int x, int z)
Deprecated.
This method was added to facilitate chunk garbage collection.
boolean
isChunkLoaded(int x, int z)
Checks if the Chunk at the specified coordinates is loaded
boolean
isChunkLoaded(Chunk chunk)
Checks if the specified Chunk is loaded
boolean
isClearWeather()
Returns whether the world has clear weather.
boolean
isGameRule(String rule)
Checks if string is a valid game rule
boolean
isHardcore()
Gets whether the world is hardcore or not.
boolean
isThundering()
Returns whether there is thunder.
void
loadChunk(int x, int z)
Loads the Chunk at the specified coordinates.
boolean
loadChunk(int x, int z, boolean generate)
Loads the Chunk at the specified coordinates.
void
loadChunk(Chunk chunk)
Loads the specified Chunk.
Raid
locateNearestRaid(Location location, int radius)
Finds the nearest raid close to the given location.
Location
locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored)
Find the closest nearby structure of a given StructureType.
void
playEffect(Location location, Effect effect, int data)
Plays an effect to all players within a default radius around a given location.
void
playEffect(Location location, Effect effect, int data, int radius)
Plays an effect to all players within a given radius around a location.
<T> void
playEffect(Location location, Effect effect, T data)
Plays an effect to all players within a default radius around a given location.
<T> void
playEffect(Location location, Effect effect, T data, int radius)
Plays an effect to all players within a given radius around a location.
void
playSound(Location location, String sound, float volume, float pitch)
Play a Sound at the provided Location in the World.
void
playSound(Location location, String sound, SoundCategory category, float volume, float pitch)
Play a Sound at the provided Location in the World.
void
playSound(Location location, Sound sound, float volume, float pitch)
Play a Sound at the provided Location in the World
void
playSound(Location location, Sound sound, SoundCategory category, float volume, float pitch)
Play a Sound at the provided Location in the World.
RayTraceResult
rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate<Entity> filter)
Performs a ray trace that checks for both block and entity collisions.
RayTraceResult
rayTraceBlocks(Location start, Vector direction, double maxDistance)
Performs a ray trace that checks for block collisions using the blocks' precise collision shapes.
RayTraceResult
rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode)
Performs a ray trace that checks for block collisions using the blocks' precise collision shapes.
RayTraceResult
rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks)
Performs a ray trace that checks for block collisions using the blocks' precise collision shapes.
RayTraceResult
rayTraceEntities(Location start, Vector direction, double maxDistance)
Performs a ray trace that checks for entity collisions.
RayTraceResult
rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize)
Performs a ray trace that checks for entity collisions.
RayTraceResult
rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate<Entity> filter)
Performs a ray trace that checks for entity collisions.
RayTraceResult
rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate<Entity> filter)
Performs a ray trace that checks for entity collisions.
boolean
refreshChunk(int x, int z)
Deprecated.
This method is not guaranteed to work suitably across all client implementations.
boolean
regenerateChunk(int x, int z)
Deprecated.
regenerating a single chunk is not likely to produce the same chunk as before as terrain decoration may be spread across chunks.
boolean
removePluginChunkTicket(int x, int z, Plugin plugin)
Removes the specified plugin's ticket for the specified chunk
void
removePluginChunkTickets(Plugin plugin)
Removes all plugin tickets for the specified plugin
void
save()
Saves world to disk
void
setAmbientSpawnLimit(int limit)
Sets the limit for number of ambient mobs that can spawn in a chunk in this world
void
setAnimalSpawnLimit(int limit)
Sets the limit for number of animals that can spawn in a chunk in this world
void
setAutoSave(boolean value)
Sets whether or not the world will automatically save
void
setBiome(int x, int y, int z, Biome bio)
Sets the biome for the given block coordinates
void
setBiome(int x, int z, Biome bio)
Deprecated.
biomes are now 3-dimensional
void
setChunkForceLoaded(int x, int z, boolean forced)
Sets whether the chunk at the specified chunk coordinates is force loaded.
void
setClearWeatherDuration(int duration)
Set the clear weather duration.
void
setDifficulty(Difficulty difficulty)
Sets the Difficulty of the world.
void
setFullTime(long time)
Sets the in-game time on the server
<T> boolean
setGameRule(GameRule<T> rule, T newValue)
Set the given GameRule's new value.
boolean
setGameRuleValue(String rule, String value)
Deprecated.
use setGameRule(GameRule, Object) instead.
void
setHardcore(boolean hardcore)
Sets whether the world is hardcore or not.
void
setKeepSpawnInMemory(boolean keepLoaded)
Sets whether the world's spawn area should be kept loaded into memory or not.
void
setMonsterSpawnLimit(int limit)
Sets the limit for number of monsters that can spawn in a chunk in this world
void
setPVP(boolean pvp)
Sets the PVP setting for this world.
void
setSpawnFlags(boolean allowMonsters, boolean allowAnimals)
Sets the spawn flags for this.
boolean
setSpawnLocation(int x, int y, int z)
Sets the spawn location of the world
boolean
setSpawnLocation(int x, int y, int z, float angle)
Sets the spawn location of the world
boolean
setSpawnLocation(Location location)
Sets the spawn location of the world.
void
setStorm(boolean hasStorm)
Set whether there is a storm.
void
setThunderDuration(int duration)
Set the thundering duration.
void
setThundering(boolean thundering)
Set whether it is thundering.
void
setTicksPerAmbientSpawns(int ticksPerAmbientSpawns)
Sets the world's ticks per ambient mob spawns value
void
setTicksPerAnimalSpawns(int ticksPerAnimalSpawns)
Sets the world's ticks per animal spawns value
void
setTicksPerMonsterSpawns(int ticksPerMonsterSpawns)
Sets the world's ticks per monster spawns value
void
setTicksPerWaterAmbientSpawns(int ticksPerAmbientSpawns)
Sets the world's ticks per water ambient mob spawns value
void
setTicksPerWaterSpawns(int ticksPerWaterSpawns)
Sets the world's ticks per water mob spawns value
void
setTime(long time)
Sets the relative in-game time on the server.
void
setWaterAmbientSpawnLimit(int limit)
Sets the limit for number of water ambient mobs that can spawn in a chunk in this world
void
setWaterAnimalSpawnLimit(int limit)
Sets the limit for number of water animals that can spawn in a chunk in this world
void
setWeatherDuration(int duration)
Set the remaining time in ticks of the current conditions.
<T extends Entity>
T
spawn(Location location, Class<T> clazz)
Spawn an entity of a specific class at the given Location
<T extends Entity>
T
spawn(Location location, Class<T> clazz, Consumer<T> function)
Spawn an entity of a specific class at the given Location, with the supplied function run before the entity is added to the world.
Arrow
spawnArrow(Location location, Vector direction, float speed, float spread)
Creates an Arrow entity at the given Location
<T extends AbstractArrow>
T
spawnArrow(Location location, Vector direction, float speed, float spread, Class<T> clazz)
Creates an arrow entity of the given class at the given Location
Entity
spawnEntity(Location loc, EntityType type)
Creates a entity at the given Location
FallingBlock
spawnFallingBlock(Location location, BlockData data)
Spawn a FallingBlock entity at the given Location of the specified Material.
FallingBlock
spawnFallingBlock(Location location, MaterialData data)
Spawn a FallingBlock entity at the given Location of the specified Material.
FallingBlock
spawnFallingBlock(Location location, Material material, byte data)
Deprecated.
Magic value
void
spawnParticle(Particle particle, double x, double y, double z, int count)
Spawns the particle (the number of times specified by count) at the target location.
void
spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ)
Spawns the particle (the number of times specified by count) at the target location.
void
spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, double x, double y, double z, int count, T data)
Spawns the particle (the number of times specified by count) at the target location.
void
spawnParticle(Particle particle, Location location, int count)
Spawns the particle (the number of times specified by count) at the target location.
void
spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ)
Spawns the particle (the number of times specified by count) at the target location.
void
spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data)
Spawns the particle (the number of times specified by count) at the target location.
<T> void
spawnParticle(Particle particle, Location location, int count, T data)
Spawns the particle (the number of times specified by count) at the target location.
World.Spigot
spigot()
LightningStrike
strikeLightning(Location loc)
Strikes lightning at the given Location
LightningStrike
strikeLightningEffect(Location loc)
Strikes lightning at the given Location without doing damage
boolean
unloadChunk(int x, int z)
Safely unloads and saves the Chunk at the specified coordinates
boolean
unloadChunk(int x, int z, boolean save)
Safely unloads and optionally saves the Chunk at the specified coordinates.
boolean
unloadChunk(Chunk chunk)
Safely unloads and saves the Chunk at the specified coordinates
boolean
unloadChunkRequest(int x, int z)
Safely queues the Chunk at the specified coordinates for unloading.
Methods inherited from interface org.bukkit.metadata.Metadatable
getMetadata, hasMetadata, removeMetadata, setMetadata
Methods inherited from interface org.bukkit.plugin.messaging.PluginMessageRecipient
getListeningPluginChannels, sendPluginMessage
Method Details
getBlockAt
@NotNull
Block getBlockAt(int x,
int y,
int z)
Gets the Block at the given coordinates
Parameters:
x - X-coordinate of the block
y - Y-coordinate of the block
z - Z-coordinate of the block
Returns:
Block at the given coordinates
getBlockAt
@NotNull
Block getBlockAt(@NotNull
Location location)
Gets the Block at the given Location
Parameters:
location - Location of the block
Returns:
Block at the given location
getHighestBlockYAt
int getHighestBlockYAt(int x,
int z)
Gets the highest non-empty (impassable) coordinate at the given coordinates.
Parameters:
x - X-coordinate of the blocks
z - Z-coordinate of the blocks
Returns:
Y-coordinate of the highest non-empty block
getHighestBlockYAt
int getHighestBlockYAt(@NotNull
Location location)
Gets the highest non-empty (impassable) coordinate at the given Location.
Parameters:
location - Location of the blocks
Returns:
Y-coordinate of the highest non-empty block
getHighestBlockAt
@NotNull
Block getHighestBlockAt(int x,
int z)
Gets the highest non-empty (impassable) block at the given coordinates.
Parameters:
x - X-coordinate of the block
z - Z-coordinate of the block
Returns:
Highest non-empty block
getHighestBlockAt
@NotNull
Block getHighestBlockAt(@NotNull
Location location)
Gets the highest non-empty (impassable) block at the given coordinates.
Parameters:
location - Coordinates to get the highest block
Returns:
Highest non-empty block
getHighestBlockYAt
int getHighestBlockYAt(int x,
int z,
@NotNull
HeightMap heightMap)
Gets the highest coordinate corresponding to the HeightMap at the given coordinates.
Parameters:
x - X-coordinate of the blocks
z - Z-coordinate of the blocks
heightMap - the heightMap that is used to determine the highest point
Returns:
Y-coordinate of the highest block corresponding to the HeightMap
getHighestBlockYAt
int getHighestBlockYAt(@NotNull
Location location,
@NotNull
HeightMap heightMap)
Gets the highest coordinate corresponding to the HeightMap at the given Location.
Parameters:
location - Location of the blocks
heightMap - the heightMap that is used to determine the highest point
Returns:
Y-coordinate of the highest block corresponding to the HeightMap
getHighestBlockAt
@NotNull
Block getHighestBlockAt(int x,
int z,
@NotNull
HeightMap heightMap)
Gets the highest block corresponding to the HeightMap at the given coordinates.
Parameters:
x - X-coordinate of the block
z - Z-coordinate of the block
heightMap - the heightMap that is used to determine the highest point
Returns:
Highest block corresponding to the HeightMap
getHighestBlockAt
@NotNull
Block getHighestBlockAt(@NotNull
Location location,
@NotNull
HeightMap heightMap)
Gets the highest block corresponding to the HeightMap at the given coordinates.
Parameters:
location - Coordinates to get the highest block
heightMap - the heightMap that is used to determine the highest point
Returns:
Highest block corresponding to the HeightMap
getChunkAt
@NotNull
Chunk getChunkAt(int x,
int z)
Gets the Chunk at the given coordinates
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
Chunk at the given coordinates
getChunkAt
@NotNull
Chunk getChunkAt(@NotNull
Location location)
Gets the Chunk at the given Location
Parameters:
location - Location of the chunk
Returns:
Chunk at the given location
getChunkAt
@NotNull
Chunk getChunkAt(@NotNull
Block block)
Gets the Chunk that contains the given Block
Parameters:
block - Block to get the containing chunk from
Returns:
The chunk that contains the given block
isChunkLoaded
boolean isChunkLoaded(@NotNull
Chunk chunk)
Checks if the specified Chunk is loaded
Parameters:
chunk - The chunk to check
Returns:
true if the chunk is loaded, otherwise false
getLoadedChunks
@NotNull
Chunk[] getLoadedChunks()
Gets an array of all loaded Chunks
Returns:
Chunk[] containing all loaded chunks
loadChunk
void loadChunk(@NotNull
Chunk chunk)
Loads the specified Chunk.
This method will keep the specified chunk loaded until one of the unload methods is manually called. Callers are advised to instead use getChunkAt which will only temporarily load the requested chunk.
Parameters:
chunk - The chunk to load
isChunkLoaded
boolean isChunkLoaded(int x,
int z)
Checks if the Chunk at the specified coordinates is loaded
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
true if the chunk is loaded, otherwise false
isChunkGenerated
boolean isChunkGenerated(int x,
int z)
Checks if the Chunk at the specified coordinates is generated
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
true if the chunk is generated, otherwise false
isChunkInUse
@Deprecated
boolean isChunkInUse(int x,
int z)
Deprecated.
This method was added to facilitate chunk garbage collection. As of the current Minecraft version chunks are now strictly managed and will not be loaded for more than 1 tick unless they are in use.
Checks if the Chunk at the specified coordinates is loaded and in use by one or more players
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
true if the chunk is loaded and in use by one or more players, otherwise false
loadChunk
void loadChunk(int x,
int z)
Loads the Chunk at the specified coordinates.
This method will keep the specified chunk loaded until one of the unload methods is manually called. Callers are advised to instead use getChunkAt which will only temporarily load the requested chunk.
If the chunk does not exist, it will be generated.
This method is analogous to loadChunk(int, int, boolean) where generate is true.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
loadChunk
boolean loadChunk(int x,
int z,
boolean generate)
Loads the Chunk at the specified coordinates.
This method will keep the specified chunk loaded until one of the unload methods is manually called. Callers are advised to instead use getChunkAt which will only temporarily load the requested chunk.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
generate - Whether or not to generate a chunk if it doesn't already exist
Returns:
true if the chunk has loaded successfully, otherwise false
unloadChunk
boolean unloadChunk(@NotNull
Chunk chunk)
Safely unloads and saves the Chunk at the specified coordinates
This method is analogous to unloadChunk(int, int, boolean) where save is true.
Parameters:
chunk - the chunk to unload
Returns:
true if the chunk has unloaded successfully, otherwise false
unloadChunk
boolean unloadChunk(int x,
int z)
Safely unloads and saves the Chunk at the specified coordinates
This method is analogous to unloadChunk(int, int, boolean) where save is true.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
true if the chunk has unloaded successfully, otherwise false
unloadChunk
boolean unloadChunk(int x,
int z,
boolean save)
Safely unloads and optionally saves the Chunk at the specified coordinates.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
save - Whether or not to save the chunk
Returns:
true if the chunk has unloaded successfully, otherwise false
unloadChunkRequest
boolean unloadChunkRequest(int x,
int z)
Safely queues the Chunk at the specified coordinates for unloading.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
true is the queue attempt was successful, otherwise false
regenerateChunk
@Deprecated
boolean regenerateChunk(int x,
int z)
Deprecated.
regenerating a single chunk is not likely to produce the same chunk as before as terrain decoration may be spread across chunks. Use of this method should be avoided as it is known to produce buggy results.
Regenerates the Chunk at the specified coordinates
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
Whether the chunk was actually regenerated
refreshChunk
@Deprecated
boolean refreshChunk(int x,
int z)
Deprecated.
This method is not guaranteed to work suitably across all client implementations.
Resends the Chunk to all clients
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
Whether the chunk was actually refreshed
isChunkForceLoaded
boolean isChunkForceLoaded(int x,
int z)
Gets whether the chunk at the specified chunk coordinates is force loaded.
A force loaded chunk will not be unloaded due to lack of player activity.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
force load status
setChunkForceLoaded
void setChunkForceLoaded(int x,
int z,
boolean forced)
Sets whether the chunk at the specified chunk coordinates is force loaded.
A force loaded chunk will not be unloaded due to lack of player activity.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
forced - force load status
getForceLoadedChunks
@NotNull
Collection<Chunk> getForceLoadedChunks()
Returns all force loaded chunks in this world.
A force loaded chunk will not be unloaded due to lack of player activity.
Returns:
unmodifiable collection of force loaded chunks
addPluginChunkTicket
boolean addPluginChunkTicket(int x,
int z,
@NotNull
Plugin plugin)
Adds a plugin ticket for the specified chunk, loading the chunk if it is not already loaded.
A plugin ticket will prevent a chunk from unloading until it is explicitly removed. A plugin instance may only have one ticket per chunk, but each chunk can have multiple plugin tickets.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
plugin - Plugin which owns the ticket
Returns:
true if a plugin ticket was added, false if the ticket already exists for the plugin
Throws:
IllegalStateException - If the specified plugin is not enabled
See Also:
removePluginChunkTicket(int, int, Plugin)
removePluginChunkTicket
boolean removePluginChunkTicket(int x,
int z,
@NotNull
Plugin plugin)
Removes the specified plugin's ticket for the specified chunk
A plugin ticket will prevent a chunk from unloading until it is explicitly removed. A plugin instance may only have one ticket per chunk, but each chunk can have multiple plugin tickets.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
plugin - Plugin which owns the ticket
Returns:
true if the plugin ticket was removed, false if there is no plugin ticket for the chunk
See Also:
addPluginChunkTicket(int, int, Plugin)
removePluginChunkTickets
void removePluginChunkTickets(@NotNull
Plugin plugin)
Removes all plugin tickets for the specified plugin
A plugin ticket will prevent a chunk from unloading until it is explicitly removed. A plugin instance may only have one ticket per chunk, but each chunk can have multiple plugin tickets.
Parameters:
plugin - Specified plugin
See Also:
addPluginChunkTicket(int, int, Plugin), removePluginChunkTicket(int, int, Plugin)
getPluginChunkTickets
@NotNull
Collection<Plugin> getPluginChunkTickets(int x,
int z)
Retrieves a collection specifying which plugins have tickets for the specified chunk. This collection is not updated when plugin tickets are added or removed to the chunk.
A plugin ticket will prevent a chunk from unloading until it is explicitly removed. A plugin instance may only have one ticket per chunk, but each chunk can have multiple plugin tickets.
Parameters:
x - X-coordinate of the chunk
z - Z-coordinate of the chunk
Returns:
unmodifiable collection containing which plugins have tickets for the chunk
See Also:
addPluginChunkTicket(int, int, Plugin), removePluginChunkTicket(int, int, Plugin)
getPluginChunkTickets
@NotNull
Map<Plugin,Collection<Chunk>> getPluginChunkTickets()
Returns a map of which plugins have tickets for what chunks. The returned map is not updated when plugin tickets are added or removed to chunks. If a plugin has no tickets, it will be absent from the map.
A plugin ticket will prevent a chunk from unloading until it is explicitly removed. A plugin instance may only have one ticket per chunk, but each chunk can have multiple plugin tickets.
Returns:
unmodifiable map containing which plugins have tickets for what chunks
See Also:
addPluginChunkTicket(int, int, Plugin), removePluginChunkTicket(int, int, Plugin)
dropItem
@NotNull
Item dropItem(@NotNull
Location location,
@NotNull
ItemStack item)
Drops an item at the specified Location
Parameters:
location - Location to drop the item
item - ItemStack to drop
Returns:
ItemDrop entity created as a result of this method
dropItem
@NotNull
Item dropItem(@NotNull
Location location,
@NotNull
ItemStack item,
@Nullable
Consumer<Item> function)
Drops an item at the specified Location Note that functions will run before the entity is spawned
Parameters:
location - Location to drop the item
item - ItemStack to drop
function - the function to be run before the entity is spawned.
Returns:
ItemDrop entity created as a result of this method
dropItemNaturally
@NotNull
Item dropItemNaturally(@NotNull
Location location,
@NotNull
ItemStack item)
Drops an item at the specified Location with a random offset
Parameters:
location - Location to drop the item
item - ItemStack to drop
Returns:
ItemDrop entity created as a result of this method
dropItemNaturally
@NotNull
Item dropItemNaturally(@NotNull
Location location,
@NotNull
ItemStack item,
@Nullable
Consumer<Item> function)
Drops an item at the specified Location with a random offset Note that functions will run before the entity is spawned
Parameters:
location - Location to drop the item
item - ItemStack to drop
function - the function to be run before the entity is spawned.
Returns:
ItemDrop entity created as a result of this method
spawnArrow
@NotNull
Arrow spawnArrow(@NotNull
Location location,
@NotNull
Vector direction,
float speed,
float spread)
Creates an Arrow entity at the given Location
Parameters:
location - Location to spawn the arrow
direction - Direction to shoot the arrow in
speed - Speed of the arrow. A recommend speed is 0.6
spread - Spread of the arrow. A recommend spread is 12
Returns:
Arrow entity spawned as a result of this method
spawnArrow
@NotNull
<T extends AbstractArrow> T spawnArrow(@NotNull
Location location,
@NotNull
Vector direction,
float speed,
float spread,
@NotNull
Class<T> clazz)
Creates an arrow entity of the given class at the given Location
Type Parameters:
T - type of arrow to spawn
Parameters:
location - Location to spawn the arrow
direction - Direction to shoot the arrow in
speed - Speed of the arrow. A recommend speed is 0.6
spread - Spread of the arrow. A recommend spread is 12
clazz - the Entity class for the arrow SpectralArrow,Arrow,TippedArrow
Returns:
Arrow entity spawned as a result of this method
generateTree
boolean generateTree(@NotNull
Location location,
@NotNull
TreeType type)
Creates a tree at the given Location
Parameters:
location - Location to spawn the tree
type - Type of the tree to create
Returns:
true if the tree was created successfully, otherwise false
generateTree
boolean generateTree(@NotNull
Location loc,
@NotNull
TreeType type,
@NotNull
BlockChangeDelegate delegate)
Creates a tree at the given Location
Parameters:
loc - Location to spawn the tree
type - Type of the tree to create
delegate - A class to call for each block changed as a result of this method
Returns:
true if the tree was created successfully, otherwise false
spawnEntity
@NotNull
Entity spawnEntity(@NotNull
Location loc,
@NotNull
EntityType type)
Creates a entity at the given Location
Parameters:
loc - The location to spawn the entity
type - The entity to spawn
Returns:
Resulting Entity of this method
strikeLightning
@NotNull
LightningStrike strikeLightning(@NotNull
Location loc)
Strikes lightning at the given Location
Parameters:
loc - The location to strike lightning
Returns:
The lightning entity.
strikeLightningEffect
@NotNull
LightningStrike strikeLightningEffect(@NotNull
Location loc)
Strikes lightning at the given Location without doing damage
Parameters:
loc - The location to strike lightning
Returns:
The lightning entity.
getEntities
@NotNull
List<Entity> getEntities()
Get a list of all entities in this World
Returns:
A List of all Entities currently residing in this world
getLivingEntities
@NotNull
List<LivingEntity> getLivingEntities()
Get a list of all living entities in this World
Returns:
A List of all LivingEntities currently residing in this world
getEntitiesByClass
@Deprecated
@NotNull
<T extends Entity> Collection<T> getEntitiesByClass(@NotNull
Class<T>... classes)
Deprecated.
Get a collection of all entities in this World matching the given class/interface
Type Parameters:
T - an entity subclass
Parameters:
classes - The classes representing the types of entity to match
Returns:
A List of all Entities currently residing in this world that match the given class/interface
getEntitiesByClass
@NotNull
<T extends Entity> Collection<T> getEntitiesByClass(@NotNull
Class<T> cls)
Get a collection of all entities in this World matching the given class/interface
Type Parameters:
T - an entity subclass
Parameters:
cls - The class representing the type of entity to match
Returns:
A List of all Entities currently residing in this world that match the given class/interface
getEntitiesByClasses
@NotNull
Collection<Entity> getEntitiesByClasses(@NotNull
Class<?>... classes)
Get a collection of all entities in this World matching any of the given classes/interfaces
Parameters:
classes - The classes representing the types of entity to match
Returns:
A List of all Entities currently residing in this world that match one or more of the given classes/interfaces
getPlayers
@NotNull
List<Player> getPlayers()
Get a list of all players in this World
Returns:
A list of all Players currently residing in this world
getNearbyEntities
@NotNull
Collection<Entity> getNearbyEntities(@NotNull
Location location,
double x,
double y,
double z)
Returns a list of entities within a bounding box centered around a Location.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the size of the search bounding box.
Parameters:
location - The center of the bounding box
x - 1/2 the size of the box along x axis
y - 1/2 the size of the box along y axis
z - 1/2 the size of the box along z axis
Returns:
the collection of entities near location. This will always be a non-null collection.
getNearbyEntities
@NotNull
Collection<Entity> getNearbyEntities(@NotNull
Location location,
double x,
double y,
double z,
@Nullable
Predicate<Entity> filter)
Returns a list of entities within a bounding box centered around a Location.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the size of the search bounding box.
Parameters:
location - The center of the bounding box
x - 1/2 the size of the box along x axis
y - 1/2 the size of the box along y axis
z - 1/2 the size of the box along z axis
filter - only entities that fulfill this predicate are considered, or null to consider all entities
Returns:
the collection of entities near location. This will always be a non-null collection.
getNearbyEntities
@NotNull
Collection<Entity> getNearbyEntities(@NotNull
BoundingBox boundingBox)
Returns a list of entities within the given bounding box.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the size of the search bounding box.
Parameters:
boundingBox - the bounding box
Returns:
the collection of entities within the bounding box, will always be a non-null collection
getNearbyEntities
@NotNull
Collection<Entity> getNearbyEntities(@NotNull
BoundingBox boundingBox,
@Nullable
Predicate<Entity> filter)
Returns a list of entities within the given bounding box.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the size of the search bounding box.
Parameters:
boundingBox - the bounding box
filter - only entities that fulfill this predicate are considered, or null to consider all entities
Returns:
the collection of entities within the bounding box, will always be a non-null collection
rayTraceEntities
@Nullable
RayTraceResult rayTraceEntities(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance)
Performs a ray trace that checks for entity collisions.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start position
direction - the ray direction
maxDistance - the maximum distance
Returns:
the closest ray trace hit result, or null if there is no hit
See Also:
rayTraceEntities(Location, Vector, double, double, Predicate)
rayTraceEntities
@Nullable
RayTraceResult rayTraceEntities(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance,
double raySize)
Performs a ray trace that checks for entity collisions.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start position
direction - the ray direction
maxDistance - the maximum distance
raySize - entity bounding boxes will be uniformly expanded (or shrinked) by this value before doing collision checks
Returns:
the closest ray trace hit result, or null if there is no hit
See Also:
rayTraceEntities(Location, Vector, double, double, Predicate)
rayTraceEntities
@Nullable
RayTraceResult rayTraceEntities(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance,
@Nullable
Predicate<Entity> filter)
Performs a ray trace that checks for entity collisions.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start position
direction - the ray direction
maxDistance - the maximum distance
filter - only entities that fulfill this predicate are considered, or null to consider all entities
Returns:
the closest ray trace hit result, or null if there is no hit
See Also:
rayTraceEntities(Location, Vector, double, double, Predicate)
rayTraceEntities
@Nullable
RayTraceResult rayTraceEntities(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance,
double raySize,
@Nullable
Predicate<Entity> filter)
Performs a ray trace that checks for entity collisions.
This may not consider entities in currently unloaded chunks. Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start position
direction - the ray direction
maxDistance - the maximum distance
raySize - entity bounding boxes will be uniformly expanded (or shrinked) by this value before doing collision checks
filter - only entities that fulfill this predicate are considered, or null to consider all entities
Returns:
the closest ray trace hit result, or null if there is no hit
rayTraceBlocks
@Nullable
RayTraceResult rayTraceBlocks(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance)
Performs a ray trace that checks for block collisions using the blocks' precise collision shapes.
This takes collisions with passable blocks into account, but ignores fluids.
This may cause loading of chunks! Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start location
direction - the ray direction
maxDistance - the maximum distance
Returns:
the ray trace hit result, or null if there is no hit
See Also:
rayTraceBlocks(Location, Vector, double, FluidCollisionMode, boolean)
rayTraceBlocks
@Nullable
RayTraceResult rayTraceBlocks(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance,
@NotNull
FluidCollisionMode fluidCollisionMode)
Performs a ray trace that checks for block collisions using the blocks' precise collision shapes.
This takes collisions with passable blocks into account.
This may cause loading of chunks! Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start location
direction - the ray direction
maxDistance - the maximum distance
fluidCollisionMode - the fluid collision mode
Returns:
the ray trace hit result, or null if there is no hit
See Also:
rayTraceBlocks(Location, Vector, double, FluidCollisionMode, boolean)
rayTraceBlocks
@Nullable
RayTraceResult rayTraceBlocks(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance,
@NotNull
FluidCollisionMode fluidCollisionMode,
boolean ignorePassableBlocks)
Performs a ray trace that checks for block collisions using the blocks' precise collision shapes.
If collisions with passable blocks are ignored, fluid collisions are ignored as well regardless of the fluid collision mode.
Portal blocks are only considered passable if the ray starts within them. Apart from that collisions with portal blocks will be considered even if collisions with passable blocks are otherwise ignored.
This may cause loading of chunks! Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start location
direction - the ray direction
maxDistance - the maximum distance
fluidCollisionMode - the fluid collision mode
ignorePassableBlocks - whether to ignore passable but collidable blocks (ex. tall grass, signs, fluids, ..)
Returns:
the ray trace hit result, or null if there is no hit
rayTrace
@Nullable
RayTraceResult rayTrace(@NotNull
Location start,
@NotNull
Vector direction,
double maxDistance,
@NotNull
FluidCollisionMode fluidCollisionMode,
boolean ignorePassableBlocks,
double raySize,
@Nullable
Predicate<Entity> filter)
Performs a ray trace that checks for both block and entity collisions.
Block collisions use the blocks' precise collision shapes. The raySize parameter is only taken into account for entity collision checks.
If collisions with passable blocks are ignored, fluid collisions are ignored as well regardless of the fluid collision mode.
Portal blocks are only considered passable if the ray starts within them. Apart from that collisions with portal blocks will be considered even if collisions with passable blocks are otherwise ignored.
This may cause loading of chunks! Some implementations may impose artificial restrictions on the maximum distance.
Parameters:
start - the start location
direction - the ray direction
maxDistance - the maximum distance
fluidCollisionMode - the fluid collision mode
ignorePassableBlocks - whether to ignore passable but collidable blocks (ex. tall grass, signs, fluids, ..)
raySize - entity bounding boxes will be uniformly expanded (or shrinked) by this value before doing collision checks
filter - only entities that fulfill this predicate are considered, or null to consider all entities
Returns:
the closest ray trace hit result with either a block or an entity, or null if there is no hit
getName
@NotNull
String getName()
Gets the unique name of this world
Returns:
Name of this world
getUID
@NotNull
UUID getUID()
Gets the Unique ID of this world
Returns:
Unique ID of this world.
getSpawnLocation
@NotNull
Location getSpawnLocation()
Gets the default spawn Location of this world
Returns:
The spawn location of this world
setSpawnLocation
boolean setSpawnLocation(@NotNull
Location location)
Sets the spawn location of the world.
The location provided must be equal to this world.
Parameters:
location - The Location to set the spawn for this world at.
Returns:
True if it was successfully set.
setSpawnLocation
boolean setSpawnLocation(int x,
int y,
int z,
float angle)
Sets the spawn location of the world
Parameters:
x - X coordinate
y - Y coordinate
z - Z coordinate
angle - the angle
Returns:
True if it was successfully set.
setSpawnLocation
boolean setSpawnLocation(int x,
int y,
int z)
Sets the spawn location of the world
Parameters:
x - X coordinate
y - Y coordinate
z - Z coordinate
Returns:
True if it was successfully set.
getTime
long getTime()
Gets the relative in-game time of this world.
The relative time is analogous to hours * 1000
Returns:
The current relative time
See Also:
Returns an absolute time of this world
setTime
void setTime(long time)
Sets the relative in-game time on the server.
The relative time is analogous to hours * 1000
Note that setting the relative time below the current relative time will actually move the clock forward a day. If you require to rewind time, please see setFullTime(long)
Parameters:
time - The new relative time to set the in-game time to (in hours*1000)
See Also:
Sets the absolute time of this world
getFullTime
long getFullTime()
Gets the full in-game time on this world
Returns:
The current absolute time
See Also:
Returns a relative time of this world
setFullTime
void setFullTime(long time)
Sets the in-game time on the server
Note that this sets the full time of the world, which may cause adverse effects such as breaking redstone clocks and any scheduled events
Parameters:
time - The new absolute time to set this world to
See Also:
Sets the relative time of this world
getGameTime
long getGameTime()
Gets the full in-game time on this world since the world generation
Returns:
The current absolute time since the world generation
See Also:
Returns a relative time of this world, Returns an absolute time of this world
hasStorm
boolean hasStorm()
Returns whether the world has an ongoing storm.
Returns:
Whether there is an ongoing storm
setStorm
void setStorm(boolean hasStorm)
Set whether there is a storm. A duration will be set for the new current conditions. This will implicitly call setClearWeatherDuration(int) with 0 ticks to reset the world's clear weather.
Parameters:
hasStorm - Whether there is rain and snow
getWeatherDuration
int getWeatherDuration()
Get the remaining time in ticks of the current conditions.
Returns:
Time in ticks
setWeatherDuration
void setWeatherDuration(int duration)
Set the remaining time in ticks of the current conditions.
Parameters:
duration - Time in ticks
isThundering
boolean isThundering()
Returns whether there is thunder.
Returns:
Whether there is thunder
setThundering
void setThundering(boolean thundering)
Set whether it is thundering. This will implicitly call setClearWeatherDuration(int) with 0 ticks to reset the world's clear weather.
Parameters:
thundering - Whether it is thundering
getThunderDuration
int getThunderDuration()
Get the thundering duration.
Returns:
Duration in ticks
setThunderDuration
void setThunderDuration(int duration)
Set the thundering duration.
Parameters:
duration - Duration in ticks
isClearWeather
boolean isClearWeather()
Returns whether the world has clear weather. This will be true such that isThundering() and hasStorm() are both false.
Returns:
true if clear weather
setClearWeatherDuration
void setClearWeatherDuration(int duration)
Set the clear weather duration. The clear weather ticks determine whether or not the world will be allowed to rain or storm. If clear weather ticks are > 0, the world will not naturally do either until the duration has elapsed. This method is equivalent to calling /weather clear with a set amount of ticks.
Parameters:
duration - duration in ticks
getClearWeatherDuration
int getClearWeatherDuration()
Get the clear weather duration.
Returns:
duration in ticks
createExplosion
boolean createExplosion(double x,
double y,
double z,
float power)
Creates explosion at given coordinates with given power
Parameters:
x - X coordinate
y - Y coordinate
z - Z coordinate
power - The power of explosion, where 4F is TNT
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(double x,
double y,
double z,
float power,
boolean setFire)
Creates explosion at given coordinates with given power and optionally setting blocks on fire.
Parameters:
x - X coordinate
y - Y coordinate
z - Z coordinate
power - The power of explosion, where 4F is TNT
setFire - Whether or not to set blocks on fire
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(double x,
double y,
double z,
float power,
boolean setFire,
boolean breakBlocks)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
Parameters:
x - X coordinate
y - Y coordinate
z - Z coordinate
power - The power of explosion, where 4F is TNT
setFire - Whether or not to set blocks on fire
breakBlocks - Whether or not to have blocks be destroyed
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(double x,
double y,
double z,
float power,
boolean setFire,
boolean breakBlocks,
@Nullable
Entity source)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
Parameters:
x - X coordinate
y - Y coordinate
z - Z coordinate
power - The power of explosion, where 4F is TNT
setFire - Whether or not to set blocks on fire
breakBlocks - Whether or not to have blocks be destroyed
source - the source entity, used for tracking damage
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(@NotNull
Location loc,
float power)
Creates explosion at given coordinates with given power
Parameters:
loc - Location to blow up
power - The power of explosion, where 4F is TNT
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(@NotNull
Location loc,
float power,
boolean setFire)
Creates explosion at given coordinates with given power and optionally setting blocks on fire.
Parameters:
loc - Location to blow up
power - The power of explosion, where 4F is TNT
setFire - Whether or not to set blocks on fire
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(@NotNull
Location loc,
float power,
boolean setFire,
boolean breakBlocks)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
Parameters:
loc - Location to blow up
power - The power of explosion, where 4F is TNT
setFire - Whether or not to set blocks on fire
breakBlocks - Whether or not to have blocks be destroyed
Returns:
false if explosion was canceled, otherwise true
createExplosion
boolean createExplosion(@NotNull
Location loc,
float power,
boolean setFire,
boolean breakBlocks,
@Nullable
Entity source)
Creates explosion at given coordinates with given power and optionally setting blocks on fire or breaking blocks.
Parameters:
loc - Location to blow up
power - The power of explosion, where 4F is TNT
setFire - Whether or not to set blocks on fire
breakBlocks - Whether or not to have blocks be destroyed
source - the source entity, used for tracking damage
Returns:
false if explosion was canceled, otherwise true
getEnvironment
@NotNull
World.Environment getEnvironment()
Gets the World.Environment type of this world
Returns:
This worlds Environment type
getSeed
long getSeed()
Gets the Seed for this world.
Returns:
This worlds Seed
getPVP
boolean getPVP()
Gets the current PVP setting for this world.
Returns:
True if PVP is enabled
setPVP
void setPVP(boolean pvp)
Sets the PVP setting for this world.
Parameters:
pvp - True/False whether PVP should be Enabled.
getGenerator
@Nullable
ChunkGenerator getGenerator()
Gets the chunk generator for this world
Returns:
ChunkGenerator associated with this world
save
void save()
Saves world to disk
getPopulators
@NotNull
List<BlockPopulator> getPopulators()
Gets a list of all applied BlockPopulators for this World
Returns:
List containing any or none BlockPopulators
spawn
@NotNull
<T extends Entity> T spawn(@NotNull
Location location,
@NotNull
Class<T> clazz)
throws IllegalArgumentException
Spawn an entity of a specific class at the given Location
Type Parameters:
T - the class of the Entity to spawn
Parameters:
location - the Location to spawn the entity at
clazz - the class of the Entity to spawn
Returns:
an instance of the spawned Entity
Throws:
IllegalArgumentException - if either parameter is null or the Entity requested cannot be spawned
spawn
@NotNull
<T extends Entity> T spawn(@NotNull
Location location,
@NotNull
Class<T> clazz,
@Nullable
Consumer<T> function)
throws IllegalArgumentException
Spawn an entity of a specific class at the given Location, with the supplied function run before the entity is added to the world.
Note that when the function is run, the entity will not be actually in the world. Any operation involving such as teleporting the entity is undefined until after this function returns.
Type Parameters:
T - the class of the Entity to spawn
Parameters:
location - the Location to spawn the entity at
clazz - the class of the Entity to spawn
function - the function to be run before the entity is spawned.
Returns:
an instance of the spawned Entity
Throws:
IllegalArgumentException - if either parameter is null or the Entity requested cannot be spawned
spawnFallingBlock
@NotNull
FallingBlock spawnFallingBlock(@NotNull
Location location,
@NotNull
MaterialData data)
throws IllegalArgumentException
Spawn a FallingBlock entity at the given Location of the specified Material. The material dictates what is falling. When the FallingBlock hits the ground, it will place that block.
The Material must be a block type, check with material.isBlock(). The Material may not be air.
Parameters:
location - The Location to spawn the FallingBlock
data - The block data
Returns:
The spawned FallingBlock instance
Throws:
IllegalArgumentException - if Location or MaterialData are null or Material of the MaterialData is not a block
spawnFallingBlock
@NotNull
FallingBlock spawnFallingBlock(@NotNull
Location location,
@NotNull
BlockData data)
throws IllegalArgumentException
Spawn a FallingBlock entity at the given Location of the specified Material. The material dictates what is falling. When the FallingBlock hits the ground, it will place that block.
The Material must be a block type, check with material.isBlock(). The Material may not be air.
Parameters:
location - The Location to spawn the FallingBlock
data - The block data
Returns:
The spawned FallingBlock instance
Throws:
IllegalArgumentException - if Location or BlockData are null
spawnFallingBlock
@Deprecated
@NotNull
FallingBlock spawnFallingBlock(@NotNull
Location location,
@NotNull
Material material,
byte data)
throws IllegalArgumentException
Deprecated.
Magic value
Spawn a FallingBlock entity at the given Location of the specified Material. The material dictates what is falling. When the FallingBlock hits the ground, it will place that block.
The Material must be a block type, check with material.isBlock(). The Material may not be air.
Parameters:
location - The Location to spawn the FallingBlock
material - The block Material type
data - The block data
Returns:
The spawned FallingBlock instance
Throws:
IllegalArgumentException - if Location or Material are null or Material is not a block
playEffect
void playEffect(@NotNull
Location location,
@NotNull
Effect effect,
int data)
Plays an effect to all players within a default radius around a given location.
Parameters:
location - the Location around which players must be to hear the sound
effect - the Effect
data - a data bit needed for some effects
playEffect
void playEffect(@NotNull
Location location,
@NotNull
Effect effect,
int data,
int radius)
Plays an effect to all players within a given radius around a location.
Parameters:
location - the Location around which players must be to hear the effect
effect - the Effect
data - a data bit needed for some effects
radius - the radius around the location
playEffect
<T> void playEffect(@NotNull
Location location,
@NotNull
Effect effect,
@Nullable
T data)
Plays an effect to all players within a default radius around a given location.
Type Parameters:
T - data dependant on the type of effect
Parameters:
location - the Location around which players must be to hear the sound
effect - the Effect
data - a data bit needed for some effects
playEffect
<T> void playEffect(@NotNull
Location location,
@NotNull
Effect effect,
@Nullable
T data,
int radius)
Plays an effect to all players within a given radius around a location.
Type Parameters:
T - data dependant on the type of effect
Parameters:
location - the Location around which players must be to hear the effect
effect - the Effect
data - a data bit needed for some effects
radius - the radius around the location
getEmptyChunkSnapshot
@NotNull
ChunkSnapshot getEmptyChunkSnapshot(int x,
int z,
boolean includeBiome,
boolean includeBiomeTemp)
Get empty chunk snapshot (equivalent to all air blocks), optionally including valid biome data. Used for representing an ungenerated chunk, or for fetching only biome data without loading a chunk.
Parameters:
x - - chunk x coordinate
z - - chunk z coordinate
includeBiome - - if true, snapshot includes per-coordinate biome type
includeBiomeTemp - - if true, snapshot includes per-coordinate raw biome temperature
Returns:
The empty snapshot.
setSpawnFlags
void setSpawnFlags(boolean allowMonsters,
boolean allowAnimals)
Sets the spawn flags for this.
Parameters:
allowMonsters - - if true, monsters are allowed to spawn in this world.
allowAnimals - - if true, animals are allowed to spawn in this world.
getAllowAnimals
boolean getAllowAnimals()
Gets whether animals can spawn in this world.
Returns:
whether animals can spawn in this world.
getAllowMonsters
boolean getAllowMonsters()
Gets whether monsters can spawn in this world.
Returns:
whether monsters can spawn in this world.
getBiome
@NotNull
@Deprecated
Biome getBiome(int x,
int z)
Deprecated.
biomes are now 3-dimensional
Gets the biome for the given block coordinates.
Parameters:
x - X coordinate of the block
z - Z coordinate of the block
Returns:
Biome of the requested block
getBiome
@NotNull
Biome getBiome(int x,
int y,
int z)
Gets the biome for the given block coordinates.
Parameters:
x - X coordinate of the block
y - Y coordinate of the block
z - Z coordinate of the block
Returns:
Biome of the requested block
setBiome
@Deprecated
void setBiome(int x,
int z,
@NotNull
Biome bio)
Deprecated.
biomes are now 3-dimensional
Sets the biome for the given block coordinates
Parameters:
x - X coordinate of the block
z - Z coordinate of the block
bio - new Biome type for this block
setBiome
void setBiome(int x,
int y,
int z,
@NotNull
Biome bio)
Sets the biome for the given block coordinates
Parameters:
x - X coordinate of the block
y - Y coordinate of the block
z - Z coordinate of the block
bio - new Biome type for this block
getTemperature
@Deprecated
double getTemperature(int x,
int z)
Deprecated.
biomes are now 3-dimensional
Gets the temperature for the given block coordinates.
It is safe to run this method when the block does not exist, it will not create the block.
This method will return the raw temperature without adjusting for block height effects.
Parameters:
x - X coordinate of the block
z - Z coordinate of the block
Returns:
Temperature of the requested block
getTemperature
double getTemperature(int x,
int y,
int z)
Gets the temperature for the given block coordinates.
It is safe to run this method when the block does not exist, it will not create the block.
This method will return the raw temperature without adjusting for block height effects.
Parameters:
x - X coordinate of the block
y - Y coordinate of the block
z - Z coordinate of the block
Returns:
Temperature of the requested block
getHumidity
@Deprecated
double getHumidity(int x,
int z)
Deprecated.
biomes are now 3-dimensional
Gets the humidity for the given block coordinates.
It is safe to run this method when the block does not exist, it will not create the block.
Parameters:
x - X coordinate of the block
z - Z coordinate of the block
Returns:
Humidity of the requested block
getHumidity
double getHumidity(int x,
int y,
int z)
Gets the humidity for the given block coordinates.
It is safe to run this method when the block does not exist, it will not create the block.
Parameters:
x - X coordinate of the block
y - Y coordinate of the block
z - Z coordinate of the block
Returns:
Humidity of the requested block
getMinHeight
int getMinHeight()
Gets the minimum height of this world.
If the min height is 0, there are only blocks from y=0.
Returns:
Minimum height of the world
getMaxHeight
int getMaxHeight()
Gets the maximum height of this world.
If the max height is 100, there are only blocks from y=0 to y=99.
Returns:
Maximum height of the world
getSeaLevel
int getSeaLevel()
Gets the sea level for this world.
This is often half of getMaxHeight()
Returns:
Sea level
getKeepSpawnInMemory
boolean getKeepSpawnInMemory()
Gets whether the world's spawn area should be kept loaded into memory or not.
Returns:
true if the world's spawn area will be kept loaded into memory.
setKeepSpawnInMemory
void setKeepSpawnInMemory(boolean keepLoaded)
Sets whether the world's spawn area should be kept loaded into memory or not.
Parameters:
keepLoaded - if true then the world's spawn area will be kept loaded into memory.
isAutoSave
boolean isAutoSave()
Gets whether or not the world will automatically save
Returns:
true if the world will automatically save, otherwise false
setAutoSave
void setAutoSave(boolean value)
Sets whether or not the world will automatically save
Parameters:
value - true if the world should automatically save, otherwise false
setDifficulty
void setDifficulty(@NotNull
Difficulty difficulty)
Sets the Difficulty of the world.
Parameters:
difficulty - the new difficulty you want to set the world to
getDifficulty
@NotNull
Difficulty getDifficulty()
Gets the Difficulty of the world.
Returns:
The difficulty of the world.
getWorldFolder
@NotNull
File getWorldFolder()
Gets the folder of this world on disk.
Returns:
The folder of this world.
getWorldType
@Nullable
@Deprecated
WorldType getWorldType()
Deprecated.
world type is only used to select the default word generation settings and is not stored in Vanilla worlds, making it impossible for this method to always return the correct value.
Gets the type of this world.
Returns:
Type of this world.
canGenerateStructures
boolean canGenerateStructures()
Gets whether or not structures are being generated.
Returns:
True if structures are being generated.
isHardcore
boolean isHardcore()
Gets whether the world is hardcore or not. In a hardcore world the difficulty is locked to hard.
Returns:
hardcore status
setHardcore
void setHardcore(boolean hardcore)
Sets whether the world is hardcore or not. In a hardcore world the difficulty is locked to hard.
Parameters:
hardcore - Whether the world is hardcore
getTicksPerAnimalSpawns
long getTicksPerAnimalSpawns()
Gets the world's ticks per animal spawns value
This value determines how many ticks there are between attempts to spawn animals.
Example Usage:
A value of 1 will mean the server will attempt to spawn animals in this world every tick.
A value of 400 will mean the server will attempt to spawn animals in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, animal spawning will be disabled for this world. We recommend using setSpawnFlags(boolean, boolean) to control this instead.
Minecraft default: 400.
Returns:
The world's ticks per animal spawns value
setTicksPerAnimalSpawns
void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns)
Sets the world's ticks per animal spawns value
This value determines how many ticks there are between attempts to spawn animals.
Example Usage:
A value of 1 will mean the server will attempt to spawn animals in this world every tick.
A value of 400 will mean the server will attempt to spawn animals in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, animal spawning will be disabled for this world. We recommend using setSpawnFlags(boolean, boolean) to control this instead.
Minecraft default: 400.
Parameters:
ticksPerAnimalSpawns - the ticks per animal spawns value you want to set the world to
getTicksPerMonsterSpawns
long getTicksPerMonsterSpawns()
Gets the world's ticks per monster spawns value
This value determines how many ticks there are between attempts to spawn monsters.
Example Usage:
A value of 1 will mean the server will attempt to spawn monsters in this world every tick.
A value of 400 will mean the server will attempt to spawn monsters in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, monsters spawning will be disabled for this world. We recommend using setSpawnFlags(boolean, boolean) to control this instead.
Minecraft default: 1.
Returns:
The world's ticks per monster spawns value
setTicksPerMonsterSpawns
void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns)
Sets the world's ticks per monster spawns value
This value determines how many ticks there are between attempts to spawn monsters.
Example Usage:
A value of 1 will mean the server will attempt to spawn monsters in this world on every tick.
A value of 400 will mean the server will attempt to spawn monsters in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, monsters spawning will be disabled for this world. We recommend using setSpawnFlags(boolean, boolean) to control this instead.
Minecraft default: 1.
Parameters:
ticksPerMonsterSpawns - the ticks per monster spawns value you want to set the world to
getTicksPerWaterSpawns
long getTicksPerWaterSpawns()
Gets the world's ticks per water mob spawns value
This value determines how many ticks there are between attempts to spawn water mobs.
Example Usage:
A value of 1 will mean the server will attempt to spawn water mobs in this world every tick.
A value of 400 will mean the server will attempt to spawn water mobs in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, water mobs spawning will be disabled for this world.
Minecraft default: 1.
Returns:
The world's ticks per water mob spawns value
setTicksPerWaterSpawns
void setTicksPerWaterSpawns(int ticksPerWaterSpawns)
Sets the world's ticks per water mob spawns value
This value determines how many ticks there are between attempts to spawn water mobs.
Example Usage:
A value of 1 will mean the server will attempt to spawn water mobs in this world on every tick.
A value of 400 will mean the server will attempt to spawn water mobs in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, water mobs spawning will be disabled for this world.
Minecraft default: 1.
Parameters:
ticksPerWaterSpawns - the ticks per water mob spawns value you want to set the world to
getTicksPerWaterAmbientSpawns
long getTicksPerWaterAmbientSpawns()
Gets the default ticks per water ambient mob spawns value.
Example Usage:
A value of 1 will mean the server will attempt to spawn water ambient mobs every tick.
A value of 400 will mean the server will attempt to spawn water ambient mobs every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, ambient mobs spawning will be disabled.
Minecraft default: 1.
Returns:
the default ticks per water ambient mobs spawn value
setTicksPerWaterAmbientSpawns
void setTicksPerWaterAmbientSpawns(int ticksPerAmbientSpawns)
Sets the world's ticks per water ambient mob spawns value
This value determines how many ticks there are between attempts to spawn water ambient mobs.
Example Usage:
A value of 1 will mean the server will attempt to spawn water ambient mobs in this world on every tick.
A value of 400 will mean the server will attempt to spawn weater ambient mobs in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, water ambient mobs spawning will be disabled for this world.
Minecraft default: 1.
Parameters:
ticksPerAmbientSpawns - the ticks per water ambient mob spawns value you want to set the world to
getTicksPerAmbientSpawns
long getTicksPerAmbientSpawns()
Gets the world's ticks per ambient mob spawns value
This value determines how many ticks there are between attempts to spawn ambient mobs.
Example Usage:
A value of 1 will mean the server will attempt to spawn ambient mobs in this world every tick.
A value of 400 will mean the server will attempt to spawn ambient mobs in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, ambient mobs spawning will be disabled for this world.
Minecraft default: 1.
Returns:
The world's ticks per ambient mob spawns value
setTicksPerAmbientSpawns
void setTicksPerAmbientSpawns(int ticksPerAmbientSpawns)
Sets the world's ticks per ambient mob spawns value
This value determines how many ticks there are between attempts to spawn ambient mobs.
Example Usage:
A value of 1 will mean the server will attempt to spawn ambient mobs in this world on every tick.
A value of 400 will mean the server will attempt to spawn ambient mobs in this world every 400th tick.
A value below 0 will be reset back to Minecraft's default.
Note: If set to 0, ambient mobs spawning will be disabled for this world.
Minecraft default: 1.
Parameters:
ticksPerAmbientSpawns - the ticks per ambient mob spawns value you want to set the world to
getMonsterSpawnLimit
int getMonsterSpawnLimit()
Gets limit for number of monsters that can spawn in a chunk in this world
Returns:
The monster spawn limit
setMonsterSpawnLimit
void setMonsterSpawnLimit(int limit)
Sets the limit for number of monsters that can spawn in a chunk in this world
Note: If set to a negative number the world will use the server-wide spawn limit instead.
Parameters:
limit - the new mob limit
getAnimalSpawnLimit
int getAnimalSpawnLimit()
Gets the limit for number of animals that can spawn in a chunk in this world
Returns:
The animal spawn limit
setAnimalSpawnLimit
void setAnimalSpawnLimit(int limit)
Sets the limit for number of animals that can spawn in a chunk in this world
Note: If set to a negative number the world will use the server-wide spawn limit instead.
Parameters:
limit - the new mob limit
getWaterAnimalSpawnLimit
int getWaterAnimalSpawnLimit()
Gets the limit for number of water animals that can spawn in a chunk in this world
Returns:
The water animal spawn limit
setWaterAnimalSpawnLimit
void setWaterAnimalSpawnLimit(int limit)
Sets the limit for number of water animals that can spawn in a chunk in this world
Note: If set to a negative number the world will use the server-wide spawn limit instead.
Parameters:
limit - the new mob limit
getWaterAmbientSpawnLimit
int getWaterAmbientSpawnLimit()
Gets user-specified limit for number of water ambient mobs that can spawn in a chunk.
Returns:
the water ambient spawn limit
setWaterAmbientSpawnLimit
void setWaterAmbientSpawnLimit(int limit)
Sets the limit for number of water ambient mobs that can spawn in a chunk in this world
Note: If set to a negative number the world will use the server-wide spawn limit instead.
Parameters:
limit - the new mob limit
getAmbientSpawnLimit
int getAmbientSpawnLimit()
Gets the limit for number of ambient mobs that can spawn in a chunk in this world
Returns:
The ambient spawn limit
setAmbientSpawnLimit
void setAmbientSpawnLimit(int limit)
Sets the limit for number of ambient mobs that can spawn in a chunk in this world
Note: If set to a negative number the world will use the server-wide spawn limit instead.
Parameters:
limit - the new mob limit
playSound
void playSound(@NotNull
Location location,
@NotNull
Sound sound,
float volume,
float pitch)
Play a Sound at the provided Location in the World
This function will fail silently if Location or Sound are null.
Parameters:
location - The location to play the sound
sound - The sound to play
volume - The volume of the sound
pitch - The pitch of the sound
playSound
void playSound(@NotNull
Location location,
@NotNull
String sound,
float volume,
float pitch)
Play a Sound at the provided Location in the World.
This function will fail silently if Location or Sound are null. No sound will be heard by the players if their clients do not have the respective sound for the value passed.
Parameters:
location - the location to play the sound
sound - the internal sound name to play
volume - the volume of the sound
pitch - the pitch of the sound
playSound
void playSound(@NotNull
Location location,
@NotNull
Sound sound,
@NotNull
SoundCategory category,
float volume,
float pitch)
Play a Sound at the provided Location in the World.
This function will fail silently if Location or Sound are null.
Parameters:
location - The location to play the sound
sound - The sound to play
category - the category of the sound
volume - The volume of the sound
pitch - The pitch of the sound
playSound
void playSound(@NotNull
Location location,
@NotNull
String sound,
@NotNull
SoundCategory category,
float volume,
float pitch)
Play a Sound at the provided Location in the World.
This function will fail silently if Location or Sound are null. No sound will be heard by the players if their clients do not have the respective sound for the value passed.
Parameters:
location - the location to play the sound
sound - the internal sound name to play
category - the category of the sound
volume - the volume of the sound
pitch - the pitch of the sound
getGameRules
@NotNull
String[] getGameRules()
Get an array containing the names of all the GameRules.
Returns:
An array of GameRule names.
getGameRuleValue
@Deprecated
@Contract("null -> null; !null -> !null")
@Nullable
String getGameRuleValue(@Nullable
String rule)
Deprecated.
use getGameRuleValue(GameRule) instead
Gets the current state of the specified rule
Will return null if rule passed is null
Parameters:
rule - Rule to look up value of
Returns:
String value of rule
setGameRuleValue
@Deprecated
boolean setGameRuleValue(@NotNull
String rule,
@NotNull
String value)
Deprecated.
use setGameRule(GameRule, Object) instead.
Set the specified gamerule to specified value.
The rule may attempt to validate the value passed, will return true if value was set.
If rule is null, the function will return false.
Parameters:
rule - Rule to set
value - Value to set rule to
Returns:
True if rule was set
isGameRule
boolean isGameRule(@NotNull
String rule)
Checks if string is a valid game rule
Parameters:
rule - Rule to check
Returns:
True if rule exists
getGameRuleValue
@Nullable
<T> T getGameRuleValue(@NotNull
GameRule<T> rule)
Get the current value for a given GameRule.
Type Parameters:
T - the GameRule's type
Parameters:
rule - the GameRule to check
Returns:
the current value
getGameRuleDefault
@Nullable
<T> T getGameRuleDefault(@NotNull
GameRule<T> rule)
Get the default value for a given GameRule. This value is not guaranteed to match the current value.
Type Parameters:
T - the type of GameRule
Parameters:
rule - the rule to return a default value for
Returns:
the default value
setGameRule
<T> boolean setGameRule(@NotNull
GameRule<T> rule,
@NotNull
T newValue)
Set the given GameRule's new value.
Type Parameters:
T - the value type of the GameRule
Parameters:
rule - the GameRule to update
newValue - the new value
Returns:
true if the value was successfully set
getWorldBorder
@NotNull
WorldBorder getWorldBorder()
Gets the world border for this world.
Returns:
The world border for this world.
spawnParticle
void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count)
Spawns the particle (the number of times specified by count) at the target location.
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
spawnParticle
void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count)
Spawns the particle (the number of times specified by count) at the target location.
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count,
@Nullable
T data)
Spawns the particle (the number of times specified by count) at the target location.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count,
@Nullable
T data)
Spawns the particle (the number of times specified by count) at the target location.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
spawnParticle
void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count,
double offsetX,
double offsetY,
double offsetZ)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
spawnParticle
void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count,
double offsetX,
double offsetY,
double offsetZ)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count,
double offsetX,
double offsetY,
double offsetZ,
@Nullable
T data)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count,
double offsetX,
double offsetY,
double offsetZ,
@Nullable
T data)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
spawnParticle
void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count,
double offsetX,
double offsetY,
double offsetZ,
double extra)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
extra - the extra data for this particle, depends on the particle used (normally speed)
spawnParticle
void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count,
double offsetX,
double offsetY,
double offsetZ,
double extra)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
extra - the extra data for this particle, depends on the particle used (normally speed)
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count,
double offsetX,
double offsetY,
double offsetZ,
double extra,
@Nullable
T data)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
extra - the extra data for this particle, depends on the particle used (normally speed)
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count,
double offsetX,
double offsetY,
double offsetZ,
double extra,
@Nullable
T data)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
extra - the extra data for this particle, depends on the particle used (normally speed)
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
@NotNull
Location location,
int count,
double offsetX,
double offsetY,
double offsetZ,
double extra,
@Nullable
T data,
boolean force)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
location - the location to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
extra - the extra data for this particle, depends on the particle used (normally speed)
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
force - whether to send the particle to players within an extended range and encourage their client to render it regardless of settings
spawnParticle
<T> void spawnParticle(@NotNull
Particle particle,
double x,
double y,
double z,
int count,
double offsetX,
double offsetY,
double offsetZ,
double extra,
@Nullable
T data,
boolean force)
Spawns the particle (the number of times specified by count) at the target location. The position of each particle will be randomized positively and negatively by the offset parameters on each axis.
Type Parameters:
T - type of particle data (see Particle.getDataType()
Parameters:
particle - the particle to spawn
x - the position on the x axis to spawn at
y - the position on the y axis to spawn at
z - the position on the z axis to spawn at
count - the number of particles
offsetX - the maximum random offset on the X axis
offsetY - the maximum random offset on the Y axis
offsetZ - the maximum random offset on the Z axis
extra - the extra data for this particle, depends on the particle used (normally speed)
data - the data to use for the particle or null, the type of this depends on Particle.getDataType()
force - whether to send the particle to players within an extended range and encourage their client to render it regardless of settings
locateNearestStructure
@Nullable
Location locateNearestStructure(@NotNull
Location origin,
@NotNull
StructureType structureType,
int radius,
boolean findUnexplored)
Find the closest nearby structure of a given StructureType. Finding unexplored structures can, and will, block if the world is looking in chunks that gave not generated yet. This can lead to the world temporarily freezing while locating an unexplored structure.
The radius is not a rigid square radius. Each structure may alter how many chunks to check for each iteration. Do not assume that only a radius x radius chunk area will be checked. For example, StructureType.WOODLAND_MANSION can potentially check up to 20,000 blocks away (or more) regardless of the radius used.
This will not load or generate chunks. This can also lead to instances where the server can hang if you are only looking for unexplored structures. This is because it will keep looking further and further out in order to find the structure.
Parameters:
origin - where to start looking for a structure
structureType - the type of structure to find
radius - the radius, in chunks, around which to search
findUnexplored - true to only find unexplored structures
Returns:
the closest Location, or null if no structure of the specified type exists.
getViewDistance
int getViewDistance()
Returns the view distance used for this world.
Returns:
the view distance used for this world
spigot
@NotNull
World.Spigot spigot()
locateNearestRaid
@Nullable
Raid locateNearestRaid(@NotNull
Location location,
int radius)
Finds the nearest raid close to the given location.
Parameters:
location - the origin location
radius - the radius
Returns:
the closest Raid, or null if no raids were found
getRaids
@NotNull
List<Raid> getRaids()
Gets all raids that are going on over this world.
Returns:
the list of all active raids
getEnderDragonBattle
@Nullable
DragonBattle getEnderDragonBattle()
Get the DragonBattle associated with this world. If this world's environment is not World.Environment.THE_END, null will be returned.
If an end world, a dragon battle instance will be returned regardless of whether or not a dragon is present in the world or a fight sequence has been activated. The dragon battle instance acts as a state holder.
Returns:
the dragon battle instance
"
|
54ea5ab3b17f8681bda6a8037fc5a012
|
{
"intermediate": 0.30805504322052,
"beginner": 0.40903133153915405,
"expert": 0.2829136252403259
}
|
37,852
|
Write out the responsibilities on a resume for a water damage restoration project manager / technician in list format. Output nothing but a list
|
dbb39df75035f7ae95c4ba8d032c9c3d
|
{
"intermediate": 0.3896547853946686,
"beginner": 0.2718110680580139,
"expert": 0.33853423595428467
}
|
37,853
|
I would like to add command to Adobe Bridge which automatically analyze the image via AI and write an Exit info such as title, description and keywords.
|
0d76dec372861be7f0bbebfa8405d9bc
|
{
"intermediate": 0.28064948320388794,
"beginner": 0.11868171393871307,
"expert": 0.6006687879562378
}
|
37,854
|
I wanna make it display info on the interactions, the ip and useragent for now
from flask import Flask, render_template, request, jsonify
import sqlite3
app = Flask(__name__)
def query_database(query, limit, offset):
connection = sqlite3.connect('leaks.db')
cursor = connection.cursor()
try:
# Execute the query based on the provided search query, limit, and offset
pattern = f"%{query}%"
query_sql = "SELECT * FROM data WHERE data LIKE ? LIMIT ? OFFSET ?"
cursor.execute(query_sql, (pattern, limit, offset))
# Fetch the results
results = cursor.fetchall()
# Return the results as a list of dictionaries
columns = [col[0] for col in cursor.description]
results_list = [dict(zip(columns, row)) for row in results]
return results_list
except sqlite3.Error as e:
# Print the SQLite error for debugging
print(f"SQLite error: {e}")
return {"error": f"SQLite error: {e}"}
finally:
connection.close()
@app.route('/')
def index():
return render_template('search.html')
@app.route('/test-page')
def text():
return render_template('test.html')
@app.route('/search', methods=['GET'])
def search():
# Get the 'query', 'limit', and 'offset' parameters from the request
query = request.args.get('query', default='', type=str)
limit = request.args.get('limit', default=10, type=int)
offset = request.args.get('offset', default=0, type=int)
# Call the query_database function with the provided parameters
results = query_database(query, limit, offset)
# Return the results as JSON
return jsonify(results)
if __name__ == "__main__":
app.run(debug=True)
|
60e1c12ff7d3a9acb7c9ee31ca282b5d
|
{
"intermediate": 0.7703714370727539,
"beginner": 0.15870536863803864,
"expert": 0.07092320919036865
}
|
37,855
|
Please can I have a VBA code that can do the following:
In sheet 'BOOKINGS' from A2 go down the column and from the dates within the cells,
find and locate all dates that fall within the current week (Monday to Sunday).
once found, select all the cell rows from column A to I,
then copy the selection and paste values only without any formatting into the sheet 'THISWEEK' starting at A2.
Before pasting into into the sheet 'THISWEEK' delete the contents only of 'THISWEEK' that have values from A2 to I100.
|
b1588ac74708e41aa578ef6a7a8d6360
|
{
"intermediate": 0.5169377326965332,
"beginner": 0.14045453071594238,
"expert": 0.3426077365875244
}
|
37,856
|
I need a VBA code that will force the sheet 'AdminMCS' to activate when the workbook is opened
|
0db1fb30a528075665564fbab9fdfbbe
|
{
"intermediate": 0.39083603024482727,
"beginner": 0.21109162271022797,
"expert": 0.39807233214378357
}
|
37,857
|
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
def generate_linear_equations(number_of_samples, max_int=100):
a_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
x_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
b_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
c_values = a_values * x_values + b_values # Compute c in ax + b = c
equations = np.concatenate((a_values, b_values, c_values), axis=1)
return equations, x_values
# Expert LSTM Model
class LSTMExpert(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTMExpert, self).__init__()
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
h = h[:, -1, :] # taking the last sequence output
return self.fc(h)
# Gating Network
class GatingNetwork(nn.Module):
def __init__(self, input_size, num_experts):
super(GatingNetwork, self).__init__()
self.fc = nn.Linear(input_size, num_experts)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
# Flatten if needed (in case input comes from LSTM with sequence length)
if x.dim() > 2:
x = x.view(x.size(0), -1)
x = self.fc(x)
return self.softmax(x)
# Mixture of Experts Model
class MixtureOfExperts(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_experts):
super(MixtureOfExperts, self).__init__()
self.num_experts = num_experts
self.experts = nn.ModuleList([LSTMExpert(input_size, hidden_size, output_size) for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Compute the gating weights
gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1]
# Compute the output from each expert for every example
expert_outputs = [expert(x) for expert in self.experts]
expert_outputs = torch.stack(expert_outputs, dim=-1) # [batch_size, output_size, num_experts]
# Multiply gating scores by expert outputs and sum the result
# torch.bmm expects [batch_size, n, m] and [batch_size, m, p]
# here it will do [batch_size, output_size, num_experts] bmm [batch_size, num_experts, 1]
mixed_output = torch.bmm(expert_outputs, gating_scores)
# Now mixed_output has shape [batch_size, output_size, 1], we should squeeze it to [batch_size, output_size]
mixed_output = mixed_output.squeeze(-1)
return mixed_output
class SingleLSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers=3): # This model will have more parameters
super(SingleLSTM, self).__init__()
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
h = h[:, -1, :] # taking the last sequence output
return self.fc(h)
# Simple Positional Encoding (not learnable, for simplicity)
def positional_encoding(seq_len, d_model, device):
pos = torch.arange(seq_len, dtype=torch.float, device=device).reshape(1, -1, 1)
dim = torch.arange(d_model, dtype=torch.float, device=device).reshape(1, 1, -1)
phase = pos / (1e4 ** (dim // d_model))
return torch.where(dim.long() % 2 == 0, torch.sin(phase), torch.cos(phase))
class SimpleTransformer(nn.Module):
def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1):
super(SimpleTransformer, self).__init__()
self.d_model = d_model
self.input_fc = nn.Linear(input_size, d_model) # Linear layer to project to model dimension
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
batch_first=True) # Added batch_first=True
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers)
self.output_fc = nn.Linear(d_model, output_size)
def forward(self, x):
seq_len, batch_size, _ = x.size()
x = self.input_fc(x) + positional_encoding(seq_len, self.d_model, x.device)
# Adding positional encodings
pos_enc = positional_encoding(seq_len, self.d_model, x.device)
x = x + pos_enc
# Passing the input through the Transformer
transformer_output = self.transformer_encoder(x)
# Taking only the result from the last token in the sequence
transformer_output = transformer_output[-1, :, :]
# Final fully connected layer to produce the output
output = self.output_fc(transformer_output)
return output.squeeze(-1) # Remove the last dimension for compatibility with the target
class TransformerExpert(nn.Module):
def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1):
super(TransformerExpert, self).__init__()
self.d_model = d_model
self.input_fc = nn.Linear(input_size, d_model) # Linear layer to project to model dimension
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True)
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers)
self.output_fc = nn.Linear(d_model, output_size)
def forward(self, x):
x = self.input_fc(x)
x += positional_encoding(x.size(1), self.d_model, x.device)
transformer_output = self.transformer_encoder(x)
transformer_output = transformer_output[:, -1, :]
output = self.output_fc(transformer_output)
return output
class MoETransformer(nn.Module):
def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1):
super(MoETransformer, self).__init__()
self.num_experts = num_experts
self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers)
for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Compute the gating weights
gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1]
# Compute the output from each expert for every example
expert_outputs = [expert(x).unsqueeze(2) for expert in self.experts] # [batch_size, output_size, 1]
expert_outputs = torch.cat(expert_outputs, dim=2) # [batch_size, output_size, num_experts]
# Multiply gating scores by expert outputs and sum the result
mixed_output = torch.bmm(expert_outputs, gating_scores) # [batch_size, output_size, 1]
# Now mixed_output has shape [batch_size, output_size, 1], we squeeze it to [batch_size, output_size]
mixed_output = mixed_output.squeeze(-1)
return mixed_output
def train_model(model, criterion, optimizer, num_epochs, batch_size, equations_tensor, solutions_tensor):
model.train()
training_losses = []
for epoch in range(num_epochs):
total_loss = 0
# Shuffle the data
perm = torch.randperm(equations_tensor.size(0))
equations_shuffled = equations_tensor[perm]
solutions_shuffled = solutions_tensor[perm]
for i in range(0, equations_tensor.size(0), batch_size):
# Slice out the batches
x_batch = equations_shuffled[i:i+batch_size]
y_batch = solutions_shuffled[i:i+batch_size]
optimizer.zero_grad()
predictions = model(x_batch)
predictions = predictions.squeeze() # Ensure predictions and targets have the same size
loss = criterion(predictions, y_batch.view(-1)) # Flatten the target tensor
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / (equations_tensor.size(0) / batch_size)
training_losses.append(average_loss)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
return training_losses
# Parameters for the Transformer model
d_model = 128
nhead = 4
dim_feedforward = 256
input_size = 3 # a, b, and c from equation ax + b = c
hidden_size = 32
output_size = 1 # we are predicting the value of x
num_experts = 10
# Training parameters
num_epochs = 20
batch_size = 128
# Reshape the equations to (batch_size, seq_length, features)
# For simplicity, we consider each equation as a sequence of length 1
# Generate the data only once before training
equations_tensor, solutions_tensor = generate_linear_equations(number_of_samples=5000)
# Convert numpy arrays to torch tensors
equations_tensor = torch.from_numpy(equations_tensor).float()
solutions_tensor = torch.from_numpy(solutions_tensor).float()
# Reshape the equations and solutions to (batch_size, seq_length, features)
train_equations_tensor = equations_tensor.view(-1, 1, input_size) # reshaping once, correctly
train_solutions_tensor = solutions_tensor.view(-1, 1) # reshaping for solutions to match batch size
# Instantiate the MoE-Transformer model
moe_transformer_model = MoETransformer(input_size=input_size, d_model=d_model, output_size=output_size, nhead=nhead, dim_feedforward=dim_feedforward, num_experts=num_experts)
moe_transformer_optimizer = torch.optim.Adam(moe_transformer_model.parameters())
moe_transformer_criterion = nn.MSELoss()
# Instantiate the SimpleTransformer model
transformer_model = SimpleTransformer(input_size=input_size, d_model=d_model, output_size=output_size, nhead=nhead, dim_feedforward=dim_feedforward)
transformer_optimizer = torch.optim.Adam(transformer_model.parameters())
transformer_criterion = nn.MSELoss()
# Instantiate the MoE model
moe_model = MixtureOfExperts(input_size, hidden_size*2, output_size, num_experts)
moe_optimizer = torch.optim.Adam(moe_model.parameters())
moe_criterion = nn.MSELoss()
# Instantiate the Single General LSTM model
large_model = SingleLSTM(input_size, hidden_size*2, output_size, num_layers=4) # Adjusted to have comparable number of parameters
large_optimizer = torch.optim.Adam(large_model.parameters())
large_criterion = nn.MSELoss()
# Print the parameter count of the MoE-Transformer
print("MoE-Transformer Parameter Count:", sum(p.numel() for p in moe_transformer_model.parameters()))
# Print the parameter count of the Transformer
print("Transformer Parameter Count:", sum(p.numel() for p in transformer_model.parameters()))
# Print the parameter count of the MoE LSTM
print("MoE LSTM Parameter Count:", sum(p.numel() for p in moe_model.parameters()))
# Print the parameter count of the Single LSTM
print("Single LSTM Parameter Count:", sum(p.numel() for p in large_model.parameters()))
# Train the MoE Transformer model
moe_transformer_losses = train_model(moe_transformer_model, moe_transformer_criterion, moe_transformer_optimizer,num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Train the Transformer model
transformer_losses = train_model(transformer_model, transformer_criterion, transformer_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Train the MoE model
moe_losses = train_model(moe_model, moe_criterion, moe_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Train the Single LSTM model
large_losses = train_model(large_model, large_criterion, large_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
# Plot the results, as before
plt.figure(figsize=(12, 8))
plt.plot(moe_losses, label="Mixture of Experts Loss")
plt.plot(large_losses, label="Single LSTM Model Loss")
plt.plot(transformer_losses, label="Simple Transformer Model Loss")
plt.plot(moe_transformer_losses, label="MoE Transformer Model Loss")
plt.xlabel("Epoch")
plt.ylabel("MSE Loss")
plt.legend()
plt.title("Model Loss Comparison")
plt.show()
|
5c18165695e5d56be8518208f5ac8897
|
{
"intermediate": 0.3398807942867279,
"beginner": 0.3772202134132385,
"expert": 0.28289899230003357
}
|
37,858
|
Hello
|
1eac6108f43e0d4d0bff41fd94c2c716
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
37,859
|
I have a VBA code that I usually run once a week.
Can you write me a code that I can include in the event that will do the following:
When I run the code,
it will check for the column A in the sheet 'List' for the last cell with a date.
It will the pop up a Yes No message saying "This event was last run on (the date found in column A of the sheet List).
If I chose Yes the rest of the event will proceed and if I choose No the event is aborted.
If I do choose Yes, the code will save the current date and time to a sheet named "List" in the next available cell in column A, before proceeding with the rest of my code.
|
3f281b17413535c5962f96bebb898058
|
{
"intermediate": 0.5175719857215881,
"beginner": 0.21252508461475372,
"expert": 0.26990294456481934
}
|
37,860
|
create a horror story that has two friends
|
6e3104f130ab97cb98ca07b6044c9575
|
{
"intermediate": 0.3402908742427826,
"beginner": 0.37382712960243225,
"expert": 0.28588196635246277
}
|
37,861
|
can you give me some example about Accounting Equation from trial balce
|
0ef567fb47c87ed20cb9c30cbdcf65c3
|
{
"intermediate": 0.36657580733299255,
"beginner": 0.39169925451278687,
"expert": 0.2417249232530594
}
|
37,862
|
You must be completely rewrite the code for Firefox, note tabCapture does not support Firefox. Fully code without comments
|
9706f0e83d2f46750cc101f799f58ec5
|
{
"intermediate": 0.31113049387931824,
"beginner": 0.36939871311187744,
"expert": 0.31947076320648193
}
|
37,863
|
You must be completely rewrite the code for Firefox, note tabCapture does not support Firefox. Fully code without comments
|
79142e839b6260469cf89fe20b2e39b0
|
{
"intermediate": 0.31113049387931824,
"beginner": 0.36939871311187744,
"expert": 0.31947076320648193
}
|
37,865
|
You must rewrite the code from Chrome for Firefox, remember tabCapture is not supported by Firefox. Show me fully rewrited code
|
78ae47e81df798bcbc3ea7863b4641dc
|
{
"intermediate": 0.38961726427078247,
"beginner": 0.29263436794281006,
"expert": 0.31774836778640747
}
|
37,866
|
H
|
ef2e2ea433c14b759a2a250a3dc7c940
|
{
"intermediate": 0.32187700271606445,
"beginner": 0.31201374530792236,
"expert": 0.3661092221736908
}
|
37,867
|
Give me the code for gui todo app using python
|
34b8389641d2cad50c65bc2d29cb6040
|
{
"intermediate": 0.684120774269104,
"beginner": 0.15822342038154602,
"expert": 0.15765585005283356
}
|
37,868
|
import torch
from mamba_ssm import Mamba
batch, length, dim = 2, 64, 16
x = torch.randn(batch, length, dim).to("cuda")
model = Mamba(
# This module uses roughly 3 * expand * d_model^2 parameters
d_model=dim, # Model dimension d_model
d_state=16, # SSM state expansion factor
d_conv=4, # Local convolution width
expand=2, # Block expansion factor
).to("cuda")
y = model(x)
assert y.shape == x.shape
|
5c617b26f053e7780769e8049d4a08ba
|
{
"intermediate": 0.4111619293689728,
"beginner": 0.2592029273509979,
"expert": 0.3296351730823517
}
|
37,869
|
In unity, using c#, create a script for a lovecraftian horror system for a game
|
4a0ff1f6eb11390b368e90a7e12a03cc
|
{
"intermediate": 0.3854212462902069,
"beginner": 0.3557246923446655,
"expert": 0.2588540315628052
}
|
37,870
|
Add a loop to the last section of the code where an input is passed to the model to generate text: import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
from collections import Counter
class TextDataset(Dataset):
def __init__(self, path, seq_len):
self.seq_len = seq_len
with open(path, "r", encoding="utf-8") as f:
text = f.read()
words = text.split()
self.vocab, self.idx2token = self.build_vocab(words)
self.tokens = [self.vocab.get(w, 0) for w in words] # Default to 0 for unknown tokens
def build_vocab(self, words):
counts = Counter(words)
vocab = {word: i for i, (word, _) in enumerate(counts.most_common(), 1)}
vocab["<pad>"] = 0
idx2token = {i: word for word, i in vocab.items()}
return vocab, idx2token
def __len__(self):
return len(self.tokens) // self.seq_len
def __getitem__(self, idx):
chunk = self.tokens[idx * self.seq_len: (idx + 1) * self.seq_len]
x = chunk[:-1]
y = chunk[1:]
return torch.tensor(x), torch.tensor(y)
def collate_fn(batch):
inputs, targets = zip(*batch)
inputs = pad_sequence(inputs, batch_first=True, padding_value=0)
targets = pad_sequence(targets, batch_first=True, padding_value=0)
return inputs, targets
# Set the path to your text file and define sequence length
path_to_text = 'C:/Users/Dell-PC/Desktop/Simple_Transfomer.txt' # replace with the path to your text file
seq_len = 30 # sequence length
# Create a dataset and data loader
dataset = TextDataset(path_to_text, seq_len)
data_loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn)
class SingleLSTM_TXT(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers=3):
# In a language model, input_size is usually the dimension of the embedding vector,
# and output_size is the size of the vocabulary.
super(SingleLSTM_TXT, self).__init__()
self.embedding = nn.Embedding(num_embeddings=output_size, embedding_dim=input_size)
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
embedded = self.embedding(x)
h, _ = self.lstm(embedded)
# You may need to reshape h if you want to include more than the last LSTM output
h = h.reshape(-1, h.shape[-1])
return self.fc(h)
def train_model_TXT(model, criterion, optimizer, num_epochs, data_loader):
model.train()
for epoch in range(num_epochs):
total_loss = 0
for inputs, targets in data_loader:
optimizer.zero_grad()
predictions = model(inputs)
loss = criterion(predictions, targets.view(-1))
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / len(data_loader.dataset)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
def generate_text(model, dataset, seed_text, num_generate, temperature=1.0):
model.eval() # Put the model in evaluation mode
# List to store the generated tokens
generated_tokens = []
# Initial sequence (prefix) to start the generation process
input_sequence = [dataset.vocab.get(word, 0) for word in seed_text.split()] # Convert to token IDs
current_sequence = torch.tensor(input_sequence, dtype=torch.long).unsqueeze(0)
# Generate num_generate tokens
for _ in range(num_generate):
# Forward pass through the model
with torch.no_grad():
output = model(current_sequence)
# Get probabilities, apply temperature scaling, and sample from the distribution
probabilities = F.softmax(output[-1] / temperature, dim=0).detach()
next_token_idx = torch.multinomial(probabilities, 1).item()
# Append token to the current sequence and to the generated tokens
generated_tokens.append(next_token_idx)
current_sequence = torch.cat((current_sequence, torch.tensor([[next_token_idx]])), 1)
# Convert tokens to words
generated_text = " ".join([dataset.idx2token[token] for token in generated_tokens])
return generated_text
# Instantiate the SingleLSTM_TXT model
vocab_size = len(dataset.vocab) # The size of the vocabulary
embedding_dim = 128 # Size of embeddings
hidden_size = 128 # Number of features in the hidden state of the LSTM
num_layers = 4 # Number of stacked LSTM layers
single_lstm_txt_model = SingleLSTM_TXT(vocab_size, embedding_dim, hidden_size, num_layers)
# Training parameters
num_epochs = 10
batch_size = 128
learning_rate = 1e-4
# Define Loss Function and Optimizer for TXT dataset
criterion = nn.CrossEntropyLoss() # Use CrossEntropyLoss for classification tasks
optimizer = torch.optim.Adam(single_lstm_txt_model.parameters(), lr=learning_rate)
# Train the model with the text data
train_model_TXT(single_lstm_txt_model, criterion, optimizer, num_epochs, data_loader)
# Seed text to start the generation
seed_text = "Give me code to define a "
num_generate = 8 # Number of words to generate
temperature = 1.0 # Sampling temperature, higher will increase diversity
# Use the trained model to generate text
generated_text = generate_text(single_lstm_txt_model, dataset, seed_text, num_generate, temperature)
print("Generated Text: ", generated_text)
|
f8dfe7f642dc0082a2fce6759d4971e4
|
{
"intermediate": 0.2887762188911438,
"beginner": 0.42997676134109497,
"expert": 0.28124696016311646
}
|
37,871
|
обьясни код каждую строку подробно def f(s):
summa = 0
for i in range(len(s)):
summa += int(s[i])
return summa
for n in range(1, 100):
s = bin(n)[2:]
s = str(s)
summa = f(s)
s = s + str(summa % 2)
summa = f(s)
s = s + str(summa % 2)
r = int(s, 2)
if r > 83:
print(r)
break
|
23da4a5386dfdf7314554ab70e8c3f2b
|
{
"intermediate": 0.2467113882303238,
"beginner": 0.5496433973312378,
"expert": 0.20364519953727722
}
|
37,872
|
Can you please help me to adjust this VBA code as required.
After the line 'If ActiveCell.Column = 9 And ActiveCell.Offset(0, -1).Value <> "" Then ' column I "P REQUEST #" & "H SPECIAL NOTES"'
I want the values of the row from column A to J to be copied to column T from T2 to T11 downwards
Dim rowNum As Integer
Dim headerCell As Range
Dim rowcell As Range
Dim outputString As String
rowNum = ActiveCell.row
Set rng = Range("A" & rowNum & ":K" & rowNum)
If Target.CountLarge > 1 Then Exit Sub 'only one cell at a time
On Error Resume Next
If Not Intersect(ActiveCell, Range("I2:I2001")) Is Nothing And Target.Value = "" Then
Exit Sub
Else
If ActiveCell.Column = 9 And ActiveCell.Offset(0, -1).Value <> "" Then ' column I "P REQUEST #" & "H SPECIAL NOTES"
Dim wdApp As Object
Dim wdDoc As Object
Dim WsdShell As Object
Set wdApp = CreateObject("Word.Application")
Dim filePath As String
filePath = ThisWorkbook.Path & "\zzzz ServProvDocs\PurchaseRequest.docm"
Set wdDoc = wdApp.Documents.Open(filePath)
wdApp.Visible = True
Set WsdShell = CreateObject("WScript.Shell")
WsdShell.AppActivate wdApp.Caption
Application.Wait (Now + TimeValue("0:00:02"))
'Application.EnableEvents = False
'outputString = ""
'' Loop through headers and row values in parallel
'For Each headerCell In Range("A1:K1")
'outputString = outputString & headerCell.Value & vbCrLf
'outputString = outputString & rng.Cells(1, headerCell.Column).Value & vbCrLf
'Next headerCell
'Shell "notepad.exe", vbNormalFocus
'Application.Wait Now + TimeValue("00:00:01")
'SendKeys outputString
Cancel = True ' Prevents entering edit mode on double-click
Application.CutCopyMode = False
Application.EnableEvents = True
End If
Cancel = True ' Prevents entering edit mode on double-click
End If
Cancel = True ' Prevents entering edit mode on double-click
End Sub
|
1066764c57bcb4e2a951c649ba717316
|
{
"intermediate": 0.33059272170066833,
"beginner": 0.5410882234573364,
"expert": 0.12831906974315643
}
|
37,873
|
Can you help me create a txt dataset composed of text and summarized text, i want to create this dataset by using an existing csv dataset , this is its layout: [
{
"doc": "Send this page to someone via email\n\nActivists in London dumped gallons of yellow and blue paint in front of the Russian embassy in support of Ukraine on Thursday morning. The protest comes on the eve of the one-year anniversary of Russia's invasion of Ukraine.\n\nPhotos and videos of the demonstration showed activists in painter's coveralls lugging wheelbarrows full of paint sacs on Bayswater Road, near Hyde Park in Kensington.\n\nAs they uncorked the sacs and let the paint spill out, other protestors with large brooms spread the pigment across the busy intersection until it resembled the Ukrainian flag. Another organizer in a high-visibility jacket directed cars to drive slowly through the demonstration.\n\nA large group of spectators gathered to watch the protest as cars continued to pass through, picking up yellow and blue paint on their tires.\n\nStory continues below advertisement\n\nThe group responsible for the stunt, Led by Donkeys, wrote in a statement: \"Tomorrow is the first anniversary of Putin's imperialist invasion of Ukraine, an independent state and a people with every right to self-determination. The existence of a massive Ukrainian flag outside his embassy in London will serve to remind him of that.\"\n\nSolidarity with Ukraine \n\n(Russian Embassy, London) pic.twitter.com/efRXKgDuqV -- Led By Donkeys (@ByDonkeys) February 23, 2023\n\nFour people, three men and one woman, were arrested in connection with the protest on suspicion of criminal damage and obstructing the highway, the Met Police confirmed to MyLondon. They are currently being detained at a West London police station.\n\nLed by Donkeys is an art activist group that formed to protest Brexit, but its focus has since grown to address other social issues. The name Led by Donkeys comes from the phrase 'lions led by donkeys,\" a saying from the First World War that referred to the belief that British soldiers were being led to their deaths by incompetent leaders.\n\nStory continues below advertisement\n\nThe activists said they created the massive flag in front of the Russian embassy with 170 litres of yellow paint spread in the eastbound lane and a similar amount of blue paint in the westbound lane. They noted the paint was \"high-standard, non-toxic, solvent-free, eco-friendly, fast-dry edible paint designed for making road art.\"\n\nOne Londoner who drove through the protest shared a photo on Twitter of his blue-tinted wheels.\n\n\"Shame about my wheels,\" he wrote. \"Still, that protest put a huge smile on my face!\"\n\nHaha! It was so weird driving along going \"all those tyres are yellow. That's weird...\" then realising I was heading towards the blue... -- EviL Ras (@EviL_Ras) February 23, 2023\n\nStory continues below advertisement\n\nThe Russian invasion of Ukraine began on Feb. 24, 2022. Just before the invasion, Ukrainian President Volodymyr Zelenskyy pleaded with his Russian counterpart Vladimir Putin to get off the war path, cautioning that an invasion would only bring \"an abundance of pain filth, blood and death\" to their doorsteps.\n\nOne year into the war, those words continue to ring true.\n\nThe numbers are dizzying: hundreds of thousands of Russian men have escaped abroad to avoid being thrown into battle; millions of Ukrainians have been uprooted from their homes; tens of billions of dollars have poured into weaponry that is making war ever more lethal; and trillions more dollars estimated have been lost for the global economy. And even those figures don't do justice to the human and economic costs.\n\nOf the body count -- surely the most important tally, but kept under wraps by both sides -- all that can be said with certainty is that it is horrific. Western officials estimate it to be in the many tens of thousands and growing inexorably.\n\nBut Ukraine still exists; that in itself is a stinging defeat for the Kremlin.\n\n-- With files from The Associated Press",
"summary": "On the eve of the one-year anniversary of Russia's invasion of Ukraine, U.K. activists dumped gallons of yellow and blue paint on the road in front of the London Russian embassy."
},
{
"doc": "Send this page to someone via email\n\nActivists in London dumped gallons of yellow and blue paint in front of the Russian embassy in support of Ukraine on Thursday morning. The protest comes on the eve of the one-year anniversary of Russia's invasion of Ukraine.\n\nPhotos and videos of the demonstration showed activists in painter's coveralls lugging wheelbarrows full of paint sacs on Bayswater Road, near Hyde Park in Kensington.\n\nAs they uncorked the sacs and let the paint spill out, other protestors with large brooms spread the pigment across the busy intersection until it resembled the Ukrainian flag. Another organizer in a high-visibility jacket directed cars to drive slowly through the demonstration.\n\nA large group of spectators gathered to watch the protest as cars continued to pass through, picking up yellow and blue paint on their tires.\n\nStory continues below advertisement\n\nThe group responsible for the stunt, Led by Donkeys, wrote in a statement: \"Tomorrow is the first anniversary of Putin's imperialist invasion of Ukraine, an independent state and a people with every right to self-determination. The existence of a massive Ukrainian flag outside his embassy in London will serve to remind him of that.\"\n\nSolidarity with Ukraine \n\n(Russian Embassy, London) pic.twitter.com/efRXKgDuqV -- Led By Donkeys (@ByDonkeys) February 23, 2023\n\nFour people, three men and one woman, were arrested in connection with the protest on suspicion of criminal damage and obstructing the highway, the Met Police confirmed to MyLondon. They are currently being detained at a West London police station.\n\nLed by Donkeys is an art activist group that formed to protest Brexit, but its focus has since grown to address other social issues. The name Led by Donkeys comes from the phrase 'lions led by donkeys,\" a saying from the First World War that referred to the belief that British soldiers were being led to their deaths by incompetent leaders.\n\nStory continues below advertisement\n\nThe activists said they created the massive flag in front of the Russian embassy with 170 litres of yellow paint spread in the eastbound lane and a similar amount of blue paint in the westbound lane. They noted the paint was \"high-standard, non-toxic, solvent-free, eco-friendly, fast-dry edible paint designed for making road art.\"\n\nOne Londoner who drove through the protest shared a photo on Twitter of his blue-tinted wheels.\n\n\"Shame about my wheels,\" he wrote. \"Still, that protest put a huge smile on my face!\"\n\nHaha! It was so weird driving along going \"all those tyres are yellow. That's weird...\" then realising I was heading towards the blue... -- EviL Ras (@EviL_Ras) February 23, 2023\n\nStory continues below advertisement\n\nThe Russian invasion of Ukraine began on Feb. 24, 2022. Just before the invasion, Ukrainian President Volodymyr Zelenskyy pleaded with his Russian counterpart Vladimir Putin to get off the war path, cautioning that an invasion would only bring \"an abundance of pain filth, blood and death\" to their doorsteps.\n\nOne year into the war, those words continue to ring true.\n\nThe numbers are dizzying: hundreds of thousands of Russian men have escaped abroad to avoid being thrown into battle; millions of Ukrainians have been uprooted from their homes; tens of billions of dollars have poured into weaponry that is making war ever more lethal; and trillions more dollars estimated have been lost for the global economy. And even those figures don't do justice to the human and economic costs.\n\nOf the body count -- surely the most important tally, but kept under wraps by both sides -- all that can be said with certainty is that it is horrific. Western officials estimate it to be in the many tens of thousands and growing inexorably.\n\nBut Ukraine still exists; that in itself is a stinging defeat for the Kremlin.\n\n-- With files from The Associated Press",
"summary": "On the eve of the one-year anniversary of Russia's invasion of Ukraine, British activists poured gallons of yellow and blue paint on the road outside the London Russian embassy."
},
{
"doc": "Send this page to someone via email\n\nActivists in London dumped gallons of yellow and blue paint in front of the Russian embassy in support of Ukraine on Thursday morning. The protest comes on the eve of the one-year anniversary of Russia's invasion of Ukraine.\n\nPhotos and videos of the demonstration showed activists in painter's coveralls lugging wheelbarrows full of paint sacs on Bayswater Road, near Hyde Park in Kensington.\n\nAs they uncorked the sacs and let the paint spill out, other protestors with large brooms spread the pigment across the busy intersection until it resembled the Ukrainian flag. Another organizer in a high-visibility jacket directed cars to drive slowly through the demonstration.\n\nA large group of spectators gathered to watch the protest as cars continued to pass through, picking up yellow and blue paint on their tires.\n\nStory continues below advertisement\n\nThe group responsible for the stunt, Led by Donkeys, wrote in a statement: \"Tomorrow is the first anniversary of Putin's imperialist invasion of Ukraine, an independent state and a people with every right to self-determination. The existence of a massive Ukrainian flag outside his embassy in London will serve to remind him of that.\"\n\nSolidarity with Ukraine \n\n(Russian Embassy, London) pic.twitter.com/efRXKgDuqV -- Led By Donkeys (@ByDonkeys) February 23, 2023\n\nFour people, three men and one woman, were arrested in connection with the protest on suspicion of criminal damage and obstructing the highway, the Met Police confirmed to MyLondon. They are currently being detained at a West London police station.\n\nLed by Donkeys is an art activist group that formed to protest Brexit, but its focus has since grown to address other social issues. The name Led by Donkeys comes from the phrase 'lions led by donkeys,\" a saying from the First World War that referred to the belief that British soldiers were being led to their deaths by incompetent leaders.\n\nStory continues below advertisement\n\nThe activists said they created the massive flag in front of the Russian embassy with 170 litres of yellow paint spread in the eastbound lane and a similar amount of blue paint in the westbound lane. They noted the paint was \"high-standard, non-toxic, solvent-free, eco-friendly, fast-dry edible paint designed for making road art.\"\n\nOne Londoner who drove through the protest shared a photo on Twitter of his blue-tinted wheels.\n\n\"Shame about my wheels,\" he wrote. \"Still, that protest put a huge smile on my face!\"\n\nHaha! It was so weird driving along going \"all those tyres are yellow. That's weird...\" then realising I was heading towards the blue... -- EviL Ras (@EviL_Ras) February 23, 2023\n\nStory continues below advertisement\n\nThe Russian invasion of Ukraine began on Feb. 24, 2022. Just before the invasion, Ukrainian President Volodymyr Zelenskyy pleaded with his Russian counterpart Vladimir Putin to get off the war path, cautioning that an invasion would only bring \"an abundance of pain filth, blood and death\" to their doorsteps.\n\nOne year into the war, those words continue to ring true.\n\nThe numbers are dizzying: hundreds of thousands of Russian men have escaped abroad to avoid being thrown into battle; millions of Ukrainians have been uprooted from their homes; tens of billions of dollars have poured into weaponry that is making war ever more lethal; and trillions more dollars estimated have been lost for the global economy. And even those figures don't do justice to the human and economic costs.\n\nOf the body count -- surely the most important tally, but kept under wraps by both sides -- all that can be said with certainty is that it is horrific. Western officials estimate it to be in the many tens of thousands and growing inexorably.\n\nBut Ukraine still exists; that in itself is a stinging defeat for the Kremlin.\n\n-- With files from The Associated Press",
"summary": "On the eve of the one-year anniversary of Russia's attack on Ukraine, U.K. protesters spilled gallons of yellow and blue paint on the roadway in front of the London Russian embassy."
},...
|
122a021a81bb43c9a7c1e9aa2b12e2c2
|
{
"intermediate": 0.4043270945549011,
"beginner": 0.3728587329387665,
"expert": 0.22281412780284882
}
|
37,874
|
hi
|
0a6c254994845264900d6728d25086b3
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
37,875
|
make the deparutre time and arrival time in single column, arrivaltime on top and departure just below arrival time
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bus Schedule and Timeline</title>
<link
rel="stylesheet"
href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"
/>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link
rel="stylesheet"
href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
/>
<style>
body {
font-family: "Roboto", sans-serif;
background-color: rgb(243, 244, 246);
}
.station {
position: relative;
margin: 10px 0px;
display: flex;
flex-direction: row;
align-items: center;
}
.timeline {
content: "";
position: absolute;
top: 50%;
bottom: -100%;
/* bottom: -65% or 65 or 100 i dont rememeber ; */
border-left: 4px solid #4c51bf;
z-index: 1;
}
.hoi {
content: "";
position: relative;
width: 16px;
height: 16px;
left: 2px;
background-color: #fff;
border: 4px solid #4c51bf;
border-radius: 50%;
transform: translateX(-50%);
z-index: 2;
}
.time-wrapper {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
z-index: 3;
width: 20px;
}
.station-time {
padding: 5px 10px;
background-color: #4c51bf;
color: #fff;
border-radius: 12px;
white-space: nowrap;
z-index: 3;
margin-right: 20px;
}
.station-name {
flex-grow: 1;
margin-left: 20px;
margin-right: 20px;
z-index: 3;
}
.header-row {
display: flex;
justify-content: space-between;
padding: 10px;
font-weight: bold;
}
.green-bg {
background-color: #10b981;
}
.green-border {
border-color: #10b981;
}
.green-line {
border-left-color: #10b981;
}
.rotate-180 {
transform: rotate(180deg);
}
</style>
</head>
<body>
<div class="container mx-auto px-4">
<h1 class="text-3xl font-bold text-center my-4">Bus Schedule</h1>
<div class="grid grid-cols-2 gap-4">
<div class="bg-gray-100 p-4 rounded-md">
<label
for="departure"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
>Departure</label
>
<input
type="text"
id="departure"
class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
placeholder="Enter departure"
value="kottayam"
/>
</div>
<div class="bg-gray-100 p-4 rounded-md">
<label
for="destination"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
>Destination</label
>
<input
type="text"
id="destination"
class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
placeholder="Enter destination"
value="ponkunnam"
/>
</div>
<div class="bg-gray-100 p-4 rounded-md">
<label
for="time"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
>Time</label
>
<input
type="time"
id="time"
class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
/>
</div>
<div class="bg-gray-100 p-4 rounded-md">
<button
type="submit"
onclick="submitForm()"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg"
>
Submit
</button>
</div>
</div>
</div>
<div class="bg-gray-100 font-roboto">
<div class="max-w-xl mx-auto py-12 px-4 sm:px-6 lg:px-2">
<div class="mt-8" id="scheduleContainer"></div>
</div>
</div>
<script>
let stationNames = [];
fetch(
"https://raw.githubusercontent.com/amith-vp/Kerala-Private-Bus-Timing/main/data%20conversion%20scripts/stations.txt"
)
.then((response) => response.text())
.then((data) => {
stationNames = data.split("\n");
$("#departure").autocomplete({
source: stationNames,
});
$("#destination").autocomplete({
source: stationNames,
});
});
async function submitForm() {
const departure = document.getElementById("departure").value;
const destination = document.getElementById("destination").value;
const time = document.getElementById("time").value;
// const time = "12:24";
// Make API request
const apiUrl = `https://busapi.amithv.xyz/api/v1/schedules?departure=${encodeURIComponent(
departure
)}&destination=${encodeURIComponent(destination)}`;
try {
const response = await fetch(apiUrl);
const scheduleData = await response.json();
updateSchedule(scheduleData, departure, destination);
} catch (error) {
console.error("Error fetching data:", error);
}
}
function updateSchedule(scheduleData, departure, destination) {
departure = departure.toUpperCase();
destination = destination.toUpperCase();
const scheduleContainer = document.getElementById("scheduleContainer");
scheduleContainer.innerHTML = "";
scheduleData.forEach((trip, index, array) => {
const tripDetails = document.createElement("details");
tripDetails.classList.add(
"bg-white",
"rounded-md",
"shadow-md",
"my-4",
"overflow-hidden"
);
const departureStation = trip.stations.find((station) =>
station.station.toUpperCase().startsWith(departure)
);
const arrivalStation = trip.stations.find((station) =>
station.station.toUpperCase().startsWith(destination)
);
const departureTime = departureStation
? departureStation.departureTime
: "N/A";
const arrivalTime = arrivalStation
? arrivalStation.arrivalTime
: "N/A";
const tripSummary = document.createElement("summary");
tripSummary.classList.add(
"flex",
"justify-between",
"items-center",
"px-4",
"py-2",
"cursor-pointer",
"bg-blue-500",
"text-white"
);
tripSummary.innerHTML = `
<div class="flex justify-between items-center w-full">
<span> ${departureTime} ➡️ ${arrivalTime}</span>
<span style="margin-left: auto;">${trip.vehicle_number}</span>
</div>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="white">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
`;
tripSummary.addEventListener("click", (event) => {
const icon = tripSummary.querySelector("svg");
if (tripDetails.open) {
icon.classList.remove("rotate-180");
} else {
icon.classList.add("rotate-180");
}
});
tripDetails.appendChild(tripSummary);
let vehicleDiv = document.createElement("div");
// vehicleDiv.textContent = `Vehicle Number: ${trip.vehicle_number}, Trip: ${trip.trip}`;
scheduleContainer.appendChild(vehicleDiv);
let hasDeparted = false;
let hasArrived = false;
trip.stations.forEach((station, stationIndex) => {
let stationDiv = document.createElement("div");
stationDiv.classList.add("station");
if (station.station.toUpperCase().startsWith(departure)) {
hasDeparted = true;
}
let arrivalTimeDiv = document.createElement("div");
arrivalTimeDiv.classList.add("station-time");
if (hasDeparted && !hasArrived) {
arrivalTimeDiv.classList.add("green-bg");
}
arrivalTimeDiv.textContent = station.arrivalTime;
stationDiv.appendChild(arrivalTimeDiv);
stationDiv.classList.add(
"px-4",
"py-2",
"border-b",
"flex",
"justify-between",
"items-center",
"last:border-b-0"
);
let timeWrapperDiv = document.createElement("div");
timeWrapperDiv.classList.add("time-wrapper");
let hoiDiv = document.createElement("div");
hoiDiv.classList.add("hoi");
if (hasDeparted && !hasArrived) {
hoiDiv.classList.add("green-border");
}
timeWrapperDiv.appendChild(hoiDiv);
if (stationIndex !== trip.stations.length - 1) {
let timelineDiv = document.createElement("div");
timelineDiv.classList.add("timeline");
if (
hasDeparted &&
!hasArrived &&
station.station.toUpperCase().startsWith(destination) === false
) {
timelineDiv.classList.add("green-line");
} else {
timelineDiv.classList.add("blue-line");
}
timeWrapperDiv.appendChild(timelineDiv);
}
stationDiv.appendChild(timeWrapperDiv);
let stationNameDiv = document.createElement("div");
stationNameDiv.classList.add("station-name");
stationNameDiv.textContent = station.station;
stationDiv.appendChild(stationNameDiv);
let departureTimeDiv = document.createElement("div");
departureTimeDiv.classList.add("station-time");
if (hasDeparted && !hasArrived) {
departureTimeDiv.classList.add("green-bg");
}
departureTimeDiv.textContent = station.departureTime;
stationDiv.appendChild(departureTimeDiv);
scheduleContainer.appendChild(stationDiv);
if (station.station.toUpperCase().startsWith(destination)) {
hasArrived = true;
}
tripDetails.appendChild(stationDiv);
});
scheduleContainer.appendChild(tripDetails);
});
}
</script>
</body>
</html>
|
bb117aa96db352b21a75933b7a5e9802
|
{
"intermediate": 0.30505725741386414,
"beginner": 0.40731874108314514,
"expert": 0.2876240015029907
}
|
37,876
|
make the deparutre time and arrival time in single column, arrivaltime on top and departure just below arrival time
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bus Schedule and Timeline</title>
<link
rel="stylesheet"
href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"
/>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link
rel="stylesheet"
href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
/>
<style>
body {
font-family: "Roboto", sans-serif;
background-color: rgb(243, 244, 246);
}
.station {
position: relative;
margin: 10px 0px;
display: flex;
flex-direction: row;
align-items: center;
}
.timeline {
content: "";
position: absolute;
top: 50%;
bottom: -100%;
/* bottom: -65% or 65 or 100 i dont rememeber ; */
border-left: 4px solid #4c51bf;
z-index: 1;
}
.hoi {
content: "";
position: relative;
width: 16px;
height: 16px;
left: 2px;
background-color: #fff;
border: 4px solid #4c51bf;
border-radius: 50%;
transform: translateX(-50%);
z-index: 2;
}
.time-wrapper {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
z-index: 3;
width: 20px;
}
.station-time {
padding: 5px 10px;
background-color: #4c51bf;
color: #fff;
border-radius: 12px;
white-space: nowrap;
z-index: 3;
margin-right: 20px;
}
.station-name {
flex-grow: 1;
margin-left: 20px;
margin-right: 20px;
z-index: 3;
}
.header-row {
display: flex;
justify-content: space-between;
padding: 10px;
font-weight: bold;
}
.green-bg {
background-color: #10b981;
}
.green-border {
border-color: #10b981;
}
.green-line {
border-left-color: #10b981;
}
.rotate-180 {
transform: rotate(180deg);
}
</style>
</head>
<body>
<div class="container mx-auto px-4">
<h1 class="text-3xl font-bold text-center my-4">Bus Schedule</h1>
<div class="grid grid-cols-2 gap-4">
<div class="bg-gray-100 p-4 rounded-md">
<label
for="departure"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
>Departure</label
>
<input
type="text"
id="departure"
class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
placeholder="Enter departure"
value="kottayam"
/>
</div>
<div class="bg-gray-100 p-4 rounded-md">
<label
for="destination"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
>Destination</label
>
<input
type="text"
id="destination"
class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
placeholder="Enter destination"
value="ponkunnam"
/>
</div>
<div class="bg-gray-100 p-4 rounded-md">
<label
for="time"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
>Time</label
>
<input
type="time"
id="time"
class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
/>
</div>
<div class="bg-gray-100 p-4 rounded-md">
<button
type="submit"
onclick="submitForm()"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg"
>
Submit
</button>
</div>
</div>
</div>
<div class="bg-gray-100 font-roboto">
<div class="max-w-xl mx-auto py-12 px-4 sm:px-6 lg:px-2">
<div class="mt-8" id="scheduleContainer"></div>
</div>
</div>
<script>
let stationNames = [];
fetch(
"https://raw.githubusercontent.com/amith-vp/Kerala-Private-Bus-Timing/main/data%20conversion%20scripts/stations.txt"
)
.then((response) => response.text())
.then((data) => {
stationNames = data.split("\n");
$("#departure").autocomplete({
source: stationNames,
});
$("#destination").autocomplete({
source: stationNames,
});
});
async function submitForm() {
const departure = document.getElementById("departure").value;
const destination = document.getElementById("destination").value;
const time = document.getElementById("time").value;
// const time = "12:24";
// Make API request
const apiUrl = `https://busapi.amithv.xyz/api/v1/schedules?departure=${encodeURIComponent(
departure
)}&destination=${encodeURIComponent(destination)}`;
try {
const response = await fetch(apiUrl);
const scheduleData = await response.json();
updateSchedule(scheduleData, departure, destination);
} catch (error) {
console.error("Error fetching data:", error);
}
}
function updateSchedule(scheduleData, departure, destination) {
departure = departure.toUpperCase();
destination = destination.toUpperCase();
const scheduleContainer = document.getElementById("scheduleContainer");
scheduleContainer.innerHTML = "";
scheduleData.forEach((trip, index, array) => {
const tripDetails = document.createElement("details");
tripDetails.classList.add(
"bg-white",
"rounded-md",
"shadow-md",
"my-4",
"overflow-hidden"
);
const departureStation = trip.stations.find((station) =>
station.station.toUpperCase().startsWith(departure)
);
const arrivalStation = trip.stations.find((station) =>
station.station.toUpperCase().startsWith(destination)
);
const departureTime = departureStation
? departureStation.departureTime
: "N/A";
const arrivalTime = arrivalStation
? arrivalStation.arrivalTime
: "N/A";
const tripSummary = document.createElement("summary");
tripSummary.classList.add(
"flex",
"justify-between",
"items-center",
"px-4",
"py-2",
"cursor-pointer",
"bg-blue-500",
"text-white"
);
tripSummary.innerHTML = `
<div class="flex justify-between items-center w-full">
<span> ${departureTime} ➡️ ${arrivalTime}</span>
<span style="margin-left: auto;">${trip.vehicle_number}</span>
</div>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="white">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
`;
tripSummary.addEventListener("click", (event) => {
const icon = tripSummary.querySelector("svg");
if (tripDetails.open) {
icon.classList.remove("rotate-180");
} else {
icon.classList.add("rotate-180");
}
});
tripDetails.appendChild(tripSummary);
let vehicleDiv = document.createElement("div");
// vehicleDiv.textContent = `Vehicle Number: ${trip.vehicle_number}, Trip: ${trip.trip}`;
scheduleContainer.appendChild(vehicleDiv);
let hasDeparted = false;
let hasArrived = false;
trip.stations.forEach((station, stationIndex) => {
let stationDiv = document.createElement("div");
stationDiv.classList.add("station");
if (station.station.toUpperCase().startsWith(departure)) {
hasDeparted = true;
}
let arrivalTimeDiv = document.createElement("div");
arrivalTimeDiv.classList.add("station-time");
if (hasDeparted && !hasArrived) {
arrivalTimeDiv.classList.add("green-bg");
}
arrivalTimeDiv.textContent = station.arrivalTime;
stationDiv.appendChild(arrivalTimeDiv);
stationDiv.classList.add(
"px-4",
"py-2",
"border-b",
"flex",
"justify-between",
"items-center",
"last:border-b-0"
);
let timeWrapperDiv = document.createElement("div");
timeWrapperDiv.classList.add("time-wrapper");
let hoiDiv = document.createElement("div");
hoiDiv.classList.add("hoi");
if (hasDeparted && !hasArrived) {
hoiDiv.classList.add("green-border");
}
timeWrapperDiv.appendChild(hoiDiv);
if (stationIndex !== trip.stations.length - 1) {
let timelineDiv = document.createElement("div");
timelineDiv.classList.add("timeline");
if (
hasDeparted &&
!hasArrived &&
station.station.toUpperCase().startsWith(destination) === false
) {
timelineDiv.classList.add("green-line");
} else {
timelineDiv.classList.add("blue-line");
}
timeWrapperDiv.appendChild(timelineDiv);
}
stationDiv.appendChild(timeWrapperDiv);
let stationNameDiv = document.createElement("div");
stationNameDiv.classList.add("station-name");
stationNameDiv.textContent = station.station;
stationDiv.appendChild(stationNameDiv);
let departureTimeDiv = document.createElement("div");
departureTimeDiv.classList.add("station-time");
if (hasDeparted && !hasArrived) {
departureTimeDiv.classList.add("green-bg");
}
departureTimeDiv.textContent = station.departureTime;
stationDiv.appendChild(departureTimeDiv);
scheduleContainer.appendChild(stationDiv);
if (station.station.toUpperCase().startsWith(destination)) {
hasArrived = true;
}
tripDetails.appendChild(stationDiv);
});
scheduleContainer.appendChild(tripDetails);
});
}
</script>
</body>
</html>
|
2aacebef4c4db54962ea44a5cd4d6c5b
|
{
"intermediate": 0.30505725741386414,
"beginner": 0.40731874108314514,
"expert": 0.2876240015029907
}
|
37,877
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract bomb {
uint256 public _code;
constructor(uint256 code) {
_code = code;
}
function blast() public {
assembly {
selfdestruct(0x0000000000000000000000000000)
}
}
}
contract Trigger {
function pullTrigger() public returns (uint256) {
Bomb bomb = new Bomb(42);
bomb.blast();
return bomb._code();
}
}
Will calling the pullTrigger() function from the Trigger contract revert?
If not, does it retrun 0 or 42?
|
ea0c35e41eb2f211c8271e4629efb2c1
|
{
"intermediate": 0.37166059017181396,
"beginner": 0.523758053779602,
"expert": 0.1045813262462616
}
|
37,878
|
I want you to act as a SQL terminal in front of an example database. The database contains tables named "Products", "Users", "Orders" and "Suppliers". I will type queries and you will reply with what the terminal would show. I want you to reply with a table of query results in a single code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so in curly braces {like this). My first command is 'SELECT TOP 10 * FROM Products ORDER BY Id DESC'.
|
3dcb1e93c1107c47abc6d00894a9c3af
|
{
"intermediate": 0.3367333710193634,
"beginner": 0.3181932270526886,
"expert": 0.34507331252098083
}
|
37,879
|
what do you know about chronos, the tool for CRISPR screen analysis
|
a0e564863746cac1c1b5f6e0e946cb4c
|
{
"intermediate": 0.298721045255661,
"beginner": 0.23822133243083954,
"expert": 0.4630575478076935
}
|
37,880
|
pourquoi lorsque je veux sur la page questoins_quizz (pour acceder aux questions du quizz) j'ai ces erreurs : Warning: Undefined array key "id" in C:\Users\alexa\Desktop\Quizz_PHP\questions_quizz.php on line 12
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1 no such column: id in C:\Users\alexa\Desktop\Quizz_PHP\questions.php:11 Stack trace: #0 C:\Users\alexa\Desktop\Quizz_PHP\questions.php(11): PDO->prepare('SELECT * FROM q...') #1 C:\Users\alexa\Desktop\Quizz_PHP\questions_quizz.php(13): getQuestions(NULL) #2 {main} thrown in C:\Users\alexa\Desktop\Quizz_PHP\questions.php on line 11 : The following text is a Git repository with code. The structure of the text are sections that begin with ----, followed by a single line containing the file path and file name, followed by a variable amount of lines containing the file contents. The text representing the Git repository ends when the symbols --END-- are encounted. Any further text beyond --END-- are meant to be interpreted as instructions using the aforementioned Git repository as context.
----
correction.php
<?php
session_start();
require_once 'questions.php';
require 'Classes/autoloader.php';
Autoloader::register();
$questions = getQuestions();
$score = isset($_SESSION['quiz_score']) ? $_SESSION['quiz_score'] : 0;
$repBonne = isset($_SESSION['repBonne']) ? $_SESSION['repBonne'] : [];
$repFausse = isset($_SESSION['repFausse']) ? $_SESSION['repFausse'] : [];
if (isset($questions) && is_array($questions)) {
echo "<h1 >Résultats du Quiz </h1>";
echo '<hr />';
if ($score === count($questions)) {
echo "Félicitations, vous avez répondu correctement à toutes les questions !<br>";
echo "<br>"
. "Votre score est de " . $score . " sur " . count($questions) . " !!!" . "<br>";
echo "<br>"
. "<img src='https://media.giphy.com/media/RPCMrr8iiyvggdbMJ5/giphy.gif' alt='Gif de félicitations' width='300' height='300'>";
} else {
echo "Vous avez répondu correctement à " . $score . " questions sur " . count($questions) . "<br>";
echo "<p>Les réponses auxquelles vous avez répondu correctement sont : </p>";
foreach ($repBonne as $rep) {
for ($i = 0; $i < count($questions); $i++) {
if ($questions[$i]->getUuid() === $rep) {
$question = $questions[$i];
break;
}
}
echo $question->getLabel() . "<br>";
}
echo "<p>Les réponses auxquelles vous avez répondu incorrectement sont : </p>";
foreach ($repFausse as $rep) {
for ($i = 0; $i < count($questions); $i++) {
if ($questions[$i]->getUuid() === $rep) {
$question = $questions[$i];
break;
}
}
echo $question->getLabel() . "<br>";
echo "<p>La bonne réponse est : </p>";
if ($question->getType() === 'text' or $question->getType() === 'radio') {
echo $question->getCorrect() . "<br>";
}
else{
foreach ($question->getCorrect() as $choice) {
echo $choice . "<br>";
}
}
}
}
} else {
echo "Aucune question trouvée";
}
unset($_SESSION['quiz_score']);
unset($_SESSION['repBonne']);
unset($_SESSION['repFausse']);
?>
----
data.json
[
{
"quiz_id": 1,
"quiz_name": "Quiz sur la géographie",
"questions": [
{
"uuid": "f4856b0a-5b89-4f18-8dd5-ff70323f2b0a",
"type": "radio",
"label": "Quelle est la capitale de la France ?",
"choices": [
"Londres",
"Paris",
"Berlin"
],
"correct": "Paris"
},
{
"uuid": "932c9079-e157-4eaf-80da-92fb4a2ea5da",
"type": "radio",
"label": "Quelle planète est surnommée la 'Planète Rouge' ?",
"choices": [
"Vénus",
"Mars",
"Jupiter"
],
"correct": "Mars"
}
]
},
{
"quiz_id": 2,
"quiz_name": "Quiz sur la cuisine",
"questions": [
{
"uuid": "7b32c56e-7d1f-4a13-80e3-c650f5f8b108",
"type": "checkbox",
"label": "Quels sont les ingrédients principaux d'une pizza margherita ?",
"choices": [
"Tomate",
"Fromage",
"Champignons",
"Anchois"
],
"correct": [
"Tomate",
"Fromage"
]
},
{
"uuid": "6d6b2e94-1f60-45f5-9c6f-2d45bd02d5e0",
"type": "text",
"label": "Quelle est la couleur du ciel pendant la journée ?",
"correct": "Bleu"
}
]
}
]
----
data.php
<?php
function getDatas(){
$source = 'databases/data.json';
$content = file_get_contents($source);
$datas = json_decode($content, true);
if (empty($datas)) {
throw new Exception('No product :(', 1);
}
return $datas;
}
?>
----
db.sqlite
SQLite format 3
|
6cb984b4b131f394ba1c60e894c4b2f2
|
{
"intermediate": 0.33920732140541077,
"beginner": 0.4857803285121918,
"expert": 0.17501236498355865
}
|
37,881
|
make me a 1 dollar cat
|
a8e168954d03e70b19e35d15098ddefa
|
{
"intermediate": 0.4271704852581024,
"beginner": 0.3581971824169159,
"expert": 0.21463227272033691
}
|
37,882
|
unzip train.csv.zip in python
|
05409dca4ad175e11ba3fdf21e0b01a9
|
{
"intermediate": 0.2694191336631775,
"beginner": 0.18230757117271423,
"expert": 0.5482733249664307
}
|
37,883
|
comment avoir les question d'un quizz dans getQuestions : $pdo->exec("
CREATE TABLE IF NOT EXISTS quizzes (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)
");
try {
$pdo->exec("
CREATE TABLE IF NOT EXISTS questions (
uuid TEXT PRIMARY KEY,
quiz_id INTEGER,
type TEXT NOT NULL,
label TEXT NOT NULL,
choices TEXT,
correct TEXT NOT NULL,
FOREIGN KEY (quiz_id) REFERENCES quizzes(id)
)
");$quizzes = json_decode(file_get_contents('data.json'), true);
foreach ($quizzes as $quiz) {
// je regarde si le quizz existe déjà (car si je execute le php il voudra insert et j'aurais un constraint fail)
$stmt = $pdo->prepare("SELECT * FROM quizzes WHERE id = ?");
$stmt->execute([$quiz['quiz_id']]);
$exists = $stmt->fetch(PDO::FETCH_ASSOC);
// si le quizz n'existe pas, je l'insert donc
if (!$exists) {
$pdo->prepare("
INSERT INTO quizzes (id, name) VALUES (?, ?)
")->execute([
$quiz['quiz_id'],
$quiz['quiz_name'],
]);
}
foreach ($quiz['questions'] as $question) {
$question['quiz_id'] = $quiz['quiz_id']; // je ne comprend pas pourquoi je n'ai pas la clé étrangère
// quiz_id dans mon tableau question alors que dans la table de la bd
// j'ai bien la clé étrangère quiz_id
$stmt = $pdo->prepare("SELECT * FROM questions WHERE uuid = ?");
$stmt->execute([$question['uuid']]);
$exists = $stmt->fetch(PDO::FETCH_ASSOC);
// meme chose pour les questions
if (!$exists) {
$pdo->prepare("
INSERT INTO questions (uuid, type, label, choices, correct) VALUES (?, ?, ?, ?, ?)
")->execute([
$question['uuid'],
$question['type'],
$question['label'],
isset($question['choices']) ? json_encode($question['choices']) : null,
is_array($question['correct']) ? json_encode($question['correct']) : $question['correct'],
]);function getQuestions($quiz_id) {
$pdo = new PDO('sqlite:db.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM questions WHERE quiz_id = ?");
$stmt->execute([$quiz_id]);
$datas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$questions = [];
foreach ($datas as $data) {
$question = null;
$uuid = $data['uuid'];
$type = $data['type'];
$label = $data['label'];
$choices = json_decode($data['choices'], true);
$correct = is_array(json_decode($data['correct'], true)) ? json_decode($data['correct'], true) : $data['correct'];
switch ($type) {
case 'radio':
$question = new RadioQuestion($uuid, $type, $label, $choices, $correct);
break;
case 'checkbox':
$question = new CheckboxQuestion($uuid, $type, $label, $choices, $correct);
break;
case 'text':
$question = new TextQuestion($uuid, $type, $label, $correct);
break;
}
if ($question !== null) {
$questions[] = $question;
}
}
return $questions;
}
|
308e934fc964e28eace21cb74bee1d9f
|
{
"intermediate": 0.25286412239074707,
"beginner": 0.4935949444770813,
"expert": 0.253540962934494
}
|
37,884
|
hi, can you help with a coding question?
|
de0e3b9f21f18ddebe2fcc4ebea863b4
|
{
"intermediate": 0.39146530628204346,
"beginner": 0.49829530715942383,
"expert": 0.11023937910795212
}
|
37,885
|
how to compile assembly code
|
fa90357d39f56dd5eb4ca2d6ddba83c3
|
{
"intermediate": 0.20548835396766663,
"beginner": 0.6355509757995605,
"expert": 0.15896068513393402
}
|
37,886
|
make an assembly code for a simple drawing program. a 500x500 window with a black pixel brush
|
800e71c5104b9699ab64120145023cb0
|
{
"intermediate": 0.29835763573646545,
"beginner": 0.44015854597091675,
"expert": 0.2614838480949402
}
|
37,887
|
i’m trying to add ai LLM to a python chess game. here’s the logic i’m trying to accomplish
-two main functions: chess game amd LLM chat
- Chess Game
- User or chess ai makes a chess move
- the game logic is applied
- if it was an ai chess move, add it to the history of the assistant
- if it was a user move, add it to the history of the user
- repeat this logic for gameplay loop, so the LLM is always updated with the moves in it’s history.
- LLM Chat
- User input area where a user can enter a message
- when a message is entered, it is rendered in the chat area, added to the history and sent to the LLM
- the LLM sends a response back, and the response is rendered in the text area
This is a prelim code to see how the lLM chat would work with pygame. It functions properly. i can send a message to the llm, it replies, and we can do a multi turn chat.
import requests
import pygame
import sys
# Initialize PyGame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
FONT_SIZE = 20
# Create a PyGame window
window = pygame.display.set_mode((WIDTH, HEIGHT))
# Set the window title
pygame.display.set_caption(“Chat GUI”)
# Fonts
font = pygame.font.Font(None, FONT_SIZE)
# Chat variables
user_input = “”
chat_history = []
# API Configuration
api_url = ‘http://127.0.0.1:5000/v1/chat/completions’
headers = {“Content-Type”: “application/json”}
def send_message():
global chat_history, user_input
user_message = user_input.strip()
if user_message:
# Add user message to chat history
chat_history.append({“role”: “user”, “content”: user_message})
# Display user message in the chat area
draw_text(window, f’User: {user_message}‘, BLACK, (410, 10))
# Send message to assistant
data = {
“mode”: “chat”,
“character”: “Assistant”,
“messages”: chat_history
}
try:
response = requests.post(api_url, headers=headers, json=data, verify=False)
assistant_message = response.json()[‘choices’][0][‘message’][‘content’]
chat_history.append({“role”: “assistant”, “content”: assistant_message})
# Clear user input after sending a message
user_input = “”
except requests.RequestException as e:
chat_history.append({“role”: “Error”, “content”: str(e)})
def draw_text(surface, text, color, pos):
text_surface = font.render(text, True, color)
surface.blit(text_surface, pos)
# Game loop
clock = pygame.time.Clock()
running = True
while running:
window.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
send_message()
elif event.key == pygame.K_BACKSPACE:
user_input = user_input[:-1]
else:
user_input += event.unicode
# Draw chat history
y = 10
for message in chat_history:
draw_text(window, f’{message[“role”]}: {message[“content”]}‘, BLACK, (410, y))
y += FONT_SIZE + 5
# Draw user input
draw_text(window, f’User: {user_input}’, BLACK, (410, HEIGHT - FONT_SIZE - 10))
pygame.display.update()
clock.tick(30)
pygame.quit()
sys.exit()
This is the chess python program. It runs, but when I try to make the first move, it crashes with an error. how do i fix this?
"""
Main driver file.
Handling user input.
Displaying current GameStatus object.
"""
import pygame as p
import ChessEngine, ChessAI
import sys
from multiprocessing import Process, Queue
import requests
BOARD_WIDTH = BOARD_HEIGHT = 512
MOVE_LOG_PANEL_WIDTH = 250
MOVE_LOG_PANEL_HEIGHT = BOARD_HEIGHT
CHAT_PANEL_WIDTH = 250
CHAT_PANEL_HEIGHT = BOARD_HEIGHT
DIMENSION = 8
SQUARE_SIZE = BOARD_HEIGHT // DIMENSION
MAX_FPS = 15
IMAGES = {}
user_input = ""
chat_history = []
api_url = 'http://127.0.0.1:5000/v1/chat/completions'
headers = {"Content-Type": "application/json"}
def loadImages():
"""
Initialize a global directory of images.
This will be called exactly once in the main.
"""
pieces = ['wp', 'wR', 'wN', 'wB', 'wK', 'wQ', 'bp', 'bR', 'bN', 'bB', 'bK', 'bQ']
for piece in pieces:
IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (SQUARE_SIZE, SQUARE_SIZE))
def main():
"""
The main driver for our code.
This will handle user input and updating the graphics.
"""
p.init()
screen = p.display.set_mode((BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
clock = p.time.Clock()
screen.fill(p.Color("white"))
game_state = ChessEngine.GameState()
valid_moves = game_state.getValidMoves()
move_made = False # flag variable for when a move is made
animate = False # flag variable for when we should animate a move
loadImages() # do this only once before while loop
running = True
square_selected = () # no square is selected initially, this will keep track of the last click of the user (tuple(row,col))
player_clicks = [] # this will keep track of player clicks (two tuples)
game_over = False
ai_thinking = False
move_undone = False
move_finder_process = None
move_log_font = p.font.SysFont("Arial", 14, False, False)
player_one = True # if a human is playing white, then this will be True, else False
player_two = False # if a hyman is playing white, then this will be True, else False
global chat_history, user_input # Declare user_input as global
while running:
human_turn = (game_state.white_to_move and player_one) or (not game_state.white_to_move and player_two)
for e in p.event.get():
if e.type == p.QUIT:
p.quit()
sys.exit()
# mouse handler
elif e.type == p.MOUSEBUTTONDOWN:
if not game_over:
location = p.mouse.get_pos() # (x, y) location of the mouse
col = location[0] // SQUARE_SIZE
row = location[1] // SQUARE_SIZE
if square_selected == (row, col) or col >= 8: # user clicked the same square twice
square_selected = () # deselect
player_clicks = [] # clear clicks
else:
square_selected = (row, col)
player_clicks.append(square_selected) # append for both 1st and 2nd click
if len(player_clicks) == 2 and human_turn: # after 2nd click
move = ChessEngine.Move(player_clicks[0], player_clicks[1], game_state.board)
for i in range(len(valid_moves)):
if move == valid_moves[i]:
game_state.makeMove(valid_moves[i])
move_made = True
animate = True
square_selected = () # reset user clicks
player_clicks = []
if not move_made:
player_clicks = [square_selected]
# key handler
elif e.type == p.KEYDOWN:
if e.key == p.K_z: # undo when 'z' is pressed
game_state.undoMove()
move_made = True
animate = False
game_over = False
if ai_thinking:
move_finder_process.terminate()
ai_thinking = False
move_undone = True
if e.key == p.K_r: # reset the game when 'r' is pressed
game_state = ChessEngine.GameState()
valid_moves = game_state.getValidMoves()
square_selected = ()
player_clicks = []
move_made = False
animate = False
game_over = False
if ai_thinking:
move_finder_process.terminate()
ai_thinking = False
move_undone = True
# AI move finder
if not game_over and not human_turn and not move_undone:
if not ai_thinking:
ai_thinking = True
return_queue = Queue() # used to pass data between threads
move_finder_process = Process(target=ChessAI.findBestMove, args=(game_state, valid_moves, return_queue))
move_finder_process.start()
if not move_finder_process.is_alive():
ai_move = return_queue.get()
if ai_move is None:
ai_move = ChessAI.findRandomMove(valid_moves)
game_state.makeMove(ai_move)
move_made = True
animate = True
ai_thinking = False
if move_made:
if animate:
animateMove(game_state.move_log[-1], screen, game_state.board, clock)
valid_moves = game_state.getValidMoves()
move_made = False
animate = False
move_undone = False
drawGameState(screen, game_state, valid_moves, square_selected)
if game_state.move_log:
# Send the move to LLM and receive AI's response
user_move = str(game_state.move_log[-1])
ai_response = send_move_to_llm(user_move)
# Update chat history with player move and AI response
chat_history.append(("user", user_move))
chat_history.append(("Assistant", ai_response))
if not game_over:
drawMoveLog(screen, game_state, chat_history, user_input, move_log_font)
if game_state.checkmate:
game_over = True
if game_state.white_to_move:
drawEndGameText(screen, "Black wins by checkmate")
else:
drawEndGameText(screen, "White wins by checkmate")
elif game_state.stalemate:
game_over = True
drawEndGameText(screen, "Stalemate")
for event in p.event.get():
if event.type == p.KEYDOWN:
if event.key == p.K_RETURN:
send_message()
elif event.key == p.K_BACKSPACE:
user_input = user_input[:-1]
else:
user_input += event.unicode
clock.tick(MAX_FPS)
p.display.flip()
def send_message():
global chat_history, user_input
user_message = user_input.strip()
if user_message:
# Add user message to chat history
chat_history.append({"role": "user", "content": user_message})
# Display user message in the chat area
draw_text(window, f'User: {user_message}', BLACK, (410, 10))
# Send message to assistant
data = {
"mode": "chat",
"character": "Assistant",
"messages": chat_history
}
try:
response = requests.post(api_url, headers=headers, json=data, verify=False)
assistant_message = response.json()['choices'][0]['message']['content']
chat_history.append({"role": "assistant", "content": assistant_message})
# Clear user input after sending a message
user_input = ""
except requests.RequestException as e:
chat_history.append({"role": "Error", "content": str(e)})
def send_move_to_llm(move):
global chat_history, user_input # Declare user_input as global
# Construct the data to send to LLM
data = {
"mode": "chat",
"character": "Assistant",
"messages": chat_history
}
try:
response = requests.post(api_url, headers=headers, json=data, verify=False)
assistant_message = response.json()['choices'][0]['message']['content']
chat_history.append({"role": "Assistant", "content": assistant_message})
# Clear user input after sending a message
user_input = ""
ai_reply = response.json()["choices"][0]["text"]
return ai_reply
except requests.RequestException as e:
chat_history.append(("Error", str(e)))
def drawGameState(screen, game_state, valid_moves, square_selected):
"""
Responsible for all the graphics within current game state.
"""
drawBoard(screen) # draw squares on the board
highlightSquares(screen, game_state, valid_moves, square_selected)
drawPieces(screen, game_state.board) # draw pieces on top of those squares
def drawBoard(screen):
"""
Draw the squares on the board.
The top left square is always light.
"""
global colors
colors = [p.Color("white"), p.Color("gray")]
for row in range(DIMENSION):
for column in range(DIMENSION):
color = colors[((row + column) % 2)]
p.draw.rect(screen, color, p.Rect(column * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def highlightSquares(screen, game_state, valid_moves, square_selected):
"""
Highlight square selected and moves for piece selected.
"""
if (len(game_state.move_log)) > 0:
last_move = game_state.move_log[-1]
s = p.Surface((SQUARE_SIZE, SQUARE_SIZE))
s.set_alpha(100)
s.fill(p.Color('green'))
screen.blit(s, (last_move.end_col * SQUARE_SIZE, last_move.end_row * SQUARE_SIZE))
if square_selected != ():
row, col = square_selected
if game_state.board[row][col][0] == (
'w' if game_state.white_to_move else 'b'): # square_selected is a piece that can be moved
# highlight selected square
s = p.Surface((SQUARE_SIZE, SQUARE_SIZE))
s.set_alpha(100) # transparency value 0 -> transparent, 255 -> opaque
s.fill(p.Color('blue'))
screen.blit(s, (col * SQUARE_SIZE, row * SQUARE_SIZE))
# highlight moves from that square
s.fill(p.Color('yellow'))
for move in valid_moves:
if move.start_row == row and move.start_col == col:
screen.blit(s, (move.end_col * SQUARE_SIZE, move.end_row * SQUARE_SIZE))
def drawPieces(screen, board):
"""
Draw the pieces on the board using the current game_state.board
"""
for row in range(DIMENSION):
for column in range(DIMENSION):
piece = board[row][column]
if piece != "--":
screen.blit(IMAGES[piece], p.Rect(column * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def draw_text(surface, text, color, pos, font):
text_surface = font.render(text, True, color)
surface.blit(text_surface, pos)
def drawChat(screen, chat_history, user_input, font):
"""
Draws the chat panel with chat history and user input.
"""
chat_panel_rect = p.Rect(BOARD_WIDTH, 0, CHAT_PANEL_WIDTH, CHAT_PANEL_HEIGHT)
p.draw.rect(screen, p.Color('black'), chat_panel_rect)
# Draw chat history
text_y = 5
for message in chat_history:
text = f'{message["role"]}: {message["content"]}'
text_object = font.render(text, True, p.Color('white'))
text_location = chat_panel_rect.move(5, text_y)
screen.blit(text_object, text_location)
text_y += text_object.get_height() + 2
# Draw user input
draw_text(screen, f'User: {user_input}', p.Color('white'), (BOARD_WIDTH + 5, CHAT_PANEL_HEIGHT - 25), font)
# the chat panel
def drawMoveLog(screen, game_state, chat_history, user_input, font):
"""
Draws the move log and chat panel.
"""
move_log_rect = p.Rect(BOARD_WIDTH, 0, MOVE_LOG_PANEL_WIDTH, MOVE_LOG_PANEL_HEIGHT)
p.draw.rect(screen, p.Color('black'), move_log_rect)
# Draw move log
move_log = game_state.move_log
move_texts = []
for i in range(0, len(move_log), 2):
move_string = str(i // 2 + 1) + '. ' + str(move_log[i]) + " "
if i + 1 < len(move_log):
move_string += str(move_log[i + 1]) + " "
move_texts.append(move_string)
moves_per_row = 3
padding = 5
line_spacing = 2
text_y = padding
for i in range(0, len(move_texts), moves_per_row):
text = ""
for j in range(moves_per_row):
if i + j < len(move_texts):
text += move_texts[i + j]
text_object = font.render(text, True, p.Color('white'))
text_location = move_log_rect.move(padding, text_y)
screen.blit(text_object, text_location)
text_y += text_object.get_height() + line_spacing
# Draw user input
draw_text(screen, f'User: {user_input}', p.Color('white'), (BOARD_WIDTH + 5, CHAT_PANEL_HEIGHT - 25), font)
drawChat(screen, chat_history, user_input, font)
def drawEndGameText(screen, text):
font = p.font.SysFont("Helvetica", 32, True, False)
text_object = font.render(text, False, p.Color("gray"))
text_location = p.Rect(0, 0, BOARD_WIDTH, BOARD_HEIGHT).move(BOARD_WIDTH / 2 - text_object.get_width() / 2,
BOARD_HEIGHT / 2 - text_object.get_height() / 2)
screen.blit(text_object, text_location)
text_object = font.render(text, False, p.Color('black'))
screen.blit(text_object, text_location.move(2, 2))
def animateMove(move, screen, board, clock):
"""
Animating a move
"""
global colors
d_row = move.end_row - move.start_row
d_col = move.end_col - move.start_col
frames_per_square = 10 # frames to move one square
frame_count = (abs(d_row) + abs(d_col)) * frames_per_square
for frame in range(frame_count + 1):
row, col = (move.start_row + d_row * frame / frame_count, move.start_col + d_col * frame / frame_count)
drawBoard(screen)
drawPieces(screen, board)
# erase the piece moved from its ending square
color = colors[(move.end_row + move.end_col) % 2]
end_square = p.Rect(move.end_col * SQUARE_SIZE, move.end_row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)
p.draw.rect(screen, color, end_square)
# draw captured piece onto rectangle
if move.piece_captured != '--':
if move.is_enpassant_move:
enpassant_row = move.end_row + 1 if move.piece_captured[0] == 'b' else move.end_row - 1
end_square = p.Rect(move.end_col * SQUARE_SIZE, enpassant_row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)
screen.blit(IMAGES[move.piece_captured], end_square)
# draw moving piece
screen.blit(IMAGES[move.piece_moved], p.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
p.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
this the the error that is occuring
/chess/chess-engine/chess/ChessMain.py", line 226, in send_move_to_llm
ai_reply = response.json()["choices"][0]["text"]
KeyError: 'text'
|
2246c8f8750b898bc60d4866f148a31f
|
{
"intermediate": 0.31536781787872314,
"beginner": 0.533728301525116,
"expert": 0.15090391039848328
}
|
37,888
|
create table of 11 columns and 20 rows about technology levels.
|
18d4a4ac7fb34bdd6ab18fb4cc936042
|
{
"intermediate": 0.41520270705223083,
"beginner": 0.16174541413784027,
"expert": 0.4230519235134125
}
|
37,889
|
import os
import subprocess
import numpy as np
import uuid # Import uuid to generate unique IDs
from moviepy.editor import VideoFileClip
from scipy.io import wavfile
import random
temporary_audio_files = []
# Define video file extensions and the output folder
video_extensions = ['.mp4', '.mkv', '.wmv', '.avi']
output_folder = 'Output'
def update_max_segments_for_selected_video():
global selected_video_path, max_segments, segment_duration, starting_offset_seconds, ending_offset_seconds, num_moments
if selected_video_path in video_durations:
video_duration = video_durations[selected_video_path]
max_segments = calculate_max_segments(video_duration, segment_duration, starting_offset_seconds, ending_offset_seconds)
num_moments = min(num_moments, max_segments) # Ajustez num_moments si nécessaire
else:
max_segments = 0
def sorting_preference_to_string(pref):
sorting_options = {
1: "Par ordre de lecture de la vidéo",
2: "Par ordre inverse de lecture de la vidéo",
3: "Par volume croissant",
4: "Par volume décroissant",
5: "Aléatoire"
}
return sorting_options.get(pref, "Non défini")
def peak_position_to_string(pos):
peak_options = {
'1': "À 1/4 du temps de lecture de la vidéo",
'2': "À 1/2 du temps de lecture de la vidéo",
'3': "À 3/4 du temps de lecture de la vidéo"
}
return peak_options.get(pos, "Non défini")
def choose_video(videos):
# Separate root files from subdirectory files
root_files = [video for video in videos if os.path.dirname(os.path.relpath(video)) == '']
subdirectory_files = [video for video in videos if os.path.dirname(os.path.relpath(video)) != '']
# Sort the files in subdirectories
subdirectory_files_sorted = sorted(subdirectory_files, key=lambda x: (os.path.dirname(x).lower(), os.path.basename(x).lower()))
# Combine lists: root files first, then sorted subdirectory files
combined_videos = root_files + subdirectory_files_sorted
print("Liste des vidéos disponibles :")
for i, video in enumerate(combined_videos):
# Get the relative path for printing
rel_path = os.path.relpath(video)
print(f"{i + 1}- {rel_path}")
while True:
choice = input("Veuillez choisir la vidéo à extraire (entrez le numéro) : ")
try:
choice_idx = int(choice) - 1
if 0 <= choice_idx < len(combined_videos):
return combined_videos[choice_idx]
else:
print("Le numéro doit être valide. Veuillez réessayer.")
except ValueError:
print("Veuillez entrer un nombre valide.")
def print_menu(selected_video_path):
global max_segments
global include_subfolders, starting_offset_seconds, ending_offset_seconds
global segment_duration, num_moments, sorting_preference, peak_position
video_name = os.path.basename(selected_video_path) if selected_video_path else "Aucune vidéo sélectionnée"
print("\nMenu des options :")
print(f"1. Traiter les sous-dossiers ou non ({str(include_subfolders)})")
print(f"2. Effectuer un retrait temporel (début: {str(starting_offset_seconds)}s, fin: {str(ending_offset_seconds)}s)")
print(f"3. Changer la durée des segments ({str(segment_duration)}s | max segments extractibles: {str(max_segments)})")
print(f"4. Changer le nombre de segments à extraire ({str(num_moments)})")
print(f"5. Changer l'ordre de tri ({sorting_preference_to_string(sorting_preference)})")
print(f"6. Changer l'emplacement du pic sonore ({peak_position_to_string(peak_position)})")
print(f"7. Lancer l'extraction")
print(f"8- ({video_name}) - Modifier")
print(f"9. Quitter")
def ask_for_number_of_moments(max_segments):
while True:
num_input = input(f"Veuillez entrer le nombre de moments forts à extraire (maximum {max_segments}): ")
try:
num = int(num_input)
if num > 0 and num <= max_segments:
return num
else:
print(f"Le nombre doit être supérieur à 0 et inférieur ou égal à {max_segments}. Veuillez réessayer.")
except ValueError:
print("Entrée non valide, veuillez réessayer avec un nombre entier.")
def ask_yes_no_question(question):
answer = None
while answer not in ('1', '2'):
print(question)
print("1- Oui")
print("2- Non")
answer = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ").strip()
if answer not in ('1', '2'):
print("Entrée non valide, veuillez réessayer.")
return answer == '1'
def ask_offset_type():
print("Souhaitez-vous un décalage temporel relatif ou absolu ?")
print("1- Relatif (pourcentage)")
print("2- Absolu (secondes)")
while True:
choice = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ").strip()
if choice in ('1', '2'):
return choice
else:
print("Entrée non valide, veuillez réessayer.")
def get_offset_value(video_duration, offset_type):
if offset_type == '1': # Relative offset
while True:
percent = input("Entrez le pourcentage du temps vidéo à ignorer : ")
try:
percent_value = float(percent)
return percent_value * video_duration / 100
except ValueError:
print("Veuillez entrer un nombre valide.")
else: # Absolute offset
while True:
seconds = input("Entrez le nombre de secondes à ignorer : ")
try:
return float(seconds)
except ValueError:
print("Veuillez entrer un nombre valide.")
def ask_for_segment_duration(allowable_duration, video_duration, starting_offset_seconds, ending_offset_seconds):
# Cette fonction a été modifiée pour répondre plus précisément aux contraintes de durée.
while True:
duration = input("Quelle est la durée (en secondes) de chaque segment vidéo à extraire (Entrez un nombre positif et inférieur ou égal à {allowable_duration}) ? ")
try:
segment_duration = float(duration)
if 0 < segment_duration <= allowable_duration:
# Calculez le nombre maximal de segments pour une vidéo
available_duration = video_duration - (starting_offset_seconds + ending_offset_seconds)
max_segments = int(available_duration // segment_duration)
return segment_duration, max_segments
else:
print(f"La durée doit être un nombre positif et moins ou égale à {allowable_duration} secondes.")
except ValueError:
print("Veuillez entrer un nombre valide.")
def ask_directory_preference():
print("Souhaitez-vous inclure les sous-dossiers dans la recherche des vidéos ?")
print("1- Oui")
print("2- Non")
choice = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ")
return choice.strip() == '1' # Retourne True si l'utilisateur choisit '1' (Oui), False sinon
def calculate_loudness(audio_data):
if audio_data.ndim == 1:
volume = audio_data.astype('float32') ** 2
else:
volume = np.mean(audio_data.astype('float32') ** 2, axis=1)
volume_dB = 10 * np.log10(volume + 1e-9) # +1e-9 to avoid log(0) and convert to dB
return volume_dB
def calculate_max_segments(video_duration, segment_duration, starting_offset, ending_offset):
allowable_duration = video_duration - (starting_offset + ending_offset)
if allowable_duration > 0:
return int(allowable_duration // segment_duration)
else:
return 0
def find_loudest_moments(audio_filename, num_moments, segment_duration, video_duration, starting_offset, ending_offset):
rate, audio_data = wavfile.read(audio_filename)
# Convert stereo to mono if necessary
if audio_data.ndim == 2:
audio_data = np.mean(audio_data, axis=1)
volume_dB = calculate_loudness(audio_data)
segment_half_duration = segment_duration / 2.0
start_index = int(starting_offset * rate)
end_index = int((video_duration - ending_offset) * rate)
moments = []
volumes = []
while len(moments) < num_moments and (end_index - start_index) > 0:
index = np.argmax(volume_dB[start_index:end_index])
print(f"Current index: {index}, start_index: {start_index}, end_index: {end_index}") # Ajouté pour le débogage
moment = (start_index + index) / rate
print(f"Added moment at {moment} seconds") # Ajouté pour le débogage
moment_volume = volume_dB[start_index + index]
if moment - segment_half_duration < starting_offset or moment + segment_half_duration > video_duration - ending_offset:
volume_dB[start_index + index] = -np.inf
continue
moments.append(moment)
print(f"Added moment at {moment} seconds") # Ajouté pour le débogage
volumes.append(moment_volume)
# Clear the volume around the found moment to prevent picking up nearby moments
# Increment the global index by adding the start_index
global_index = start_index + index
# Définir le facteur de neutralisation (par exemple, 0.25 pour un quart de la durée du segment)
neutralization_factor = 0.1 # Ajuster ce facteur en fonction de vos besoins
# Calculer le rayon de neutralisation en appliquant le facteur à la durée du segment
neutralization_radius = segment_duration * neutralization_factor
# Déterminer les indices de début et de fin de la plage de neutralisation
clear_range_start = max(0, global_index - int(rate * neutralization_radius))
clear_range_end = min(len(volume_dB), global_index + int(rate * neutralization_radius))
# Mettre la plage de neutralisation à -inf pour éviter de sélectionner à nouveau des moments proches
volume_dB[clear_range_start:clear_range_end] = -np.inf
print(f"Volume after clearing at index {global_index}: {volume_dB[global_index]}")
return moments, volumes
def perform_extraction():
global starting_offset_seconds, ending_offset_seconds
global segment_duration, num_moments, sorting_preference, peak_position, processed_videos, selected_video_path, max_segments
# Vérifiez si une vidéo a été sélectionnée.
if not selected_video_path:
print("Aucune vidéo sélectionnée pour l'extraction.")
return
# Vérifiez si la vidéo sélectionnée est contenue dans video_durations.
if selected_video_path not in video_durations:
print(f"La vidéo sélectionnée '{selected_video_path}' n'est pas disponible.")
return
# Obtenez la durée de la vidéo sélectionnée.
duration = video_durations[selected_video_path]
available_duration = duration - (starting_offset_seconds + ending_offset_seconds)
if available_duration <= segment_duration:
print(f"La vidéo {selected_video_path} est trop courte après les décalages. Ignorer.")
return
if sorting_preference == 5: # Aléatoire
all_possible_moments = np.arange(starting_offset_seconds, duration - ending_offset_seconds - segment_duration, segment_duration) + (segment_duration / 2)
np.random.shuffle(all_possible_moments)
selected_moments = all_possible_moments[:num_moments]
volumes = [0] * len(selected_moments) # Les volumes sont justes pour la compatibilité avec extract_segments.
else:
audio_path = f'temp_audio_{uuid.uuid4().hex}.wav'
try:
with VideoFileClip(selected_video_path) as video_clip:
video_clip.audio.write_audiofile(audio_path, codec='pcm_s16le', fps=44100, nbytes=2, buffersize=2000)
moments, volumes = find_loudest_moments(audio_path, num_moments, segment_duration, duration, starting_offset_seconds, ending_offset_seconds)
sorted_moments, sorted_volumes = sort_moments(moments, volumes, sorting_preference)
selected_moments = sorted_moments
volumes = sorted_volumes
finally:
if os.path.exists(audio_path):
os.remove(audio_path)
# Juste avant l'appel à extract_segments, mettez à jour num_moments pour être sûr qu'il ne dépasse pas max_segments
num_moments = min(num_moments, max_segments)
extract_segments(selected_video_path, selected_moments, segment_duration, duration, peak_position)
processed_videos += 1
print(f"Extraction terminée pour la vidéo '{selected_video_path}'")
def extract_segments(video_path, moments, segment_duration, video_duration, peak_position):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
base_name = os.path.splitext(os.path.basename(video_path))[0]
half_segment_duration = segment_duration / 2
for i, moment in enumerate(moments):
if peak_position == '1': # 1/4
start_time = max(moment - segment_duration * 0.25, 0)
elif peak_position == '2': # 1/2
start_time = max(moment - segment_duration * 0.5, 0)
elif peak_position == '3': # 3/4
start_time = max(moment - segment_duration * 0.75, 0)
end_time = min(start_time + segment_duration, video_duration)
output_filename = f"{base_name}_moment{i + 1}.mp4"
output_path = os.path.join(output_folder, output_filename)
command = [
"ffmpeg",
"-y", # Overwrite output files without asking
"-ss", str(start_time), # Start time
"-i", video_path, # Input file
"-t", str(min(segment_duration, video_duration - start_time)), # Duration or remaining video
"-c:v", "libx264", # Specify video codec for output
"-preset", "medium", # Specify the encoding preset (trade-off between encoding speed and quality)
"-crf", "23", # Specify the Constant Rate Factor for quality (lower means better quality)
"-c:a", "aac", # Specify audio codec for output
"-strict", "-2", # Necessary for some versions of ffmpeg to use experimental aac encoder
"-b:a", "192k", # Specify the audio bitrate
output_path # Output path
]
try:
subprocess.run(command, check=True, stderr=subprocess.PIPE)
print(f"Extracted and re-encoded {output_filename}")
except subprocess.CalledProcessError as e:
# Catch the exception for this process, print an error message,
# but don't break from the for loop.
err_msg = e.stderr.decode('utf-8') if e.stderr else 'Unknown error'
print(f"Failed to extract segment from {video_path}: {err_msg}")
def store_segment_info(video_path, moment, volume, order):
base_name = os.path.splitext(os.path.basename(video_path))[0]
output_filename = f"{base_name}_moment{order}.mp4"
output_path = os.path.join(output_folder, output_filename)
extracted_segments.append({
'path': output_path,
'timestamp': moment,
'volume': volume
})
def ask_sorting_preference():
print("Comment souhaitez-vous trier les vidéos extraites ?")
print("1- Par ordre de lecture de la vidéo")
print("2- Par ordre inverse de lecture de la vidéo")
print("3- Par volume croissant")
print("4- Par volume décroissant")
print("5- Aléatoire")
choice = int(input("Veuillez entrer le numéro de votre choix : "))
return choice
def sort_moments(moments, volumes, choice):
if choice == 1: # Par ordre de lecture de la vidéo
zipped = sorted(zip(moments, volumes), key=lambda x: x[0])
elif choice == 2: # Par ordre inverse de lecture de la vidéo
zipped = sorted(zip(moments, volumes), key=lambda x: x[0], reverse=True)
elif choice == 3: # Par volume croissant
zipped = sorted(zip(moments, volumes), key=lambda x: x[1])
elif choice == 4: # Par volume décroissant
zipped = sorted(zip(moments, volumes), key=lambda x: x[1], reverse=True)
elif choice == 5: # Pas de tri, sélection aléatoire
zipped = list(zip(moments, volumes))
random.shuffle(zipped)
else:
zipped = zip(moments, volumes)
# Unzip the list of tuples to two lists
sorted_moments, sorted_volumes = zip(*zipped) if zipped else ([], [])
return list(sorted_moments), list(sorted_volumes)
def get_video_durations(include_subfolders):
video_durations = {}
for root, dirs, files in os.walk('.', topdown=True):
# Si l'utilisateur ne souhaite pas inclure les sous-dossiers, nous modifions dirs sur place
if not include_subfolders:
dirs[:] = [] # Cela empêchera os.walk de descendre dans tous les sous-dossiers
# La suite du traitement des fichiers reste inchangée
for file in files:
if file.lower().endswith(tuple(video_extensions)):
video_path = os.path.join(root, file)
try:
# Essayez d'ouvrir et d'extraire les métadonnées du fichier vidéo.
video_clip = VideoFileClip(video_path)
video_duration = video_clip.duration
video_durations[video_path] = video_duration
except Exception as e:
# Si une erreur survient, affichez un message et ignorez le fichier vidéo.
print(f"Error processing video {video_path}: {e}")
finally:
# Assurez-vous de fermer le clip pour libérer les ressources.
video_clip.close()
return video_durations
def confirm_segment_number_or_ask_again(video_duration, starting_offset_seconds, ending_offset_seconds):
allowable_duration = video_duration - (starting_offset_seconds + ending_offset_seconds)
while True:
segment_duration, max_segments = ask_for_segment_duration(allowable_duration, video_duration, starting_offset_seconds, ending_offset_seconds)
print(f"Avec cette durée, vous pouvez extraire jusqu'à {max_segments} segments.")
confirmation = ask_yes_no_question("Voulez-vous continuer avec ce nombre de segments ?")
if confirmation:
return segment_duration, max_segments
def ask_peak_position():
print("Où doit être situé le pic sonore dans la vidéo extraite ?")
print("1- A 1/4 du temps de lecture de la vidéo")
print("2- A 1/2 du temps de lecture de la vidéo")
print("3- A 3/4 du temps de lecture de la vidéo")
while True:
choice = input("Veuillez entrer le numéro de votre choix (1, 2, ou 3) : ").strip()
if choice in ('1', '2', '3'):
return choice
else:
print("Entrée non valide, veuillez réessayer.")
def main():
global include_subfolders, starting_offset_seconds, ending_offset_seconds
global segment_duration, num_moments, sorting_preference, peak_position
global processed_videos, video_durations, selected_video_path, max_segments
# Initialize the variables with default values
include_subfolders = False
starting_offset_seconds = 0
ending_offset_seconds = 0
segment_duration = 5.0 # Default value, e.g., 5 seconds
num_moments = 20 # Default value, e.g., 20 moments
sorting_preference = 4 # Default value, e.g., sorting by descending volume
peak_position = '2' # Default value, e.g., peak at the middle of the segment
selected_video_path = "" # Initialement vide
processed_videos = 0
# Load video durations at the start of the script
video_durations = get_video_durations(include_subfolders)
if not video_durations:
print("Aucune vidéo trouvée pour l'analyse.")
exit()
video_list = sorted(list(video_durations.keys()), key=lambda x: os.path.basename(x))
selected_video_path = video_list[0] if video_list else "" # Select the first video by default, if available.
# Calculate max_segments with the newly obtained video_durations
video_duration = video_durations[selected_video_path] # Obtenez la durée de la vidéo sélectionnée
max_segments = calculate_max_segments(video_durations[selected_video_path], segment_duration, starting_offset_seconds, ending_offset_seconds)
while True:
# Recalculate the max segments using the selected video before displaying the menu
update_max_segments_for_selected_video()
# Display the menu with the updated max segments
print_menu(selected_video_path)
choice = input("Veuillez entrer le numéro de votre choix : ").strip()
# Handle user choices
if choice == '1':
# Update include_subfolders and recalculate video durations
include_subfolders = ask_directory_preference()
video_durations = get_video_durations(include_subfolders)
# Optionally, reset selected_video_path if include_subfolders changed
video_list = sorted(list(video_durations.keys()), key=lambda x: os.path.basename(x))
selected_video_path = video_list[0] if video_list else ""
update_max_segments_for_selected_video()
elif choice == '2':
# Récupérez les nouvelles valeurs.
offset_type = ask_offset_type()
# Utilisez une valeur minimale mise à jour si nécessaire.
min_duration = min(video_durations.values())
print("Configuration du retrait temporel pour le début de la vidéo:")
starting_offset_seconds = get_offset_value(min_duration, offset_type)
print("Configuration du retrait temporel pour la fin de la vidéo:")
ending_offset_seconds = get_offset_value(min_duration, offset_type)
elif choice == '3':
# L'utilisateur définit la durée des segments et potentiellement le nombre de moments
video_duration = min(video_durations.values()) # Min. duration among all videos
allowable_duration = video_duration - (starting_offset_seconds + ending_offset_seconds)
segment_duration, max_segments = ask_for_segment_duration(
allowable_duration,
video_duration,
starting_offset_seconds,
ending_offset_seconds
)
if num_moments > max_segments:
num_moments = max_segments
# Ce bloc assure que num_moments n'excède jamais max_segments après un changement de durée des segments
elif choice == '4':
num_moments = ask_for_number_of_moments(max_segments)
elif choice == '5':
sorting_preference = ask_sorting_preference()
elif choice == '6':
peak_position = ask_peak_position()
elif choice == '7':
# Exécutez vos sous-fonctions pour effectuer l'extraction des segments.
# Vous souhaiterez probablement encapsuler cela dans une autre fonction.
perform_extraction() # Call perform_extraction instead of extract_segments
elif choice == '8':
video_list = sorted(list(video_durations.keys()), key=lambda x: os.path.basename(x))
prev_video_path = selected_video_path
selected_video_path = choose_video(video_list)
if selected_video_path != prev_video_path:
print(f"Vidéo sélectionnée pour l'extraction : {os.path.basename(selected_video_path)}")
update_max_segments_for_selected_video() # Mise à jour des segments max après le choix.
elif choice == '9':
print("Fin du programme.")
break
else:
print("Choix non valide. Veuillez réessayer.")
print(f"Le traitement de toutes les vidéos est terminé. {processed_videos} vidéos ont été traitées.")
if __name__ == "__main__":
main()
|
c528cb40c513e703871a4ddd05c9a8d3
|
{
"intermediate": 0.3652503192424774,
"beginner": 0.49265196919441223,
"expert": 0.14209769666194916
}
|
37,890
|
def draw_grid(self, grid_type, image_width, image_height):
# Calculate center position to center the grid on the image
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
x_center = canvas_width // 2
y_center = canvas_height // 2
# Calculate the top-left corner position of the image
x_start = x_center - (image_width // 2)
y_start = y_center - (image_height // 2)
grid_color = "grey"
if grid_type == "a":
# Draw a simple 3x3 grid
for i in range(1, 3):
self.canvas.create_line(x_start + image_width * i / 3, y_start, x_start + image_width * i / 3, y_start + image_height, fill=grid_color)
self.canvas.create_line(x_start, y_start + image_height * i / 3, x_start + image_width, y_start + image_height * i / 3, fill=grid_color)
elif grid_type == "b":
# Draw a golden ratio grid
gr = (1 + 5 ** 0.5) / 2 # golden ratio
self.canvas.create_line(x_start + image_width / gr, y_start, x_start + image_width / gr, y_start + image_height, fill=grid_color)
self.canvas.create_line(x_start + image_width - (image_width / gr), y_start, x_start + image_width - (image_width / gr), y_start + image_height, fill=grid_color)
self.canvas.create_line(x_start, y_start + image_height / gr, x_start + image_width, y_start + image_height / gr, fill=grid_color)
self.canvas.create_line(x_start, y_start + image_height - (image_height / gr), x_start + image_width, y_start + image_height - (image_height / gr), fill=grid_color)
elif grid_type == "c":
# Draw a 4x4 grid
for i in range(1, 4):
self.canvas.create_line(x_start + image_width * i / 4, y_start, x_start + image_width * i / 4, y_start + image_height, fill=grid_color)
self.canvas.create_line(x_start, y_start + image_height * i / 4, x_start + image_width, y_start + image_height * i / 4, fill=grid_color)
elif grid_type == "d":
pass
make def draw_grid to open a window that ask for input for x and y for the amount of lines in the grid instead. make it open a message window that ask for 2 boxes input (value)x(value) below the input add a checkbox for golden ratio that when turned on disabled the grid xy input box and when i click apply it insert that value to be the number of x and y lines on the grid
|
2cbd4b3bb615c99fd94a0ddc470c1f2e
|
{
"intermediate": 0.29930901527404785,
"beginner": 0.44626063108444214,
"expert": 0.25443029403686523
}
|
37,891
|
write a table of 11 columns and 20 rows about technology levels, the rows represent the levels. the first level is paleolithic level and the last one being kardashev type 5.
|
3c771e39f4da496fc531a28a4d2ab0a0
|
{
"intermediate": 0.2662108540534973,
"beginner": 0.19343702495098114,
"expert": 0.5403521656990051
}
|
37,892
|
I have an Android app with these dependencies:
dependencies {
implementation("com.google.android.gms:play-services-ads:22.6.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.8.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}
I have to add the following dependencies to it:
def lifecycle_version = "2.3.1"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
How can I do it? Please format it to work.
|
e55ed805162a67bb5f97bdad56039570
|
{
"intermediate": 0.44282132387161255,
"beginner": 0.2631468176841736,
"expert": 0.29403185844421387
}
|
37,893
|
I have an app with these dependencies:
dependencies {
implementation("com.google.android.gms:play-services-ads:22.6.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.8.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}
I need to add the following dependencies:
def lifecycle_version = "2.3.1"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
How can I do it? Make the formatting work.
|
da8f19af11c5ae9358675326f6285543
|
{
"intermediate": 0.4962187707424164,
"beginner": 0.25730225443840027,
"expert": 0.24647900462150574
}
|
37,894
|
I have an app with these dependencies:
dependencies {
implementation("com.google.android.gms:play-services-ads:22.6.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.8.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}
I need to add the following dependencies:
def lifecycle_version = "2.3.1"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
How can I do it? Make the formatting work.
|
762c9a6b038eaa529359a5238e483a5d
|
{
"intermediate": 0.4962187707424164,
"beginner": 0.25730225443840027,
"expert": 0.24647900462150574
}
|
37,895
|
make tooltip from tktooltip appear on top of a topmost window
|
ee580f903d8af922317c7ba826d299b8
|
{
"intermediate": 0.3614960014820099,
"beginner": 0.2682011127471924,
"expert": 0.37030285596847534
}
|
37,896
|
Can you proofread and critique the below DDLG / CGL personals ad I'm planning to post? My name/location/age will be in the title so it's not in the ad itself. Also we can assume the target audience understands some acronyms like TPE, aro/ace etc
The ad posting format is markdown but I will paste it in code tags to let you analyse correctness of the formatting
|
456e18b7b16017a9f8f97b45ae67464b
|
{
"intermediate": 0.32344549894332886,
"beginner": 0.452026903629303,
"expert": 0.22452761232852936
}
|
37,897
|
i’m trying to add ai LLM to a python chess game. here’s the logic i’m trying to accomplish
-two main functions: chess game amd LLM chat
- Chess Game
- User or chess ai makes a chess move
- the game logic is applied
- repeat this logic for gameplay loop
- LLM Chat
- User input area where a user can enter a message
- when a message is entered, it is rendered in the chat area, added to the history and sent to the LLM
- the LLM sends a response back, and the response is rendered in the text area
i did a prelim to test out only the chat functionality. it works and i can do multi-turn conversations
|
f94f43564eea7ce71fbf15a148011096
|
{
"intermediate": 0.45620083808898926,
"beginner": 0.23364612460136414,
"expert": 0.3101530969142914
}
|
37,898
|
Title: Unraveling the Future of Online Communication: A Deep Dive Into Emerging Trends
Introduction:
Online communication has come a long way since its humble beginnings. From bulletin board systems and chat rooms to instant messaging and social media giants, each phase of development brought forth unique tools and functionalities shaping human interaction. Now, let us delve into the key drivers charting the course of tomorrow's digital dialogues.
Artificial Intelligence (AI)-Powered Assistants: Chatbots and voice assistants powered by advanced AI algorithms will play a crucial role in online communications. Natural language processing capabilities will significantly improve conversation fluency, making interactions indistinguishable from those involving humans. Furthermore, these bots can serve as customer support agents, moderators, or companions, addressing queries, enforcing rules, and providing emotional comfort when needed.
Multimodal Interfaces: Besides textual messages, online conversations may incorporate multiple modalities such as audio, video, holograms, and augmented reality elements. Realistic avatars, expressive facial animations, gestures, and tone of voice will contribute to enhanced empathy, intimacy, and overall satisfaction during remote exchanges.
Contextually Intelligent Systems: Advances in context awareness will allow digital platforms to better understand nuanced meanings behind words and adapt responses accordingly. For instance, sarcasm detection or cultural sensitivity features could prevent misunderstandings and foster inclusivity across international communities. Moreover, proactive recommendation engines that consider situational factors such as location, weather conditions, mood, or historical behavior might streamline decision-making processes and facilitate serendipitous discoveries.
Ephemeral Content Overload: Inspired by successful applications like Snapchat and TikTok, fleeting posts filled with humor, spontaneity, and creativity will gain traction. Embracing impermanence allows users to experiment freely without fearing judgment based on past activities. Consequently, authentic self-expression becomes the norm rather than an exception in online spheres.
Digital Identity Management: Managing digital identities spanning numerous platforms requires robust authentication mechanisms ensuring privacy, security, and verifiability. Self-sovereign identity solutions backed by blockchain technology give individuals full control over their persona attributes and credentials while preventing impersonation attempts. Anchoring trustworthy reputation scores tied to verified accounts encourages responsible conduct and fosters positive online discourse.
Immersive Mixed Reality Spaces: Combining physical and digital environments opens up limitless opportunities for creative expression, experiential marketing, collaborative problem solving, or simply hanging out with friends from afar. Blurring boundaries between real and virtual life enables people to establish deeper connections regardless of geographical constraints, leading ultimately towards a highly interconnected global village mentality.
Neuroenhancements and Biometrics: Wearables and implantable technologies capturing neurological signals and biometric data promise unprecedented insights into users' emotions, intentions, and cognitive states. Leveraging such feedback loops, platforms can fine-tune user experiences optimizing engagement levels while maintaining healthy limits against excessive use or addictive behaviors.
Conclusion:
Navigating the ever-evolving terrain of online communication calls upon both curiosity and vigilance. Anticipatory foresight coupled with judicious governance ensures nascent innovations align with societal values and promote overall wellbeing. Through meaningful dialogue and cooperation amongst stakeholders, we shall collectively craft a vibrant digital landscape teeming with endless possibilities for connection, exploration, and self-actualization.
|
0d1adfd2e80deeaf6816e90a2d5f5e37
|
{
"intermediate": 0.11726520210504532,
"beginner": 0.455757200717926,
"expert": 0.4269775450229645
}
|
37,899
|

# Diagrams
[](/LICENSE)
[](https://badge.fury.io/py/diagrams)


[](https://www.tickgit.com/browse?repo=github.com/mingrammer/diagrams)

<a href="https://www.buymeacoffee.com/mingrammer" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
**Diagram as Code**.
Diagrams lets you draw the cloud system architecture **in Python code**. It was born for **prototyping** a new system architecture design without any design tools. You can also describe or visualize the existing system architecture as well. Diagrams currently supports main major providers including: `AWS`, `Azure`, `GCP`, `Kubernetes`, `Alibaba Cloud`, `Oracle Cloud` etc... It also supports `On-Premise` nodes, `SaaS` and major `Programming` frameworks and languages.
**Diagram as Code** also allows you to **track** the architecture diagram changes in any **version control** system.
> NOTE: It does not control any actual cloud resources nor does it generate cloud formation or terraform code. It is just for drawing the cloud system architecture diagrams.
## Providers

















## Getting Started
It requires **Python 3.7** or higher, check your Python version first.
It uses [Graphviz](https://www.graphviz.org/) to render the diagram, so you need to [install Graphviz](https://graphviz.gitlab.io/download/) to use **diagrams**. After installing graphviz (or already have it), install the **diagrams**.
> macOS users can download the Graphviz via `brew install graphviz` if you're using [Homebrew](https://brew.sh).
|
8fe880d11a25e131cd2f12f389eab883
|
{
"intermediate": 0.35830986499786377,
"beginner": 0.41071590781211853,
"expert": 0.2309741973876953
}
|
37,900
|
мне нужно написать скрипт на js чтобы card1 был изначально скрыт. при наведение на card появлялся card1 а card скрывался
|
e8132ecdec5a51442e5df808355ddba0
|
{
"intermediate": 0.32183271646499634,
"beginner": 0.3152267634868622,
"expert": 0.3629405200481415
}
|
37,901
|
Write me a simple GLSL shader that affects only a solid unbroken blob of red color
|
de945f9a5287cf433893d545cf6b7899
|
{
"intermediate": 0.44320377707481384,
"beginner": 0.3262380063533783,
"expert": 0.23055824637413025
}
|
37,902
|
How do I use the X11 library in C to make a window not resizeable?
|
643866e5edb167b636897a8f5bad81e1
|
{
"intermediate": 0.8102954030036926,
"beginner": 0.09255114197731018,
"expert": 0.09715347737073898
}
|
37,903
|
Check my code : import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
from collections import Counter
# Expert LSTM Model
class LSTMExpert(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTMExpert, self).__init__()
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
# Shape of h: [batch_size, sequence_length, hidden_size]
# No longer taking the last sequence output, transform for all time steps
h = h.reshape(-1, h.shape[2]) # Flatten to two dimensions: [batch_size * sequence_length, hidden_size]
return self.fc(h)
# Gating Network
class GatingNetwork(nn.Module):
def __init__(self, input_size, num_experts):
super(GatingNetwork, self).__init__()
self.fc = nn.Linear(input_size, num_experts)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
if x.dim() > 2:
x = x.view(x.size(0), -1) # Flatten the tensor correctly
x = self.fc(x)
return self.softmax(x)
# Mixture of Experts Model
class MixtureOfExperts(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_experts):
super(MixtureOfExperts, self).__init__()
self.num_experts = num_experts
self.experts = nn.ModuleList([LSTMExpert(input_size, hidden_size, output_size) for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Flatten x for gating input: [batch_size * sequence_length, input_size]
gating_input = x.contiguous().view(-1, x.shape[-1])
# Get gating scores for each expert: [batch_size * sequence_length, num_experts, 1]
gating_scores = self.gating_network(gating_input).view(-1, self.num_experts, 1)
# Compute outputs from each expert
expert_outputs = [expert(x) for expert in self.experts] # List of [batch_size * sequence_length, vocab_size] tensors
# Stack along a new dimension for experts: [batch_size * sequence_length, vocab_size, num_experts]
expert_outputs = torch.stack(expert_outputs, dim=2)
# Calculate weighted sum of expert outputs: [batch_size * sequence_length, vocab_size]
mixed_output = torch.bmm(expert_outputs, gating_scores) # [batch_size * sequence_length, vocab_size, 1]
mixed_output = mixed_output.squeeze(-1) # Remove last singleton dimension
return mixed_output
class TextDataset(Dataset):
def __init__(self, path, seq_len):
self.seq_len = seq_len
with open(path, "r", encoding="utf-8") as f:
text = f.read()
words = text.split()
self.vocab, self.idx2token = self.build_vocab(words)
self.tokens = [self.vocab.get(w, 0) for w in words] # Default to 0 for unknown tokens
def build_vocab(self, words):
counts = Counter(words)
vocab = {word: i for i, (word, _) in enumerate(counts.most_common(), 1)}
vocab["<pad>"] = 0
idx2token = {i: word for word, i in vocab.items()}
return vocab, idx2token
def __len__(self):
return len(self.tokens) // self.seq_len
def __getitem__(self, idx):
chunk = self.tokens[idx * self.seq_len: (idx + 1) * self.seq_len]
x = chunk[:-1]
y = chunk[1:]
return torch.tensor(x), torch.tensor(y)
def collate_fn(batch):
inputs, targets = zip(*batch)
inputs = pad_sequence(inputs, batch_first=True, padding_value=0)
targets = pad_sequence(targets, batch_first=True, padding_value=0)
return inputs, targets
# Set the path to your text file and define sequence length
path_to_text = 'GSM2K.txt' # replace with the path to your text file
seq_len = 32 # sequence length
# Create a dataset and data loader
dataset = TextDataset(path_to_text, seq_len)
data_loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn)
def train_model_TXT(model, criterion, optimizer, num_epochs, data_loader):
model.train()
for epoch in range(num_epochs):
total_loss = 0
for i, (inputs, targets) in enumerate(data_loader):
optimizer.zero_grad()
# Forward pass
predictions = model(inputs)
# Flatten targets to be [batch_size * sequence_length]
targets = targets.view(-1)
# Flatten predictions to be [batch_size * sequence_length, num_classes]
predictions = predictions.view(-1, predictions.size(-1))
# Loss computation
loss = criterion(predictions, targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / len(data_loader.dataset)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
def generate_text(model, dataset, seed_text, num_generate, temperature=1.0):
model.eval() # Put the model in evaluation mode
# List to store the generated tokens
generated_tokens = []
# Initial sequence (prefix) to start the generation process
input_sequence = [dataset.vocab.get(word, dataset.vocab["<pad>"]) for word in seed_text.split()] # Convert to token IDs
current_sequence = torch.tensor(input_sequence, dtype=torch.long).unsqueeze(0)
# Generate num_generate tokens
for _ in range(num_generate):
# Forward pass through the model
with torch.no_grad():
output = model(current_sequence)
# Get probabilities, apply temperature scaling, and sample from the distribution
probabilities = F.softmax(output[-1] / temperature, dim=0).detach()
next_token_idx = torch.multinomial(probabilities, 1).item()
# Append token to the current sequence and to the generated tokens
generated_tokens.append(next_token_idx)
current_sequence = torch.cat((current_sequence, torch.tensor([[next_token_idx]])), 1)
# Convert tokens to words
generated_text = " ".join([dataset.idx2token.get(token, "<unk>") for token in generated_tokens]) # Use .get() to provide a default value for missing keys
return generated_text
# Integration of MoE with the rest of the code
vocab_size = len(dataset.vocab) # The size of the vocabulary
embedding_dim = 128 # Size of embeddings
hidden_size = 256 # Number of features in the hidden state of the LSTM
num_experts = 2 # Define the number of LSTM experts you want in your MoE model
# Instantiate the MixtureOfExperts model
mixture_of_experts_model = MixtureOfExperts(embedding_dim, hidden_size, vocab_size, num_experts)
# Wrap the experts and the embedding layer into a new combined model, replacing SingleLSTM_TXT
class MoEModel(nn.Module):
def __init__(self, embedding_dim, vocab_size, MoE):
super(MoEModel, self).__init__()
self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
self.MoE = MoE
def forward(self, x):
embedded = self.embedding(x)
output = self.MoE(embedded)
return output
# Instantiate the MoEModel with embeddings and mixture of experts
moe_model = MoEModel(embedding_dim, vocab_size, mixture_of_experts_model)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# Example usage with your model:
total_params = count_parameters(moe_model)
print(f"Total trainable parameters: {total_params}")
# Training parameters
num_epochs = 2
batch_size = 256
learning_rate = 1e-3
# Define Loss Function and Optimizer for MoE model
criterion = nn.CrossEntropyLoss() # Use CrossEntropyLoss for classification tasks
optimizer = torch.optim.Adam(moe_model.parameters(), lr=learning_rate)
# Replace references to single_lstm_txt_model with moe_model
# Train the model with the text data
train_model_TXT(moe_model, criterion, optimizer, num_epochs, data_loader)
# Start a loop for the interactive chat-like text generation
while True:
try:
# Get user input
seed_text = input("Enter seed text (type 'quit' to stop): ")
# Check if user wants to quit the interaction
if seed_text.lower() == "quit":
print("Exiting text generation chat.")
break
# User input is not empty and not “quit”, generate text
if seed_text.strip():
num_generate = 16 # Number of words to generate
temperature = 0.5 # Sampling temperature, higher will increase diversity
# Use the trained model to generate text
generated_text = generate_text(moe_model, dataset, seed_text, num_generate, temperature)
print("Generated Text:", generated_text)
else:
print("Seed text cannot be empty.")
except KeyboardInterrupt:
# Handle KeyboardInterrupt (Ctrl+C) to gracefully exit
print("\nExiting text generation chat.")
break
|
f3913e03a2c15a542050285b664e4237
|
{
"intermediate": 0.37488099932670593,
"beginner": 0.3967312276363373,
"expert": 0.22838781774044037
}
|
37,904
|
I have the following code. It's about calling an App Open Ad. I have three problems: The first one is that when I open the app for the first time, it does not shows the ad. In the log, it only shows "AppOpenAdManager - Ad was loaded.". My second problem is that when I open the app for the second time, it shows the ad, but in the log: "NullPointerException occurs when invoking a method from a delegating listener.
java.lang.NullPointerException: Context cannot be null.
at com.google.android.gms.common.internal.Preconditions.checkNotNull(com.google.android.gms:play-services-basement@@18.2.0:2)
at com.google.android.gms.ads.appopen.AppOpenAd.load(com.google.android.gms:play-services-ads-lite@@22.6.0:1)
at com.example.myapplication.MyApplication$AppOpenAdManager.loadAd(MyApplication.java:70)
at com.example.myapplication.MyApplication$AppOpenAdManager.access$300(MyApplication.java:50)
at com.example.myapplication.MyApplication$AppOpenAdManager$2.onAdDismissedFullScreenContent(MyApplication.java:117)
at com.google.android.gms.internal.ads.zzaxg.zzc(com.google.android.gms:play-services-ads-lite@@22.6.0:1)
at com.google.android.gms.internal.ads.zzezl.zza(Unknown Source:2)
at com.google.android.gms.internal.ads.zzfaz.zza(com.google.android.gms:play-services-ads@@22.6.0:2)
at com.google.android.gms.internal.ads.zzezs.zzj(com.google.android.gms:play-services-ads@@22.6.0:4)
at com.google.android.gms.internal.ads.zzfaa.zzq(com.google.android.gms:play-services-ads@@22.6.0:2)
at com.google.android.gms.internal.ads.zzfaa.zza(com.google.android.gms:play-services-ads@@22.6.0:1)
at com.google.android.gms.internal.ads.zzbju.zza(com.google.android.gms:play-services-ads@@22.6.0:3)
at com.google.android.gms.internal.ads.zzchc.zzP(com.google.android.gms:play-services-ads@@22.6.0:6)
at com.google.android.gms.internal.ads.zzchc.zzj(com.google.android.gms:play-services-ads@@22.6.0:16)
at com.google.android.gms.internal.ads.zzchv.zza(com.google.android.gms:play-services-ads@@22.6.0:3)
at com.google.android.gms.internal.ads.zzcht.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:958)
at android.os.Handler.dispatchMessage(Handler.java:99)
at com.google.android.gms.internal.ads.zzfqv.zza(com.google.android.gms:play-services-ads-lite@@22.6.0:1)
at com.google.android.gms.ads.internal.util.zzf.zza(com.google.android.gms:play-services-ads@@22.6.0:1)
at com.google.android.gms.internal.ads.zzfqv.dispatchMessage(com.google.android.gms:play-services-ads-lite@@22.6.0:1)
at android.os.Looper.loopOnce(Looper.java:205)
at android.os.Looper.loop(Looper.java:294)
at android.app.ActivityThread.main(ActivityThread.java:8177)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)
A GMSG tried to close something that wasn't an overlay.
#004 The webview is destroyed. Ignoring action.
sendCancelIfRunning: isInProgress=falsecallback=android.view.ViewRootImpl$$ExternalSyntheticLambda17@d7b2a91
"
And my third problem is that if I re-open the app, it doesn't shows the ad, instead gives log: "The app open ad is not ready yet."
How can I solve these problems?
The code:
package com.example.myapplication;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.appopen.AppOpenAd;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import java.util.Date;
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks, LifecycleObserver {
private AppOpenAdManager appOpenAdManager;
private Activity currentActivity;
public long loadTime = 0;
@Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
appOpenAdManager = new AppOpenAdManager(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
appOpenAdManager.showAdIfAvailable(currentActivity);
}
private class AppOpenAdManager {
private static final String LOG_TAG = "AppOpenAdManager";
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921";
private AppOpenAd appOpenAd = null;
private boolean isLoadingAd = false;
private boolean isShowingAd = false;
/** Constructor. */
public AppOpenAdManager(MyApplication myApplication) {}
/** Request an ad. */
private void loadAd(Context context) {
// We will implement this below.
if (isLoadingAd || isAdAvailable()) {
return;
}
isLoadingAd = true;
AdRequest request = new AdRequest.Builder().build();
AppOpenAd.load(
context, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
new AppOpenAd.AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(AppOpenAd ad) {
// Called when an app open ad has loaded.
Log.d(LOG_TAG, "Ad was loaded.");
appOpenAd = ad;
isLoadingAd = false;
loadTime = (new Date()).getTime();
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Called when an app open ad has failed to load.
Log.d(LOG_TAG, loadAdError.getMessage());
isLoadingAd = false;
}
});
}
public void showAdIfAvailable(
@NonNull final Activity activity){
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.");
return;
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.");
loadAd(MyApplication.this);
return;
}
appOpenAd.setFullScreenContentCallback(
new FullScreenContentCallback (){
@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, "Ad dismissed fullscreen content.");
appOpenAd = null;
isShowingAd = false;
loadAd(activity);
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, adError.getMessage());
appOpenAd = null;
isShowingAd = false;
loadAd(activity);
}
@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(LOG_TAG, "Ad showed fullscreen content.");
}
});
isShowingAd = true;
appOpenAd.show(activity);
}
/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
}
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {
// Updating the currentActivity only when an ad is not showing.
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity;
}
}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
|
729e3577a8bdcd119f58fa6fc10858a3
|
{
"intermediate": 0.35975566506385803,
"beginner": 0.4785308539867401,
"expert": 0.16171346604824066
}
|
37,905
|
hi
|
8b6b5e4ef0e94657bf377fd93b951c02
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
37,906
|
Assume the role of a senior programmer. Modify this code so that the new picture is flipped 180 degrees:
import csteutils.SimpleIO;
import csteutils.myro.MyroColorImage;
import csteutils.myro.MyroPixel;
import java.awt.Color;
public class OrientationChanger
{
public static void main (String [] args)
{
//loading the original image
SimpleIO.showMessage("Ready for original image?");
MyroColorImage picture = new MyroColorImage();
picture.resize(400,400);
picture.show();
MyroColorImage pic2 = new MyroColorImage(picture.getWidth() / 2, picture.getHeight() / 2);
SimpleIO.showMessage("Ready for orientation change?");
//looping through each pixel,
for (MyroPixel pixel: picture)
{
// flipping each pixel 180º by getting the y value of pixel, subtracting it from the image height, display new image
//int yMax = picture.getHeight();
int y = pixel.getY();
int y2 = picture.getHeight()-y-1;
// on the new image, sets the new pixel value to the calculated 180º orientation.
MyroPixel other = pic2.getPixel(pixel.getX(), y2);
other.setColor(pixel.getColor());
Color color = pixel.getColor();
MyroPixel pixel2 = new MyroPixel(pic2, pixel.getX(), y2);
pixel2.setColor(new Color (color.getRed(), color.getGreen(), color.getBlue()));
System.out.println("a");
}
System.out.println("done");
pic2.show();
picture.show();
}
}
|
7bf7b833fbb2a5968ccc4f9ed21f5764
|
{
"intermediate": 0.4122103452682495,
"beginner": 0.3193240761756897,
"expert": 0.26846563816070557
}
|
37,907
|
so how do i open this file in R: gene_effect.hdf5? and then be able to read the table normally. I got htis from chronos for CRISPR scren analysis
|
1c14a713e63683871118f6b391630b13
|
{
"intermediate": 0.7174213528633118,
"beginner": 0.09610798209905624,
"expert": 0.1864706128835678
}
|
37,908
|
how to check if a column in a dataframe in R contains duplicate values?
|
10b86f6f5a41d0640d8ab4f6a13c4026
|
{
"intermediate": 0.5818976163864136,
"beginner": 0.10626082867383957,
"expert": 0.31184154748916626
}
|
37,909
|
#organise dataframe from depmap
colnames(HumagneCDLogfoldChange_guide_data_intermediate) <- HumagneCDLogfoldChange_guide_data_intermediate[1,]
HumagneCDLogfoldChange_guide_data_intermediate <- HumagneCDLogfoldChange_guide_data_intermediate[-1,]
colnames(HumagneCDLogfoldChange_guide_data_intermediate)[1] <- "Gene"
HumagneCDLogfoldChange_guide_data_intermediate$source <- "DepMap"
#change first colname
colnames(result_df)[1] <- "Gene"
result_df$source <- "Metz"
DepMap_and_Metz_Humagne_combined <- inner_join(HumagneCDLogfoldChange_guide_data_intermediate, result_df, by = "Gene")
> DepMap_and_Metz_Humagne_combined <- inner_join(HumagneCDLogfoldChange_guide_data_intermediate, result_df, by = "Gene")
Error in `inner_join()`:
! Input columns in `x` must be unique.
✖ Problem with `SC.000067.CD02_CD.1_14_A`, `SC.000097.CD01_CD.1_14_A`, `SC.000147.CD01_CD.1_14_A`,
`SC.000183.CD01_CD.1_14_A`, `SC.000292.CD02_CD.1_14_A`, `SC.000404.CD01_CD.1_14_A`,
`SC.000502.CD01_CD.1_14_A`, `SC.000527.CD01_CD.1_14_A`, `SC.000583.CD01_CD.1_14_A`,
`SC.000696.CD01_CD.1_14_A`, `SC.000774.CD01_CD.1_14_A`, `SC.000900.CD01_CD.1_14_A`,
`SC.001509.CD01_CD.1_14_A`, `SC.001619.CD01_CD.1_14_A`, `SC.001975.CD01_CD.1_14_A`,
`SC.001975.CD01_CD.1_21_A`, `SC.001975.CD01_CD.1_14_B`, `SC.001975.CD01_CD.1_21_B`,
`SC.001975.CD01_CD.1_14_C`, and `SC.001975.CD01_CD.1_14_D`.
Run `rlang::last_trace()` to see where the error occurred.
i am sure the Gene column of the dataframes i want to combine are containing the same stuff
|
6dd9b13daaacf4c32e2f36d1d3cd09ba
|
{
"intermediate": 0.43807315826416016,
"beginner": 0.30920588970184326,
"expert": 0.2527209222316742
}
|
37,910
|
#organise dataframe from depmap
colnames(HumagneCDLogfoldChange_guide_data_intermediate) <- HumagneCDLogfoldChange_guide_data_intermediate[1,]
HumagneCDLogfoldChange_guide_data_intermediate <- HumagneCDLogfoldChange_guide_data_intermediate[-1,]
colnames(HumagneCDLogfoldChange_guide_data_intermediate)[1] <- "Gene"
HumagneCDLogfoldChange_guide_data_intermediate$source <- "DepMap"
#change first colname
colnames(result_df)[1] <- "Gene"
result_df$source <- "Metz"
DepMap_and_Metz_Humagne_combined <- inner_join(HumagneCDLogfoldChange_guide_data_intermediate, result_df, by = "Gene")
> DepMap_and_Metz_Humagne_combined <- inner_join(HumagneCDLogfoldChange_guide_data_intermediate, result_df, by = "Gene")
Error in `inner_join()`:
! Input columns in `x` must be unique.
✖ Problem with `SC.000067.CD02_CD.1_14_A`, `SC.000097.CD01_CD.1_14_A`, `SC.000147.CD01_CD.1_14_A`,
`SC.000183.CD01_CD.1_14_A`, `SC.000292.CD02_CD.1_14_A`, `SC.000404.CD01_CD.1_14_A`,
`SC.000502.CD01_CD.1_14_A`, `SC.000527.CD01_CD.1_14_A`, `SC.000583.CD01_CD.1_14_A`,
`SC.000696.CD01_CD.1_14_A`, `SC.000774.CD01_CD.1_14_A`, `SC.000900.CD01_CD.1_14_A`,
`SC.001509.CD01_CD.1_14_A`, `SC.001619.CD01_CD.1_14_A`, `SC.001975.CD01_CD.1_14_A`,
`SC.001975.CD01_CD.1_21_A`, `SC.001975.CD01_CD.1_14_B`, `SC.001975.CD01_CD.1_21_B`,
`SC.001975.CD01_CD.1_14_C`, and `SC.001975.CD01_CD.1_14_D`.
Run `rlang::last_trace()` to see where the error occurred.
I am sure the dataframes i want to combine contain the same stuff
|
f40a8dff9e80faea73c43467592971b4
|
{
"intermediate": 0.39319175481796265,
"beginner": 0.32826122641563416,
"expert": 0.278547078371048
}
|
37,911
|
what python library can I get the real year of today from?
|
e0335d01e927ec91a08db5d8f1f3fe3f
|
{
"intermediate": 0.6265777349472046,
"beginner": 0.11569415777921677,
"expert": 0.25772809982299805
}
|
37,912
|
Improve this list of skills
Moving
CSS
Serving
Python
Water damage restoration
Customer service
Project Management
Mold Remediation
HTML5
Food service
Expediting
Bussing
Microsoft Outlook
Food handling
Microsoft Excel
Microsoft Word
Adobe Photoshop
Demolition
JavaScript
POS
Dishwashing
Restoration
Windows
Restaurant experience
Microsoft Office
Project management
Fire Restoration
|
096362a90886801f3a1fb246f4024c82
|
{
"intermediate": 0.4867538511753082,
"beginner": 0.28861740231513977,
"expert": 0.2246287316083908
}
|
37,913
|
adapte le code de process_quiz au reste du projet qui maintenant gère plusieurs quizz et pas un seul : <?php
require_once 'databases/connexion.php';
function getQuizzes() {
$pdo = new PDO('sqlite:db.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM quizzes");
$stmt->execute();
$quizzes = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $quizzes;
}
?> questions.php : <?php
require_once 'databases/connexion.php';
use Classes\Form\Type\TextQuestion;
use Classes\Form\Type\CheckboxQuestion;
use Classes\Form\Type\RadioQuestion;
function getQuestions($quiz_id) {
$pdo = new PDO('sqlite:db.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM questions WHERE quiz_id = ?");
$stmt->execute([$quiz_id]);
$datas = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($datas);
$questions = [];
foreach ($datas as $data) {
$question = null;
$uuid = $data['uuid'];
$type = $data['type'];
$label = $data['label'];
$choices = json_decode($data['choices'], true);
$correct = is_array(json_decode($data['correct'], true)) ? json_decode($data['correct'], true) : $data['correct'];
switch ($type) {
case 'radio':
$question = new RadioQuestion($uuid, $type, $label, $choices, $correct);
break;
case 'checkbox':
$question = new CheckboxQuestion($uuid, $type, $label, $choices, $correct);
break;
case 'text':
$question = new TextQuestion($uuid, $type, $label, $correct);
break;
}
if ($question !== null) {
$questions[] = $question;
}
}
return $questions;
}
?> questions_quizz.php : <?php
session_start();
require_once 'questions.php';
require 'Classes/autoloader.php';
Autoloader::register();
use Classes\Form\Type\TextQuestion;
use Classes\Form\Type\CheckboxQuestion;
use Classes\Form\Type\RadioQuestion;
$quiz_id = $_GET['quiz_id'];
var_dump($quiz_id);
$questions = getQuestions($quiz_id);
echo "<form method='POST' action='process_quiz.php'>";
echo "<h1> Répondez aux questions</h1>";
echo '<hr />';
foreach ($questions as $question) {
echo $question->render().PHP_EOL;
}
echo '<button type="submit" class="btn btn-primary">Valider</button>';
echo "</form>";
?> process_quizz.php a adapter : <?php
session_start();
require_once 'questions.php';
require 'Classes/autoloader.php';
Autoloader::register();
$questions = getQuestions();
$score = 0;
$repBonne = [];
$repFausse = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
foreach ($_POST as $key => $userResponse) {
$questionId = str_replace('question-', '', $key);
$currentQuestion = null;
foreach ($questions as $question) {
if ($question->getUuid() === $questionId) {
$currentQuestion = $question;
break;
}
}
$currentQuestion->setUserResponse($userResponse);
if ($currentQuestion && $currentQuestion->isCorrect()) {
$repBonne[] = $currentQuestion->getUuid();
$score++;
} else {
$repFausse[] = $currentQuestion->getUuid();
}
}
$_SESSION['quiz_score'] = $score;
$_SESSION['repBonne'] = $repBonne;
$_SESSION['repFausse'] = $repFausse;
header("Location: correction.php");
exit();
} else {
header("Location: quizz.php");
exit();
}
?>
index.php : <?php
require_once 'quizz.php';
$quizzes = getQuizzes();
echo "<h1>Choose a Quiz</h1>";
foreach ($quizzes as $quiz) {
echo "<a href='questions_quizz.php?quiz_id={$quiz['id']}'>{$quiz['name']}</a><br>";
}
?>
|
1356f35dccbd0b63d4af2d73478bc906
|
{
"intermediate": 0.36112180352211,
"beginner": 0.5199130177497864,
"expert": 0.11896517127752304
}
|
37,914
|
Shared from StarGen:
Planet type/Distance/Mass (EM = Earth mass)/Radius (ER = Earth radius)
1. Rock/0.326 AU/0.139 EM/0.523 ER
2. Rock/0.530 AU/0.195 EM0.584 ER
3. Venusian/0.756 AU/0.769 EM/0.918 ER
4. Venusian/0.980 AU/0.232 EM/0.619 ER
5. Ice/1.595 AU/1.772 EM/1.204 ER
6. Ice/2.211 AU/1.120 EM/1.038 ER
7. Ice/2.751 AU/0.923 EM/0.974 ER
8. Jovian/3.734 AU/43.034 EM/5.554 ER
9. Jovian/7.631 AU/1049.410 EM/14.964 ER
10. Sub-Jovian/25.974 AU/2.398 EM/2.812 ER
11. Ice/38.962 AU/0.877 EM/1.276 ER
|
3f28af0aa06748eb693b6d25d0fd35dd
|
{
"intermediate": 0.3831087052822113,
"beginner": 0.33055150508880615,
"expert": 0.28633975982666016
}
|
37,915
|
Shared from StarGen:
~System 1
Planet type/Distance/Mass (EM = Earth mass)/Radius (ER = Earth radius)
1. Rock/0.326 AU/0.139 EM/0.523 ER
2. Rock/0.530 AU/0.195 EM0.584 ER
3. Venusian/0.756 AU/0.769 EM/0.918 ER
4. Venusian/0.980 AU/0.232 EM/0.619 ER
5. Ice/1.595 AU/1.772 EM/1.204 ER
6. Ice/2.211 AU/1.120 EM/1.038 ER
7. Ice/2.751 AU/0.923 EM/0.974 ER
8. Jovian/3.734 AU/43.034 EM/5.554 ER
9. Jovian/7.631 AU/1049.410 EM/14.964 ER
10. Sub-Jovian/25.974 AU/2.398 EM/2.812 ER
11. Ice/38.962 AU/0.877 EM/1.276 ER
~System 2
1. Rock/0.337 AU/0.023 EM/0.287
2. Rock/0.564 AU/0.419 EM/0.752
3. Terrestrial/1.042 AU/1.557 EM/1.155 ER
4. Sub-Jovian/1.745 AU/6.300 EM/2.976 ER
5. Martian/2.724 AU/0.230 EM/0.617 ER
6. Jovian/4.015 AU/61.190 EM/6.192 ER
7. Jovian/7.106 AU/126.096 EM/8.018 ER
8. Jovian/12.304 AU/416.693 EM/11.894 ER
9. Rock/24.283 AU/0.587 EM/1.120 ER
10. Sub-Jovian/35.087 AU/2.561 EM/2.940 ER
11. Rock/42.765 AU/0.149 EM/0.714 ER
12. Rock/48.745 AU/0.019 EM/0.364 ER
|
d95081b0013e2666be2ce5b66a2cb74f
|
{
"intermediate": 0.3804374635219574,
"beginner": 0.32894042134284973,
"expert": 0.2906220853328705
}
|
37,916
|
hi
|
921463dd77a608f1f7284a1afa80e784
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
37,917
|
i have yearly prices of a stock in a format of dict like this {'1998': 0.009134873424380829, '1999': 0.014240743516714135, '2000': 0.014681132953772335, '2001': 0.026271470865611317, '2002': 0.11075949367088607, '2003': 0.18123738634835238, '2004': 0.2680412356914327, '2005': 0.8272294900545006, '2006': 2.175056275197196, '2007': 2.981044202957758, '2008': 0.35767937620716794, '2009': 1.9497178040020524, '2010': 2.3646506910105236, '2011': 2.2229454841334415, '2012': 2.1555857957490927, '2013': 2.560876545109504, '2014': 1.0394015481897072, '2015': 1.1562541467121852, '2016': 1.8324644094932987, '2017': 3.1761751813332375, '2018': 2.5601486547549985, '2019': 3.3176231832710985, '2020': 3.007284220731579, '2021': 3.9836765369819163, '2022': 2.195751770095794, '2023': 3.07803277085188, '2024': 2.999592685960876}
and i have a list of dividents like that [{'year': '2023', 'dividend': 25.0}, {'year': '2022', 'dividend': 0.0}, {'year': '2021', 'dividend': 18.7}, {'year': '2020', 'dividend': 18.7}, {'year': '2019', 'dividend': 16.0}, {'year': '2018', 'dividend': 12.0}, {'year': '2017', 'dividend': 6.0}, {'year': '2016', 'dividend': 1.97}, {'year': '2015', 'dividend': 0.45}, {'year': '2014', 'dividend': 3.2}, {'year': '2013', 'dividend': 3.2}, {'year': '2012', 'dividend': 2.59}, {'year': '2011', 'dividend': 1.15}, {'year': '2010', 'dividend': 0.45}, {'year': '2009', 'dividend': 0.63}, {'year': '2008', 'dividend': 0.65}, {'year': '2007', 'dividend': 0.465}, {'year': '2006', 'dividend': 0.295}, {'year': '2005', 'dividend': 0.1895}, {'year': '2004', 'dividend': 0.144}, {'year': '2003', 'dividend': 0.116}, {'year': '2002', 'dividend': 0.057}, {'year': '2001', 'dividend': 0.04}, {'year': '2000', 'dividend': 0.0395}]
can you write a script that calculates the total return of a stock if dividends were reinvested? use python
|
86f147d39ab52700bc059f180dd781ec
|
{
"intermediate": 0.37736520171165466,
"beginner": 0.29855620861053467,
"expert": 0.32407861948013306
}
|
37,918
|
I will share 3 scripts consisting of a puzzle. In the PlayerInteraction script, instead of pressing E to call the Interact() function, i want to press E to call a OnGUI function in which I loop through my player inventory and list all of the name items containing the EldritchSymbol component. When the player click on one of the available item in the list, then it will call the Interact() function, and the player will place the item he clicked on under the current symbol transform. Also, I need anothe OnGUI function that list the name of the item in the symbol slot, and when the player clicks it, it returns back to the player inventory. I want the GUI to be center screen.
Script 1:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LovecraftianPuzzle : MonoBehaviour
{
public enum EldritchSymbols { Nyarlathotep, Azathoth, Cthulhu, ShubNiggurath, YogSothoth }
public Transform[] symbolSlots;
public GameObject[] eldritchSymbolPrefabs;
public GameObject portal;
public Animator portalAnimator;
public AudioSource gatewayAudio;
public AudioClip placeSymbolSound;
private GameObject player;
private AudioSource playerAudioSource;
private void Start()
{
player = GameObject.Find("Player");
playerAudioSource = player.GetComponent<AudioSource>();
}
private List<EldritchSymbols> correctOrder = new List<EldritchSymbols>()
{
EldritchSymbols.Nyarlathotep,
EldritchSymbols.Azathoth,
EldritchSymbols.Cthulhu,
EldritchSymbols.ShubNiggurath,
EldritchSymbols.YogSothoth
};
private List<EldritchSymbols> currentOrder = new List<EldritchSymbols>();
private Dictionary<EldritchSymbols, int> symbolToSlotIndex = new Dictionary<EldritchSymbols, int>()
{
{ EldritchSymbols.Nyarlathotep, 0 },
{ EldritchSymbols.Cthulhu, 2 },
{ EldritchSymbols.Azathoth, 1 },
{ EldritchSymbols.ShubNiggurath, 3 },
{ EldritchSymbols.YogSothoth, 4 }
};
public void PlaceSymbol(EldritchSymbols symbol)
{
int slotIndex = symbolToSlotIndex[symbol];
if (symbolSlots[slotIndex].childCount == 0)
{
GameObject symbolObject = Instantiate(
eldritchSymbolPrefabs[(int)symbol],
symbolSlots[slotIndex].position,
Quaternion.Euler(0, 24, -90), // Rotate 90 degrees around the Z axis
symbolSlots[slotIndex]);
if (!currentOrder.Contains(symbol)) // Check if the symbol is already in the list
{
currentOrder.Add(symbol); // Add it only if it's not present
}
playerAudioSource.PlayOneShot(placeSymbolSound);
}
CheckPuzzleSolved();
}
private void CheckPuzzleSolved()
{
if (currentOrder.Count == correctOrder.Count)
{
bool isSolved = true;
for (int i = 0; i < correctOrder.Count; i++)
{
if (currentOrder[i] != correctOrder[i])
{
isSolved = false;
break;
}
}
if (isSolved)
{
StartCoroutine(GatewayAnimation());
}
}
}
public IEnumerator GatewayAnimation()
{
portalAnimator.SetBool("OpenGateway", true);
MeshCollider gatewayMeshFilter = portalAnimator.gameObject.GetComponent<MeshCollider>();
gatewayAudio.Play();
gatewayMeshFilter.enabled = false;
yield return new WaitForSeconds(1f);
portalAnimator.SetBool("OpenGateway", false);
}
public void ResetPuzzle()
{
currentOrder.Clear();
foreach (Transform slot in symbolSlots)
{
if (slot.childCount > 0)
{
Destroy(slot.GetChild(0).gameObject);
}
}
}
public void RemoveSymbol(EldritchSymbols symbol)
{
// Find the index of the symbol in the currentOrder list
int index = currentOrder.FindIndex(s => s == symbol);
// Check that the index is valid
if (index >= 0 && index < currentOrder.Count)
{
// Find the corresponding symbol in the symbolSlots array
for (int i = 0; i < symbolSlots.Length; i++)
{
if (symbolSlots[i].childCount > 0)
{
GameObject symbolObject = symbolSlots[i].GetChild(0).gameObject;
EldritchSymbols symbolInSlot = symbolObject.GetComponent<EldritchSymbol>().symbolType;
if (symbolInSlot == symbol)
{
// Remove the symbol from currentOrder and destroy the symbol object
currentOrder.RemoveAt(index);
playerAudioSource.PlayOneShot(placeSymbolSound);
Destroy(symbolObject);
break;
}
}
}
}
}
}
Script 2:
using UnityEngine;
public class EldritchSymbol : MonoBehaviour
{
public LovecraftianPuzzle.EldritchSymbols symbolType;
}
Script 3:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
public float interactionDistance = 2f;
public LayerMask interactionMask;
private GameObject currentInteractable;
private GameObject lastPlacedSymbol;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Interact();
}
}
void FixedUpdate()
{
CheckForInteractions();
}
void CheckForInteractions()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, transform.forward, out hitInfo, interactionDistance, interactionMask))
{
if (hitInfo.transform.gameObject != currentInteractable)
{
currentInteractable = hitInfo.transform.gameObject;
Debug.Log("New Interactable: " + currentInteractable.name);
// You can add visual feedback or highlighting for the interactable object here.
}
}
/*else
{
if (currentInteractable != null)
{
currentInteractable = null;
Debug.Log("No interactable object in range.");
// You can remove visual feedback or highlighting for the interactable object here.
}
}*/
}
void Interact()
{
if (currentInteractable != null)
{
EldritchSymbol symbol = currentInteractable.GetComponent<EldritchSymbol>();
if (symbol != null)
{
LovecraftianPuzzle puzzle = FindObjectOfType<LovecraftianPuzzle>();
if (puzzle != null)
{
if (lastPlacedSymbol == currentInteractable)
{
puzzle.RemoveSymbol(symbol.symbolType);
lastPlacedSymbol = null; // Reset the last placed symbol
}
else
{
puzzle.PlaceSymbol(symbol.symbolType);
lastPlacedSymbol = currentInteractable; // Store the placed symbol
}
}
}
}
}
}
Here's an exemple on how I loop for Item name in my Inventory:
for (int t = 0; t < InvManager.Items; t++) //Starting a loop in the slots of the inventory:
{
if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot.
{
Item ItemScript = InvManager.Slots[t].Item.GetComponent(); //Getting the item script from the items inside the bag.
if (ItemScript.Name == "ExempleName"){//Do stuff}
|
fee80febe888165a3ebc061a85faf22c
|
{
"intermediate": 0.32544755935668945,
"beginner": 0.5577275156974792,
"expert": 0.11682499200105667
}
|
37,919
|
I will share 3 scripts consisting of a puzzle. In the PlayerInteraction script, instead of pressing E to call the Interact() function, i want to press E to call a UI function in which I loop through my player inventory and list all of the name items containing the EldritchSymbol component. When the player click on one of the available item in the list, then it will call the Interact() function, and the player will place the item he clicked on under the current symbol transform. Also, I need anothe OnGUI function that list the name of the item in the symbol slot, and when the player clicks it, it returns back to the player inventory. I want the GUI to be center screen.
Je vais partager 3 scripts pour un puzzle dans Unity et ma propre méthode pour vérifier l'inventaire du joueur et ajouté un item dans l'inventaire. Dans ce puzzle, j'aimerais pouvoir modifier la manière que le joueur place un symbol. Dans un GUI centré dans l'écran, en vérifiant si un des 5 items comprenant la composante EldritchSymbol est dans l'inventaire, je veux que le joueur puisse lui-meme choisir l'item à placer dans le symbolSlot transform. J'aimerais aussi modifier la manière que le joeur Remove un symbol. Je veux qu'un nouveau GUI toujours centré montre le symbol actuellement placé, et qu'en cliquant sur le bouton, le joueur enlève le symbol, laissant le symbol transform vierge, puis l'item retourne dans l'inventaire du joueur. Donc, pour résumer. Changer la manière de placer et d'enlever un symbole en utilisant des GUI centré dans l'écran, pour placer un symbol il faut chercher dans l'inventaire du joueur si un item possède un symbol, puis placé cet item sur le symbol transform en pleine interaction. Pour enlever un symbole, le GUI change et montre le symbol actuellement placé sur le symbol transform, le joueur peut retirer le symbol du symbol transform et l'item retourne dans l'inventaire du joueur.
Script 1:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LovecraftianPuzzle : MonoBehaviour
{
public enum EldritchSymbols { Nyarlathotep, Azathoth, Cthulhu, ShubNiggurath, YogSothoth }
public Transform[] symbolSlots;
public GameObject[] eldritchSymbolPrefabs;
public GameObject portal;
public Animator portalAnimator;
public AudioSource gatewayAudio;
public AudioClip placeSymbolSound;
private GameObject player;
private AudioSource playerAudioSource;
private void Start()
{
player = GameObject.Find("Player");
playerAudioSource = player.GetComponent<AudioSource>();
}
private List<EldritchSymbols> correctOrder = new List<EldritchSymbols>()
{
EldritchSymbols.Nyarlathotep,
EldritchSymbols.Azathoth,
EldritchSymbols.Cthulhu,
EldritchSymbols.ShubNiggurath,
EldritchSymbols.YogSothoth
};
private List<EldritchSymbols> currentOrder = new List<EldritchSymbols>();
private Dictionary<EldritchSymbols, int> symbolToSlotIndex = new Dictionary<EldritchSymbols, int>()
{
{ EldritchSymbols.Nyarlathotep, 0 },
{ EldritchSymbols.Cthulhu, 2 },
{ EldritchSymbols.Azathoth, 1 },
{ EldritchSymbols.ShubNiggurath, 3 },
{ EldritchSymbols.YogSothoth, 4 }
};
public void PlaceSymbol(EldritchSymbols symbol)
{
int slotIndex = symbolToSlotIndex[symbol];
if (symbolSlots[slotIndex].childCount == 0)
{
GameObject symbolObject = Instantiate(
eldritchSymbolPrefabs[(int)symbol],
symbolSlots[slotIndex].position,
Quaternion.Euler(0, 24, -90), // Rotate 90 degrees around the Z axis
symbolSlots[slotIndex]);
if (!currentOrder.Contains(symbol)) // Check if the symbol is already in the list
{
currentOrder.Add(symbol); // Add it only if it's not present
}
playerAudioSource.PlayOneShot(placeSymbolSound);
}
CheckPuzzleSolved();
}
private void CheckPuzzleSolved()
{
if (currentOrder.Count == correctOrder.Count)
{
bool isSolved = true;
for (int i = 0; i < correctOrder.Count; i++)
{
if (currentOrder[i] != correctOrder[i])
{
isSolved = false;
break;
}
}
if (isSolved)
{
StartCoroutine(GatewayAnimation());
}
}
}
public IEnumerator GatewayAnimation()
{
portalAnimator.SetBool("OpenGateway", true);
MeshCollider gatewayMeshFilter = portalAnimator.gameObject.GetComponent<MeshCollider>();
gatewayAudio.Play();
gatewayMeshFilter.enabled = false;
yield return new WaitForSeconds(1f);
portalAnimator.SetBool("OpenGateway", false);
}
public void ResetPuzzle()
{
currentOrder.Clear();
foreach (Transform slot in symbolSlots)
{
if (slot.childCount > 0)
{
Destroy(slot.GetChild(0).gameObject);
}
}
}
public void RemoveSymbol(EldritchSymbols symbol)
{
// Find the index of the symbol in the currentOrder list
int index = currentOrder.FindIndex(s => s == symbol);
// Check that the index is valid
if (index >= 0 && index < currentOrder.Count)
{
// Find the corresponding symbol in the symbolSlots array
for (int i = 0; i < symbolSlots.Length; i++)
{
if (symbolSlots[i].childCount > 0)
{
GameObject symbolObject = symbolSlots[i].GetChild(0).gameObject;
EldritchSymbols symbolInSlot = symbolObject.GetComponent<EldritchSymbol>().symbolType;
if (symbolInSlot == symbol)
{
// Remove the symbol from currentOrder and destroy the symbol object
currentOrder.RemoveAt(index);
playerAudioSource.PlayOneShot(placeSymbolSound);
Destroy(symbolObject);
break;
}
}
}
}
}
}
Script 2:
using UnityEngine;
public class EldritchSymbol : MonoBehaviour
{
public LovecraftianPuzzle.EldritchSymbols symbolType;
}
Script 3:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
public float interactionDistance = 2f;
public LayerMask interactionMask;
private GameObject currentInteractable;
private GameObject lastPlacedSymbol;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Interact();
}
}
void FixedUpdate()
{
CheckForInteractions();
}
void CheckForInteractions()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, transform.forward, out hitInfo, interactionDistance, interactionMask))
{
if (hitInfo.transform.gameObject != currentInteractable)
{
currentInteractable = hitInfo.transform.gameObject;
Debug.Log("New Interactable: " + currentInteractable.name);
// You can add visual feedback or highlighting for the interactable object here.
}
}
/*else
{
if (currentInteractable != null)
{
currentInteractable = null;
Debug.Log("No interactable object in range.");
// You can remove visual feedback or highlighting for the interactable object here.
}
}*/
}
void Interact()
{
if (currentInteractable != null)
{
EldritchSymbol symbol = currentInteractable.GetComponent<EldritchSymbol>();
if (symbol != null)
{
LovecraftianPuzzle puzzle = FindObjectOfType<LovecraftianPuzzle>();
if (puzzle != null)
{
if (lastPlacedSymbol == currentInteractable)
{
puzzle.RemoveSymbol(symbol.symbolType);
lastPlacedSymbol = null; // Reset the last placed symbol
}
else
{
puzzle.PlaceSymbol(symbol.symbolType);
lastPlacedSymbol = currentInteractable; // Store the placed symbol
}
}
}
}
}
}
Here's an exemple on how I loop for Item name in my Inventory:
for (int t = 0; t < InvManager.Items; t++) //Starting a loop in the slots of the inventory:
{
if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot.
{
Item ItemScript = InvManager.Slots[t].Item.GetComponent(); //Getting the item script from the items inside the bag.
if (ItemScript.Name == "The Shadow People"){//Do stuff}
Here's an exemple on how I add an item in my inventory:
if (InvManager.PickupType == InventoryManager.PickupTypes.Keyboard) //Check if the player is using the keyboard to pick up items.
{
if (Input.GetKey(InvManager.ActionKey)) //Checking if the player pressed the key used to pick up items.
{
//if(other == InvManager.Player.GetComponent<Collider>())
//{
if (ItemType == 0)
{
PlayerPrefs.SetString(id, "true");
_itemCollected = true;
InvManager.AddItem(MyTransform); //Add this item to the bag
}
}
}
Additionnal Note : Items having the EldritchSymbol are books. They are having different names and each of them possess one of the symbol.
"The Unknown and The Deep Void" (Yog Sothoth)
"Mark Of The Old Gods" (Azathoth)
"The House Of R'lyeh" (Cthulhu)
"The Shadow People" (Shub Niggurath)
"Invocations of The Cosmic Horror" (Nyalarthotep)
Même si le joueur peut placer n'importe quel livre n'importe où, chaque livre doit être placé sur le bon symboleTransformation ET dans le bon ordre.
Enfin, c'est ce que j'aimerais accomplir.
|
063d32b247e1b9dc9a079c09748b4e7f
|
{
"intermediate": 0.3909139335155487,
"beginner": 0.3853933811187744,
"expert": 0.2236926406621933
}
|
37,920
|
I will share 3 scripts consisting of a puzzle. In the PlayerInteraction script, instead of pressing E to call the Interact() function, i want to press E to call a UI function in which I loop through my player inventory and list all of the name items containing the EldritchSymbol component. When the player click on one of the available item in the list, then it will call the Interact() function, and the player will place the item he clicked on under the current symbol transform. Also, I need anothe OnGUI function that list the name of the item in the symbol slot, and when the player clicks it, it returns back to the player inventory. I want the GUI to be center screen.
Je vais partager 3 scripts pour un puzzle dans Unity et ma propre méthode pour vérifier l'inventaire du joueur et ajouté un item dans l'inventaire. Dans ce puzzle, j'aimerais pouvoir modifier la manière que le joueur place un symbol. Dans un GUI centré dans l'écran, en vérifiant si un des 5 items comprenant la composante EldritchSymbol est dans l'inventaire, je veux que le joueur puisse lui-meme choisir l'item à placer dans le symbolSlot transform. J'aimerais aussi modifier la manière que le joeur Remove un symbol. Je veux qu'un nouveau GUI toujours centré montre le symbol actuellement placé, et qu'en cliquant sur le bouton, le joueur enlève le symbol, laissant le symbol transform vierge, puis l'item retourne dans l'inventaire du joueur. Donc, pour résumer. Changer la manière de placer et d'enlever un symbole en utilisant des GUI centré dans l'écran, pour placer un symbol il faut chercher dans l'inventaire du joueur si un item possède un symbol, puis placé cet item sur le symbol transform en pleine interaction. Pour enlever un symbole, le GUI change et montre le symbol actuellement placé sur le symbol transform, le joueur peut retirer le symbol du symbol transform et l'item retourne dans l'inventaire du joueur.
Script 1:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LovecraftianPuzzle : MonoBehaviour
{
public enum EldritchSymbols { Nyarlathotep, Azathoth, Cthulhu, ShubNiggurath, YogSothoth }
public Transform[] symbolSlots;
public GameObject[] eldritchSymbolPrefabs;
public GameObject portal;
public Animator portalAnimator;
public AudioSource gatewayAudio;
public AudioClip placeSymbolSound;
private GameObject player;
private AudioSource playerAudioSource;
private void Start()
{
player = GameObject.Find("Player");
playerAudioSource = player.GetComponent<AudioSource>();
}
private List<EldritchSymbols> correctOrder = new List<EldritchSymbols>()
{
EldritchSymbols.Nyarlathotep,
EldritchSymbols.Azathoth,
EldritchSymbols.Cthulhu,
EldritchSymbols.ShubNiggurath,
EldritchSymbols.YogSothoth
};
private List<EldritchSymbols> currentOrder = new List<EldritchSymbols>();
private Dictionary<EldritchSymbols, int> symbolToSlotIndex = new Dictionary<EldritchSymbols, int>()
{
{ EldritchSymbols.Nyarlathotep, 0 },
{ EldritchSymbols.Cthulhu, 2 },
{ EldritchSymbols.Azathoth, 1 },
{ EldritchSymbols.ShubNiggurath, 3 },
{ EldritchSymbols.YogSothoth, 4 }
};
public void PlaceSymbol(EldritchSymbols symbol)
{
int slotIndex = symbolToSlotIndex[symbol];
if (symbolSlots[slotIndex].childCount == 0)
{
GameObject symbolObject = Instantiate(
eldritchSymbolPrefabs[(int)symbol],
symbolSlots[slotIndex].position,
Quaternion.Euler(0, 24, -90), // Rotate 90 degrees around the Z axis
symbolSlots[slotIndex]);
if (!currentOrder.Contains(symbol)) // Check if the symbol is already in the list
{
currentOrder.Add(symbol); // Add it only if it's not present
}
playerAudioSource.PlayOneShot(placeSymbolSound);
}
CheckPuzzleSolved();
}
private void CheckPuzzleSolved()
{
if (currentOrder.Count == correctOrder.Count)
{
bool isSolved = true;
for (int i = 0; i < correctOrder.Count; i++)
{
if (currentOrder[i] != correctOrder[i])
{
isSolved = false;
break;
}
}
if (isSolved)
{
StartCoroutine(GatewayAnimation());
}
}
}
public IEnumerator GatewayAnimation()
{
portalAnimator.SetBool("OpenGateway", true);
MeshCollider gatewayMeshFilter = portalAnimator.gameObject.GetComponent<MeshCollider>();
gatewayAudio.Play();
gatewayMeshFilter.enabled = false;
yield return new WaitForSeconds(1f);
portalAnimator.SetBool("OpenGateway", false);
}
public void ResetPuzzle()
{
currentOrder.Clear();
foreach (Transform slot in symbolSlots)
{
if (slot.childCount > 0)
{
Destroy(slot.GetChild(0).gameObject);
}
}
}
public void RemoveSymbol(EldritchSymbols symbol)
{
// Find the index of the symbol in the currentOrder list
int index = currentOrder.FindIndex(s => s == symbol);
// Check that the index is valid
if (index >= 0 && index < currentOrder.Count)
{
// Find the corresponding symbol in the symbolSlots array
for (int i = 0; i < symbolSlots.Length; i++)
{
if (symbolSlots[i].childCount > 0)
{
GameObject symbolObject = symbolSlots[i].GetChild(0).gameObject;
EldritchSymbols symbolInSlot = symbolObject.GetComponent<EldritchSymbol>().symbolType;
if (symbolInSlot == symbol)
{
// Remove the symbol from currentOrder and destroy the symbol object
currentOrder.RemoveAt(index);
playerAudioSource.PlayOneShot(placeSymbolSound);
Destroy(symbolObject);
break;
}
}
}
}
}
}
Script 2:
using UnityEngine;
public class EldritchSymbol : MonoBehaviour
{
public LovecraftianPuzzle.EldritchSymbols symbolType;
}
Script 3:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
public float interactionDistance = 2f;
public LayerMask interactionMask;
private GameObject currentInteractable;
private GameObject lastPlacedSymbol;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Interact();
}
}
void FixedUpdate()
{
CheckForInteractions();
}
void CheckForInteractions()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, transform.forward, out hitInfo, interactionDistance, interactionMask))
{
if (hitInfo.transform.gameObject != currentInteractable)
{
currentInteractable = hitInfo.transform.gameObject;
Debug.Log("New Interactable: " + currentInteractable.name);
// You can add visual feedback or highlighting for the interactable object here.
}
}
/*else
{
if (currentInteractable != null)
{
currentInteractable = null;
Debug.Log("No interactable object in range.");
// You can remove visual feedback or highlighting for the interactable object here.
}
}*/
}
void Interact()
{
if (currentInteractable != null)
{
EldritchSymbol symbol = currentInteractable.GetComponent<EldritchSymbol>();
if (symbol != null)
{
LovecraftianPuzzle puzzle = FindObjectOfType<LovecraftianPuzzle>();
if (puzzle != null)
{
if (lastPlacedSymbol == currentInteractable)
{
puzzle.RemoveSymbol(symbol.symbolType);
lastPlacedSymbol = null; // Reset the last placed symbol
}
else
{
puzzle.PlaceSymbol(symbol.symbolType);
lastPlacedSymbol = currentInteractable; // Store the placed symbol
}
}
}
}
}
}
Here's an exemple on how I loop for Item name in my Inventory:
for (int t = 0; t < InvManager.Items; t++) //Starting a loop in the slots of the inventory:
{
if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot.
{
Item ItemScript = InvManager.Slots[t].Item.GetComponent(); //Getting the item script from the items inside the bag.
if (ItemScript.Name == "The Shadow People"){//Do stuff}
Here's an exemple on how I add an item in my inventory:
if (InvManager.PickupType == InventoryManager.PickupTypes.Keyboard) //Check if the player is using the keyboard to pick up items.
{
if (Input.GetKey(InvManager.ActionKey)) //Checking if the player pressed the key used to pick up items.
{
//if(other == InvManager.Player.GetComponent<Collider>())
//{
if (ItemType == 0)
{
PlayerPrefs.SetString(id, "true");
_itemCollected = true;
InvManager.AddItem(MyTransform); //Add this item to the bag
}
}
}
Additionnal Note : Items having the EldritchSymbol are books. They are having different names and each of them possess one of the symbol.
"The Unknown and The Deep Void" (Yog Sothoth)
"Mark Of The Old Gods" (Azathoth)
"The House Of R'lyeh" (Cthulhu)
"The Shadow People" (Shub Niggurath)
"Invocations of The Cosmic Horror" (Nyalarthotep)
Même si le joueur peut placer n'importe quel livre n'importe où, chaque livre doit être placé sur le bon symboleTransformation ET dans le bon ordre.
Enfin, c'est ce que j'aimerais accomplir.
|
1adbc8b8f3cf182192f56dbdfc370566
|
{
"intermediate": 0.3909139335155487,
"beginner": 0.3853933811187744,
"expert": 0.2236926406621933
}
|
37,921
|
I have the following code:
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) {
}
});
loadRewardedAds();
mTextView=findViewById(R.id.Coins);
mButton=findViewById(R.id.RewardedbtnAds);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showRewardAds();
}
});
private void showRewardAds() {
if (mRewardedAd!=null) {
mRewardedAd.show(MainActivity.this, new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
int amount = rewardItem.getAmount();
String type=rewardItem.getType();
mTextView.setText("The content is unlocked.")
}
});
} else {
Toast.makeText(MainActivity.this,"Reward ads is not ready yet", Toast.LENGTH_SHORT).show();
}
}
private void loadRewardedAds() {
AdRequest adRequest=new AdRequest.Builder().build();
RewardedAd.load(this, REWARD_AD_UNIT_ID, adRequest, new RewardedAdLoadCallback() {
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
mRewardedAd=null;
}
@Override
public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
super.onAdLoaded(rewardedAd);
mRewardedAd=rewardedAd;
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdClicked() {
super.onAdClicked();
}
@Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
}
@Override
public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
}
@Override
public void onAdImpression() {
super.onAdImpression();
}
@Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
}
});
}
});
}
final boolean[] volt = {false};
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
Button bannerbutton = findViewById(R.id.BannerbtnAds);
bannerbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!volt[0]) {
mAdView.loadAd(adRequest);
mAdView.setVisibility(View.VISIBLE);
volt[0] = true;
} else {
mAdView.setVisibility(View.GONE);
volt[0] = false;
}
}
});
loadInterstitialAd(); // Call this method to load the ad
Button button = findViewById(R.id.IntbtnAds);
button.setOnClickListener(view -> {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn’t ready yet.");
loadInterstitialAd(); // Try to load again if it wasn’t ready when the button was clicked
}
});
}
private void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
setInterstitialAdCallbacks();
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
}
private void setInterstitialAdCallbacks() {
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
@Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
loadInterstitialAd(); // Load a new ad when the current one is closed
}
@Override
public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
mInterstitialAd = null;
}
// Implement other callbacks if needed
});
}
public static final String REWARD_AD_UNIT_ID="ca-app-pub-3940256099942544/5224354917";
public static final String TAG="Mainactivity";
private RewardedAd mRewardedAd;
private Button mButton;
private TextView mTextView;
}
Why doesn't it work? It says "MyApplication/app/src/main/java/com/example/myapplication/MainActivity.java:56: error: illegal start of expression
private void showRewardAds() {
^"
|
fc388203ea7c1bd75005c0896d510eb5
|
{
"intermediate": 0.2806747555732727,
"beginner": 0.4883407652378082,
"expert": 0.23098444938659668
}
|
37,922
|
get 1 st element in dict
|
f664293e92d49410dde30a9c987a90b5
|
{
"intermediate": 0.37486040592193604,
"beginner": 0.3209993839263916,
"expert": 0.30414023995399475
}
|
37,923
|
Warning: Uncaught PDOException: SQLSTATE[HY000]: General error: 5 database is locked in C:\Users\alexa\Desktop\Quizz_PHP\process_quiz.php:62 Stack trace: #0 C:\Users\alexa\Desktop\Quizz_PHP\process_quiz.php(62): PDOStatement->execute(Array) #1 C:\Users\alexa\Desktop\Quizz_PHP\process_quiz.php(40): storeUserQuizCompletion('test', '1', 1) #2 {main} thrown in C:\Users\alexa\Desktop\Quizz_PHP\process_quiz.php on line 62
Fatal error: Maximum execution time of 30 seconds exceeded in C:\Users\alexa\Desktop\Quizz_PHP\process_quiz.php on line 40
|
f71d876c4786ff1c109be8a78e4874db
|
{
"intermediate": 0.2929888367652893,
"beginner": 0.47615984082221985,
"expert": 0.23085132241249084
}
|
37,924
|
Hello
|
1f3d50fb344cc88fa2113a56a8b80961
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
37,925
|
如何解决:
F:\react-blog-develop>yarn dev
yarn run v1.22.21
$ next dev
- info Loaded env from F:\react-blog-develop\.env
- ready started server on [::]:3000, url: http://localhost:3000
- event compiled client and server successfully in 157 ms (20 modules)
- wait compiling...
- event compiled client and server successfully in 140 ms (20 modules)
- info Loaded env from F:\react-blog-develop\.env
- info Loaded env from F:\react-blog-develop\.env
- wait compiling /page (client and server)...
- event compiled client and server successfully in 837 ms (678 modules)
prisma:query SELECT "public"."Posts"."id", "public"."Posts"."title", "public"."Posts"."published", "public"."Posts"."authorId", "public"."Posts"."createdAt" FROM "public"."Posts" WHERE 1=1 ORDER BY "public"."Posts"."createdAt" DESC OFFSET $1
{ status: 'fulfilled', value: [] }
- wait compiling /api/auth/[...nextauth] (client and server)...
- event compiled client and server successfully in 1508 ms (853 modules)
- wait compiling...
- event compiled successfully in 355 ms (383 modules)
prisma:query SELECT "public"."Posts"."id", "public"."Posts"."title", "public"."Posts"."published", "public"."Posts"."authorId", "public"."Posts"."createdAt" FROM "public"."Posts" WHERE 1=1 ORDER BY "public"."Posts"."createdAt" DESC OFFSET $1
{ status: 'fulfilled', value: [] }
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error getaddrinfo ENOTFOUND github.com {
error: Error: getaddrinfo ENOTFOUND github.com
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26) {
name: 'OAuthCallbackError',
code: 'ENOTFOUND'
},
providerId: 'github',
message: 'getaddrinfo ENOTFOUND github.com'
}
prisma:query SELECT "public"."Posts"."id", "public"."Posts"."title", "public"."Posts"."published", "public"."Posts"."authorId", "public"."Posts"."createdAt" FROM "public"."Posts" WHERE 1=1 ORDER BY "public"."Posts"."createdAt" DESC OFFSET $1
{ status: 'fulfilled', value: [] }
- error TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is already closed
prisma:query SELECT "public"."Posts"."id", "public"."Posts"."title", "public"."Posts"."published", "public"."Posts"."authorId", "public"."Posts"."createdAt" FROM "public"."Posts" WHERE 1=1 ORDER BY "public"."Posts"."createdAt" DESC OFFSET $1
{ status: 'fulfilled', value: [] }
prisma:query SELECT "public"."Posts"."id", "public"."Posts"."title", "public"."Posts"."published", "public"."Posts"."authorId", "public"."Posts"."createdAt" FROM "public"."Posts" WHERE 1=1 ORDER BY "public"."Posts"."createdAt" DESC OFFSET $1
- error TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is already closed
{ status: 'fulfilled', value: [] }
- error TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is already closed
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error outgoing request timed out after 3500ms {
error: RPError: outgoing request timed out after 3500ms
at F:\react-blog-develop\node_modules\openid-client\lib\helpers\request.js:137:13
at async Client.grant (F:\react-blog-develop\node_modules\openid-client\lib\client.js:1316:22)
at async Client.oauthCallback (F:\react-blog-develop\node_modules\openid-client\lib\client.js:603:24)
at async oAuthCallback (F:\react-blog-develop\node_modules\next-auth\core\lib\oauth\callback.js:111:16)
at async Object.callback (F:\react-blog-develop\node_modules\next-auth\core\routes\callback.js:52:11)
at async AuthHandler (F:\react-blog-develop\node_modules\next-auth\core\index.js:208:28)
at async NextAuthApiHandler (F:\react-blog-develop\node_modules\next-auth\next\index.js:22:19)
at async NextAuth._args$ (F:\react-blog-develop\node_modules\next-auth\next\index.js:107:14) {
name: 'OAuthCallbackError',
code: undefined
},
providerId: 'github',
message: 'outgoing request timed out after 3500ms'
}
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error outgoing request timed out after 3500ms {
error: RPError: outgoing request timed out after 3500ms
at F:\react-blog-develop\node_modules\openid-client\lib\helpers\request.js:137:13
at async Client.grant (F:\react-blog-develop\node_modules\openid-client\lib\client.js:1316:22)
at async Client.oauthCallback (F:\react-blog-develop\node_modules\openid-client\lib\client.js:603:24)
at async oAuthCallback (F:\react-blog-develop\node_modules\next-auth\core\lib\oauth\callback.js:111:16)
at async Object.callback (F:\react-blog-develop\node_modules\next-auth\core\routes\callback.js:52:11)
at async AuthHandler (F:\react-blog-develop\node_modules\next-auth\core\index.js:208:28)
at async NextAuthApiHandler (F:\react-blog-develop\node_modules\next-auth\next\index.js:22:19)
at async NextAuth._args$ (F:\react-blog-develop\node_modules\next-auth\next\index.js:107:14) {
name: 'OAuthCallbackError',
code: undefined
},
providerId: 'github',
message: 'outgoing request timed out after 3500ms'
}
|
871c74364bb20aeb27a1a6001b4d3983
|
{
"intermediate": 0.3325847089290619,
"beginner": 0.3831183910369873,
"expert": 0.2842968702316284
}
|
37,926
|
i have a dict:
{'SBER': {'1998': 1.0, '1999': 1.7098080356961523, '2000': 1.8009463048313752, '2001': 3.0319544425816742, '2002': 13.22315792575705, '2003': 16.575909810859496, '2004': 32.3871606099827, '2005': 74.2175418811371, '2006': 167.17734204003443, '2007': 285.03723829947864, '2008': 56.90324912674235, '2009': 165.1303379492334, '2010': 223.7440496961296, '2011': 201.47851185590764, '2012': 211.56940245669125, '2013': 227.8729952794189, '2014': 110.09573826880218, '2015': 119.86847493564652, '2016': 194.11436997699113, '2017': 306.51266557101764, '2018': 249.99558263197446, '2019': 329.6941316094078, '2020': 319.27642285146084, '2021': 446.6608648391273, '2022': 234.90013571867368, '2023': 345.1888781192195, '2024': 335.6155065543285}, 'SBERP': {'1998': 1.0, '1999': 1.5589426207817858, '2000': 1.7619877188626227, '2001': 3.3147207291626293, '2002': 14.202321460821128, '2003': 23.73961160242624, '2004': 35.78025575367798, '2005': 111.30322746463274, '2006': 294.16498829905584, '2007': 405.7398387738823, '2008': 51.84689394741818, '2009': 285.7421878446653, '2010': 348.64341958785786, '2011': 333.2689366451964, '2012': 335.7511762654028, '2013': 413.91656550379287, '2014': 178.35566447553845, '2015': 199.57129613641126, '2016': 321.5922609356433, '2017': 575.4186911602479, '2018': 496.23628759571505, '2019': 691.250094277494, '2020': 677.6352797575382, '2021': 954.6047208687057, '2022': 526.1659640612475, '2023': 804.1673083352877, '2024': 783.6740398653316}, 'ROSN': {'2006': 1.0, '2007': 0.9908789752546991, '2008': 0.42474391675932693, '2009': 0.9067846314531538, '2010': 0.7507705279095773, '2011': 0.8400829326717478, '2012': 0.9349289224971801, '2013': 0.8777834863258551, '2014': 0.5994448008821512, '2015': 0.5338636498744237, '2016': 0.7389050237901296, '2017': 0.7136534519728965, '2018': 0.9698850098127899, '2019': 1.0891143701351407, '2020': 0.9667773127939631, '2021': 1.3299698694054494, '2022': 1.0886659768247156, '2023': 1.3645692783197043, '2024': 1.3796381772800244}, 'LKOH': {'1997': 0.9999999999999999, '1998': 0.2576516480025177, '1999': 0.438566592242953, '2000': 0.4981011696485425, '2001': 0.6112350611111543, '2002': 0.9421812953340476, '2003': 1.2446565177663897, '2004': 1.8513297481895097, '2005': 3.477039371019298, '2006': 5.487832760174205, '2007': 5.388875785928995, '2008': 2.045584832609243, '2009': 3.92350983005807, '2010': 3.8237315093685726, '2011': 4.04499852397549, '2012': 4.7842257257969925, '2013': 4.916290032649284, '2014': 3.8244930026297452, '2015': 3.420791089331322, '2016': 4.688613602948519, '2017': 5.6318327759744875, '2018': 7.791588317053861, '2019': 10.559947853218489, '2020': 7.915932878586572, '2021': 11.518187961253807, '2022': 11.638483513352465, '2023': 13.658921857242262, '2024': 12.660149134527131}, 'NVTK': {'2004': 1.0293429190061065, '2005': 2.1645823889600853, '2006': 6.233465414815659, '2007': 6.247756085843829, '2008': 2.108594954843809, '2009': 5.685112332097802, '2010': 8.902769164138679, '2011': 14.452147675070501, '2012': 11.62954062438021, '2013': 13.203219601668785, '2014': 10.312890485259976, '2015': 10.738129643833336, '2016': 13.328653671111633, '2017': 13.21885685339926, '2018': 20.745306071193404, '2019': 24.373014027755858, '2020': 19.984794152473683, '2021': 28.925292792668163, '2022': 24.617028246906905, '2023': 25.288468463902316, '2024': 24.30564018792907}, 'SIBN': {'1999': 1.0, '2000': 0.9362852505086394, '2001': 3.013128532524529, '2002': 9.340147310413311, '2003': 11.970704951807093, '2004': 14.484508732112571, '2005': 21.306326059526636, '2006': 25.724608132765685, '2007': 35.06517843181167, '2008': 14.465236692994212, '2009': 39.03570680852214, '2010': 30.28109281986317, '2011': 36.35472808430965, '2012': 38.248468304544836, '2013': 40.447773268315075, '2014': 30.381428170643115, '2015': 22.447729050809677, '2016': 31.636993269346217, '2017': 47.614064980642446, '2018': 64.47363895861102, '2019': 81.68513055866305, '2020': 56.07129376836025, '2021': 100.51276803121101, '2022': 136.86325364698732, '2023': 189.81797257841916, '2024': 181.9319476989861}, 'GAZP': {'2006': 1.004887585532747, '2007': 1.1423935139754207, '2008': 0.37143802939465853, '2009': 0.5086292674865721, '2010': 0.49823480447486396, '2011': 0.5269835785198066, '2012': 0.4422740465936113, '2013': 0.43941252828072125, '2014': 0.30540262673166085, '2015': 0.23774395755824168, '2016': 0.27666499177175863, '2017': 0.2849565114208511, '2018': 0.3231525420154344, '2019': 0.563813117120764, '2020': 0.3638812574862416, '2021': 0.7217940812585115, '2022': 0.5755780510554478, '2023': 0.37307676845021265, '2024': 0.3616322137599433}, 'GMKN': {'2001': 1.0, '2002': 1.3660663724018483, '2003': 3.787481270396942, '2004': 3.881962201221967, '2005': 5.786962398595014, '2006': 10.631460347977994, '2007': 20.487465946041794, '2008': 5.5044520030342285, '2009': 10.617072389649683, '2010': 15.29027549090397, '2011': 14.575184795629275, '2012': 13.306221873854986, '2013': 14.398112513226936, '2014': 18.90580090207714, '2015': 16.525513776572677, '2016': 21.13083737739536, '2017': 23.56062016587265, '2018': 29.335547934397617, '2019': 46.1344928116266, '2020': 52.00706280804349, '2021': 61.036112215656786, '2022': 53.230810329655995, '2023': 43.50578727213493, '2024': 41.64966382760957}, 'TATN': {'2001': 0.9999999999999999, '2002': 1.5885362692799123, '2003': 2.0626684955729417, '2004': 3.1217096641569015, '2005': 7.094854484089224, '2006': 10.330995739682223, '2007': 12.900926911465696, '2008': 3.9760651806218794, '2009': 12.016801825252998, '2010': 12.338949790574263, '2011': 14.606117412655411, '2012': 17.87877527616856, '2013': 17.830644279996005, '2014': 14.951102002745957, '2015': 14.898870384789774, '2016': 19.564785415662588, '2017': 27.84603727291779, '2018': 41.84580057411617, '2019': 50.65218400381257, '2020': 28.919718853558116, '2021': 31.097735693281013, '2022': 33.869473903406266, '2023': 45.07997633584204, '2024': 49.96421877202243}, 'TATNP': {'2001': 1.0, '2002': 1.535830990701411, '2003': 1.8569725634851835, '2004': 2.760455649968829, '2005': 7.883304222265377, '2006': 10.942516759829635, '2007': 12.62428167404215, '2008': 3.6337359389731634, '2009': 12.009588331662114, '2010': 14.37464052596335, '2011': 19.30737999837905, '2012': 22.28380553271157, '2013': 19.243965053032017, '2014': 22.22877222420132, '2015': 23.221706727885696, '2016': 26.626117472053544, '2017': 57.41497195827478, '2018': 83.27144614033911, '2019': 132.21115109935153, '2020': 77.7971500116098, '2021': 81.95768027300599, '2022': 93.70817372554168, '2023': 128.72880760512058, '2024': 142.00698000831264}, 'PLZL': {'2006': 1.0, '2007': 0.8540525349714788, '2008': 0.37315849279367536, '2009': 1.0839967515424307, '2010': 1.144935932217122, '2011': 0.9700289569500605, '2012': 0.6739227152632785, '2013': 0.561262691681004, '2014': 0.28672572344906083, '2015': 0.9315825565215335, '2016': 1.56830912653047, '2017': 2.0334384717083243, '2018': 1.840079657904016, '2019': 2.85512963283774, '2020': 5.266906119084734, '2021': 5.576725453376241, '2022': 3.558435908531484, '2023': 3.4646169233329123, '2024': 3.3999382555991473}, 'SNGS': {'1997': 0.9999999999999999, '1998': 0.392249085693256, '1999': 1.0855675543074734, '2000': 1.1057086476887565, '2001': 1.570457993676676, '2002': 1.9797728893777051, '2003': 3.085202413070561, '2004': 4.446441123313717, '2005': 6.210608366134005, '2006': 8.474073911956985, '2007': 7.244558514986194, '2008': 4.050739456722597, '2009': 5.937841713824043, '2010': 6.336627873346809, '2011': 6.5852976007202955, '2012': 5.92501801216872, '2013': 5.85618589915613, '2014': 4.205512130871486, '2015': 3.7589852944731117, '2016': 3.5179843367947683, '2017': 3.619414417979997, '2018': 3.209951207472206, '2019': 5.465351636691174, '2020': 3.7910623815864346, '2021': 4.125966369788633, '2022': 3.115349249192478, '2023': 3.0957245786868146, '2024': 2.609627472627831}, 'SNGSP': {'1997': 1.0, '1998': 0.19647005278611224, '1999': 0.4967064830757218, '2000': 0.8529808056002228, '2001': 1.6874667891804571, '2002': 2.291205408272238, '2003': 3.434133036079109, '2004': 5.725470245583271, '2005': 8.919929514840764, '2006': 10.257493406563551, '2007': 7.300671405427221, '2008': 2.506077844884263, '2009': 6.526248255814807, '2010': 7.046194552665604, '2011': 8.970582019133394, '2012': 11.648872073820954, '2013': 13.6163663470537, '2014': 14.271237209343935, '2015': 15.812725570511905, '2016': 14.71000986246205, '2017': 14.99398268560207, '2018': 17.93043164013396, '2019': 21.660309278470333, '2020': 20.724126091335126, '2021': 23.67505691268411, '2022': 23.038688613160854, '2023': 36.564833663707795, '2024': 34.296712853336686}, 'CHMF': {'2005': 1.0261264672472548, '2006': 1.3927720025199484, '2007': 2.751459648648487, '2008': 0.5135338794035565, '2009': 1.2946724304710422, '2010': 2.4074331699965668, '2011': 2.437433269069082, '2012': 2.0748835596992485, '2013': 1.6776562326581355, '2014': 1.9076412032258419, '2015': 2.4173002845414704, '2016': 3.6858555007883878, '2017': 4.289270681314941, '2018': 4.60337968707692, '2019': 4.951173755899353, '2020': 5.866410451941556, '2021': 9.696491495642316, '2022': 6.008909601024185, '2023': 6.436862884680646, '2024': 7.0914266560478465}, 'VTBR': {'2007': 1.0058736926472849, '2008': 0.2570899635541139, '2009': 0.4905302989487432, '2010': 0.7370724591096323, '2011': 0.5159338235329272, '2012': 0.4016813875547044, '2013': 0.3408671528545026, '2014': 0.2313175780521874, '2015': 0.27481098454890457, '2016': 0.2815378554473732, '2017': 0.23143145054637404, '2018': 0.16179906853325013, '2019': 0.2094745402052401, '2020': 0.14811827755223078, '2021': 0.20085887099495547, '2022': 0.08821570589913968, '2023': 0.08271626117754473, '2024': 0.07793366494296791}, 'NLMK': {'2006': 1.02442996742671, '2007': 1.7977012272507316, '2008': 0.5165741948089128, '2009': 1.5260574510109377, '2010': 1.9050518694345515, '2011': 1.272382590142703, '2012': 1.0835011995927524, '2013': 0.874574669015066, '2014': 0.666683701087326, '2015': 0.6373741549164237, '2016': 1.1784577951767572, '2017': 1.6022484101981591, '2018': 1.9147744301978893, '2019': 1.8673345967354607, '2020': 2.569483499352804, '2021': 3.547362883450942, '2022': 2.1382014374242715, '2023': 2.3148440531734287, '2024': 2.3685362543124717}, 'IRKT': {'2004': 1.0, '2005': 1.0372636737538719, '2006': 1.6367778441644905, '2007': 1.533139859227372, '2008': 0.17269774597931012, '2009': 0.4343721656940069, '2010': 0.5118582992810183, '2011': 0.34351185799736367, '2012': 0.28776108392122407, '2013': 0.26269678150746906, '2014': 0.17654139528578616, '2015': 0.18578785409035461, '2016': 0.22653627801276918, '2017': 0.41537327643342126, '2018': 1.2498552886985592, '2019': 0.8990784573062633, '2020': 0.5360981508171091, '2021': 0.47366414444841554, '2022': 1.0734017733713133, '2023': 1.0122145023639233, '2024': 1.119927183720876}, 'PHOR': {'2011': 1.0253832876434155, '2012': 1.4431045406452592, '2013': 1.0405636466153987, '2014': 1.2054782438710072, '2015': 1.5768226509042558, '2016': 1.6945198711275065, '2017': 1.8702867395306706, '2018': 1.806624672012855, '2019': 1.9268327742842408, '2020': 2.1975550606642416, '2021': 4.686693769509546, '2022': 7.660435214892047, '2023': 6.129352193119384, '2024': 5.955638310792724}, 'UNAC': {'2010': 0.9999999999999999, '2011': 0.4226419376560701, '2012': 0.32451432368477495, '2013': 0.2416475681857124, '2014': 0.13341733388624835, '2015': 0.2747640091796508, '2016': 0.5734638386289266, '2017': 0.9058586666727998, '2018': 0.79089572933842, '2019': 0.6550504041348895, '2020': 0.35942932543397094, '2021': 0.6341502056537079, '2022': 0.5793850981631214, '2023': 0.9838677058521962, '2024': 0.9954813954662491}, 'YNDX': {'2014': 0.9999999999999999, '2015': 0.665277861549741, '2016': 0.7595692155966236, '2017': 1.330749088844307, '2018': 1.1843605958187038, '2019': 1.6839687233513188, '2020': 2.7964656226053637, '2021': 2.941663940682586, '2022': 1.3398121153223193, '2023': 1.1284422181791822, '2024': 1.1332186004298201}, 'GAZT': {'2012': 1.0, '2013': 0.9357219166968417, '2014': 0.6716021030252494, '2015': 0.5057674968591687, '2016': 0.5234029962612233, '2017': 0.5736524481861136, '2018': 0.5011050723125696, '2019': 0.3996687038582326, '2020': 0.3349962090356731, '2021': 0.3456312249528228, '2022': 0.4435228011720263, '2023': 5.8140170543805265, '2024': 5.758801205319945}, 'MGNT': {'2006': 1.0, '2007': 1.3564208519184437, '2008': 0.3727664914861519, '2009': 1.7965239371940276, '2010': 3.3591868702086516, '2011': 2.824517533171235, '2012': 4.3166636623224175, '2013': 7.854200647552776, '2014': 7.202631002344897, '2015': 5.760525449742133, '2016': 5.3299180395264045, '2017': 3.640118223055677, '2018': 1.8904109618949205, '2019': 2.0140198511856724, '2020': 2.783566060615572, '2021': 3.6335390597021497, '2022': 3.7633966949140887, '2023': 3.5213464878747494, '2024': 3.8410750137156042}, 'AKRN': {'2006': 1.0, '2007': 1.5778436372139935, '2008': 0.5676815150845299, '2009': 1.5505695960781565, '2010': 1.6279367188705962, '2011': 3.0700374766035283, '2012': 2.66536321552548, '2013': 2.0043285777014437, '2014': 2.1136356328823673, '2015': 3.8907657242256, '2016': 4.592189789808526, '2017': 6.443501304952091, '2018': 6.966705039664026, '2019': 8.146241643732342, '2020': 9.264308936837464, '2021': 21.94525613719832, '2022': 37.25905532296521, '2023': 25.943813307517907, '2024': 25.7001583958807}, 'MAGN': {'2006': 1.1390990287471328, '2007': 2.015224525176427, '2008': 0.4040712282673022, '2009': 1.3844942663293096, '2010': 1.7246627263170604, '2011': 0.8355144783707028, '2012': 0.6427014167565022, '2013': 0.42732326346002514, '2014': 0.47529018980164256, '2015': 0.6315726744184533, '2016': 1.0913193358880129, '2017': 1.628499584805532, '2018': 1.6894146586018775, '2019': 1.6672378840593463, '2020': 1.7258558468813225, '2021': 2.8297944876275665, '2022': 1.8333363145402997, '2023': 1.9595170147707626, '2024': 1.9962252142699402}, 'TCSG': {'2019': 1.0, '2020': 1.7019896423404355, '2021': 5.362223545483576, '2022': 2.4898963515980492, '2023': 2.0326488155899747, '2024': 1.9441265757955462}, 'FIVE': {'2018': 1.0, '2019': 1.2913295210869398, '2020': 1.3962171296164467, '2021': 1.0897720144903327, '2022': 1.0060473126563354, '2023': 0.9110985642404138, '2024': 0.9440479541807657}, 'OZON': {'2020': 1.0, '2021': 1.0158371958507255, '2022': 0.5932480888868484, '2023': 0.7865257536190569, '2024': 0.7746453092762342}, 'ALRS': {'2011': 1.0, '2012': 0.371960659617989, '2013': 0.5404565315012216, '2014': 0.5029090542050665, '2015': 0.42897074939024454, '2016': 0.8082687737333553, '2017': 0.8220677058886965, '2018': 1.0333910644992421, '2019': 0.9192151185378293, '2020': 0.9058788479091662, '2021': 1.5566373831059832, '2022': 0.9671417591859197, '2023': 0.6825048307374392, '2024': 0.7226023249889686}, 'RUAL': {'2015': 1.0425040041736586, '2016': 1.2714312561888355, '2017': 1.9237613183753137, '2018': 1.3617933437816616, '2019': 1.364627588733738, '2020': 1.5516585343449003, '2021': 2.9165671659587566, '2022': 2.094038844621826, '2023': 1.3221117032026362, '2024': 1.2257540281002623}, 'MTSS': {'2003': 1.0, '2004': 1.741133609074724, '2005': 1.8420720611176336, '2006': 2.246096919727812, '2007': 4.054930752586054, '2008': 1.22539595187242, '2009': 2.5881087173006736, '2010': 2.936469179124636, '2011': 2.691371723526307, '2012': 3.1003541829889105, '2013': 4.147014873668734, '2014': 2.415830537619232, '2015': 1.7696962627287134, '2016': 2.1713349340829025, '2017': 3.1513571380245136, '2018': 2.686589058796045, '2019': 3.8869314282923333, '2020': 3.7825882343421524, '2021': 4.013337966882249, '2022': 4.5558687789958645, '2023': 3.7059580538273504, '2024': 3.5849262261497366}}
containing stock ticker and price change over years
can you create an ETF based on that data and calculate total return? use python
|
d9e87549673127fa28786c17cf931d36
|
{
"intermediate": 0.3386499881744385,
"beginner": 0.3729088306427002,
"expert": 0.28844118118286133
}
|
37,927
|
async function getCardName(ctx, text, card) {
// 定义请求头
const headers = {
'Content-Type': 'application/json',
// 如果需要,添加其他必要的请求头,比如认证token等
// ‘Authorization’: ‘Bearer YOUR_TOKEN’
};
// 定义请求体
const body = {
text: "一本书籍在空中翻滚,书页上写满了神秘的符文,每一个字母都在发光,散发着强大的魔力",
user: "111",
token: "000"
};
body.text =text;
// 发送请求到端口4999
try {
const nameresponse = await axios.post('http://127.0.0.1:4999/text2name_json', body, {
headers
});
console.log('Response for 4999 port:', nameresponse.data.names);
const name = _.sample(nameresponse.data.names);
card.Name = name
return name
} catch (error) {
console.error('Error for 4999 port:', error.response ? error.response.data : error.message);
}
}
async function getCardSkill(ctx,text, card) {
// 定义请求头
const headers = {
'Content-Type': 'application/json',
// 如果需要,添加其他必要的请求头,比如认证token等
// ‘Authorization’: ‘Bearer YOUR_TOKEN’
};
// 定义请求体
const body = {
text: "一本书籍在空中翻滚,书页上写满了神秘的符文,每一个字母都在发光,散发着强大的魔力",
user: "111",
token: "000"
};
body.text = text;
// 发送请求到端口5000
try {
const skillresponse = await axios.post('http://127.0.0.1:5000/text2skill_json', body, { headers });
console.log('Response for 5000 port:', skillresponse.data.skills);
const addresses = skillresponse.data.skills;
const skills = await strapi.db.query('api::skill.skill').findMany({
where: {
address:{
$in: addresses
}
},
});
const skill = _.sample(skills)
if (skill) {
card.Cost = skill.Cost;
card.Attack = skill.Attack;
card.Health = skill.Health;
card.CardClass = skill.CardClass;
card.Type = skill.Type;
card.Description = skill.EffectDesc;
card.BackgroundStory = text;
card.skill = skill;
};
console.log(card)
return card
} catch (error) {
console.error('Error for 5000 port:', error.response ? error.response.data : error.message);
}
}
async function getCardAvatar(ctx, prompt, card) {
const headers = {
'Content-Type': 'application/json',
'x-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlvbmlkIjoiZXh0ZXJuYWwifQ.ScAXbWObCZC63cl0gVXslIRAgLUM5oZqpXJmP9_HZos'
}
let response = await axios.post('https://api.talesofai.cn/v3/make_image', ctx.request.body, {
headers, params: {
query: ctx.query
}
});
const taskId = response.data;
response = await axios.get('https://api.talesofai.cn/v1/get_task_image', {
params: {
taskId,
}
});
while (response.data.status !== 'SUCCESS') {
// 等待一段时间后再继续轮询
await new Promise(resolve => setTimeout(resolve, 1000));
response = await axios.get('https://api.talesofai.cn/v1/get_task_image', {
params: {
taskId
}
});
console.log("progress: ", response.data.data.progress);
}
card.Avatar = response.data.data.img_url;
}
let templateCard = await strapi.db.query('api::card.card').findOne({
where: {
$not: {
skill: null
}
},
populate: ['skill']
});
templateCard.IsAiGenerated = true;
axios.defaults.headers['Content-Type'] = 'application/json'
// 解构并复制原始的 body 数据
let modifiedBody = { ...ctx.request.body };
// 选择新的 rawPrompt
const firstPrompt = modifiedBody.rawPrompt[0];
const remainingPrompts = modifiedBody.rawPrompt.slice(1);
const selectedPrompt = remainingPrompts[Math.floor(Math.random() * remainingPrompts.length)];
// 构建新的 rawPrompt 数组
const newRawPrompt = [firstPrompt, selectedPrompt];
const text = modifiedBody.rawPrompt[0].value;
const name = await getCardName(ctx, text, templateCard);
modifiedBody.rawPrompt[0].value = name + ',' + text
// 更新 modifiedBody 中的 rawPrompt 属性
ctx.request.body = { ...modifiedBody, rawPrompt: newRawPrompt };
try {
const allResults = await Promise.all([
getCardSkill(ctx, text, templateCard),
getCardAvatar(ctx, name + ',' + text, templateCard)
]);
// await getCardName(ctx, text, templateCard),
// await getCardSkill(ctx, text, templateCard),
// await getCardAvatar(ctx, templateCard)
// 所有请求成功,此时allResults为一个数组,包含了每一个函数返回的结果。
// 根据函数的实现情况和实际需求来处理这些结果
console.log('All requests finished successfully.');
const random = Math.floor(Math.random() * 100); // 生成0-99之间的随机数
if (random < 5) {
templateCard.FaceRank = 0;
} else {
templateCard.FaceRank = 1;
}
templateCard.id = 0;
// 例如,如果这些函数没有返回值,但是修改了card对象,则你可以在这里返回card
return templateCard;
} catch (error) {
// 如果有任何请求失败,则会捕获到错误
console.error('An error occurred:', error.message);
throw error; // 可以重新抛出错误或者处理错误
}
finally{
await strapi.db.query('api::record.record').create({
data: {
title: text,
body : JSON.stringify(templateCard),
body_json: templateCard,
tag: "ai generate card"
}
})
} 帮我修改下代码,现在只返回了 一张卡牌,我想用生成的。10个 names和skills。填充10张卡牌然后返回
|
484729ec1e25d4d087de6da813583339
|
{
"intermediate": 0.25757497549057007,
"beginner": 0.5129009485244751,
"expert": 0.22952404618263245
}
|
37,928
|
how do detect if window of a title "abc" exist in keyboard maestro engine
|
6c28f3b8565e35840cb57bab188b89ee
|
{
"intermediate": 0.29752206802368164,
"beginner": 0.14807479083538055,
"expert": 0.5544031858444214
}
|
37,929
|
Make a D&D 5e statblock for a hypothetical creature called a "Wobblebutt Sheep". A "Wobblebutt" refers to a unique mutation present in many quadrupedal mammals, in which a vast number of a species' numbers have an enormously enlarged and (as the name would suggest) wobbly rear end, round and protruding and that which makes up about a third of their body weight and size, if not more; the bigger their behind, the more desirable they are. The potential reasons behind the development of such a trait in so many varying animals are numerous, and could be anything from a self-defense mechanism to a way to make itself appear more intimidating, or perhaps a mass spell gone... right? However, the sheer width of their hindquarters leaves them with little awareness as to what's directly behind them, which why its common to see Wobblebutts accidentally sit down on any smaller creatures (un)lucky enough to get caught directly behind it.
|
3eb435b5c2bc682a2ca43fd57aa45cfa
|
{
"intermediate": 0.3445381224155426,
"beginner": 0.33829522132873535,
"expert": 0.31716665625572205
}
|
37,930
|
Convert select to oracle CREATE VIEW statement
|
26c5888ef3726d7c09aadf1846ce23e2
|
{
"intermediate": 0.26567745208740234,
"beginner": 0.15064026415348053,
"expert": 0.5836822390556335
}
|
37,931
|
I have a spreadsheet where I usually enter suppliers details.
The information is always entered in B3 to B8.
Can I have a VBA code that will do the following.
As I enter data into each cell it calculates other cell as follows:
B3 calculates J1
B4 calculates K1
B5 calculates L1
B6 calculates M1
B7 calculates N1
B8 calculates O1
After the last entry in B8,
I want the VBA code to search down the J,K,L,M,N,O columns to row 700
to find if there is a duplicate entry.
If any duplicate entry is found, it should highlight the duplicate in the Row 1 entry.
If no duplicate entry is found,
It will make button 2 visible and pop up a Yes No message asking,
"Do you want to add the details to the Suppliers List".
If I choose Yes,
thenthe data in B3:B8 is added to the next available row in sheet 'Suppliers',
B3 into A
B4 into B
B5 into C
B6 into D
B7 into E
B8 into F
After the entry it will pop up a message saying
"New suppliers details added"
new line
"Remember to update List selection in"
new line
"Job Request B3"
|
8f54c13fc6b0cb111f1c97b43c0784bd
|
{
"intermediate": 0.41788700222969055,
"beginner": 0.2692127227783203,
"expert": 0.3129003047943115
}
|
37,932
|
I made some correction to the code as shown below,
but I am getting an error on this line:
Range("J1:O1").Find(What:=duplicateCell.Value, LookIn:=xlValues, LookAt:=xlWhole).Interior.Color = RGB(255, 0, 0)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lastRow As Long
Dim checkRange As Range
Dim duplicateCell As Range
' Unlock the worksheet
ActiveSheet.Unprotect Password:="edit"
' Check if Target is within the specified range
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, Range("D4")) Is Nothing Then
' Call FindAndCopySupplierData
Application.EnableEvents = False
Call FindAndCopySupplierData
Application.EnableEvents = True
End If
' Check if Target is within the specified range
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, Range("A11")) Is Nothing Then
' Update E12 with current timestamp
Application.EnableEvents = False
If Target.Value <> "" Then
Range("E11").Value = Now
End If
Application.EnableEvents = True
End If
' Calculate J1 to O1 based on B3 to B8 entries
If Not Intersect(Target, Range("B3:B8")) Is Nothing Then
Range("J1:O1").Value = WorksheetFunction.Transpose(Range("B3:B8").Value)
End If
' Check for duplicate entries in J1 to O1 from row 1 to 700
lastRow = 700
Set checkRange = Range("J4:O" & lastRow)
For Each duplicateCell In checkRange
If WorksheetFunction.CountIf(checkRange, duplicateCell.Value) > 1 Then
' Mark duplicates in Row 1
If Application.CountIf(Rows(1), duplicateCell.Value) > 1 Then
duplicateFound = True
Range("J1:O1").Find(What:=duplicateCell.Value, LookIn:=xlValues, LookAt:=xlWhole).Interior.Color = RGB(255, 0, 0)
Else
' Reset color if no duplicates are found in Row 1
Range("J1:O1").Interior.ColorIndex = xlNone
End If
End If
Next duplicateCell
' Check if all entries are unique
If WorksheetFunction.CountA(checkRange) = lastRow Then
' Make Button2 visible
'Sheet1.Buttons("Button2").Visible = True
' Ask user if they want to add the details to the Suppliers List
Dim response As VbMsgBoxResult
response = MsgBox("Do you want to add the details to the Suppliers List?", vbQuestion + vbYesNo)
If response = vbYes Then
' Add details to Suppliers List
Dim suppliersSheet As Worksheet
Set suppliersSheet = ThisWorkbook.Sheets("Suppliers")
With suppliersSheet
lastRow = .Cells(.Rows.count, "A").End(xlUp).row + 1 ' Find next available row in Suppliers sheet
.Cells(lastRow, "A").Value = Range("B3").Value
.Cells(lastRow, "B").Value = Range("B4").Value
.Cells(lastRow, "C").Value = Range("B5").Value
.Cells(lastRow, "D").Value = Range("B6").Value
.Cells(lastRow, "E").Value = Range("B7").Value
.Cells(lastRow, "F").Value = Range("B8").Value
MsgBox "New supplier's details added" & vbCrLf & "Remember to update List selection in" & vbCrLf & "Job Request B3"
End With
End If
End If
' Lock the worksheet
ActiveSheet.Protect Password:="edit"
End Sub
|
3d01e4e4f4b246c44c200e6c36fc2578
|
{
"intermediate": 0.37756702303886414,
"beginner": 0.36517471075057983,
"expert": 0.25725826621055603
}
|
37,933
|
git push -u origin dev
To git.mcb.ru:validation/vtests.git
! [rejected] dev -> dev (non-fast-forward)
error: failed to push some refs to 'git.mcb.ru:validation/vtests.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Ismailov@ITPC010959 MINGW64 /z/ADD/ФД/Валидация/Рабочая директория/Исмаилов/mkb_libs/vtests (dev)
$ git pull dev
fatal: 'dev' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Ismailov@ITPC010959 MINGW64 /z/ADD/ФД/Валидация/Рабочая директория/Исмаилов/mkb_libs/vtests (dev)
$ git pull --all
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream-to=origin/<branch> dev
Ismailov@ITPC010959 MINGW64 /z/ADD/ФД/Валидация/Рабочая директория/Исмаилов/mkb_libs/vtests (dev)
$ git pull --all dev
fatal: fetch --all does not take a repository argument
Ismailov@ITPC010959 MINGW64 /z/ADD/ФД/Валидация/Рабочая директория/Исмаилов/mkb_libs/vtests (dev)
$ git pull dev
fatal: 'dev' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
|
da8f427611fe799a10ec707b05bf6def
|
{
"intermediate": 0.3938227891921997,
"beginner": 0.2528521716594696,
"expert": 0.3533250093460083
}
|
37,934
|
im working on a script but how do i get this # Construct the command to run
command_suffix = ' '.join([option for option in selected_options_list] + [website for website in custom_websites if website and website.strip() != ''] + ([f'"SEPARATE APP IDS - CHECK THIS TO SEPARATE YOUR PREFIX\'S"'] if separate_app_ids else []) + ([f'"Start Fresh"'] if start_fresh else [])) + "'" to make the output of this selection to come out like this? /bin/bash -c 'curl -Ls https://raw.githubusercontent.com/moraroy/NonSteamLaunchers-On-Steam-Deck/main/NonSteamLaunchers.sh | nohup /bin/bash -s -- "Epic Games" "SEPARATE APP IDS - CHECK THIS TO SEPARATE YOUR PREFIX'\''S"'
|
8ff3c19e482c11ef7c683973f452f9d4
|
{
"intermediate": 0.5012755393981934,
"beginner": 0.335263192653656,
"expert": 0.16346123814582825
}
|
37,935
|
hi
|
95c4bcfc963c3f4770b3a5f43edec11d
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
37,936
|
Ismailov@ITPC010959 MINGW64 /z/ADD/ФД/Валидация/Рабочая директория/Исмаилов/mkb_libs/vtests (dev)
$ git pull origin dev
From git.mcb.ru:validation/vtests
* branch dev -> FETCH_HEAD
Auto-merging vtests/additional.py
CONFLICT (content): Merge conflict in vtests/additional.py
Auto-merging vtests/imports.py
Automatic merge failed; fix conflicts and then commit the result.
Как посмотреть, какие это конфликты?
|
b7be5ae1993d7a745354a054291fdd27
|
{
"intermediate": 0.42618194222450256,
"beginner": 0.24213989078998566,
"expert": 0.331678181886673
}
|
37,937
|
What would be a great puzzle script for a lovecraftian horror game in c# for Unity?
|
9a868dc7dd4ff19a94e1aa5272bc9622
|
{
"intermediate": 0.4786933362483978,
"beginner": 0.3502541780471802,
"expert": 0.171052485704422
}
|
37,938
|
Create in C# for uinity an amazing lovecraftian puzzle. Here’s a backstory to help you : The game is about townpeople who appeared to have made a collective suicide in a ritual of some sort, and they are now zombie like people possessed by cosmic horror entities called "The Shadow People". The player is an occult investigator sent to help one of the citizen, who had claimed something weird happening in the town of Ashbury recently. The player entering Ashbury faces the horrifying nightmare the town has now become. On his way, the place retrieve some books that relates the events in some way and the player slowly understand what's going on. These books are name " Invocation of the cosmic horror", "The House of R'lyeh", "Mark of the old Gods", "The Shadow People", The Unknown and the Deep Void".
|
af1ff30802cbd916399c164463e81680
|
{
"intermediate": 0.4156602919101715,
"beginner": 0.3632813096046448,
"expert": 0.22105835378170013
}
|
37,939
|
i have this responses
{
"responses": {
"urn:li:dataset:(urn:li:dataPlatform:bigquery,data-dev-270120.dbt_test.testing_vita_model,PROD)": {
"entityName": "dataset",
"urn": "urn:li:dataset:(urn:li:dataPlatform:bigquery,data-dev-270120.dbt_test.testing_vita_model,PROD)",
"aspects": {
"browsePaths": {
"name": "browsePaths",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "BrowsePaths",
"paths": [
"/prod/bigquery/data-dev-270120/dbt_test"
]
},
"created": {
"time": 1691464435632,
"actor": "urn:li:corpuser:datahub"
}
},
"container": {
"name": "container",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "Container",
"container": "urn:li:container:0000169e8eeca3ad16278f6218b154a1"
},
"created": {
"time": 1691464435650,
"actor": "urn:li:corpuser:datahub"
}
},
"datasetKey": {
"name": "datasetKey",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "DatasetKey",
"platform": "urn:li:dataPlatform:bigquery",
"name": "data-dev-270120.dbt_test.testing_vita_model",
"origin": "PROD"
},
"created": {
"time": 1691464435632,
"actor": "urn:li:corpuser:datahub"
}
},
"browsePathsV2": {
"name": "browsePathsV2",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "BrowsePathsV2",
"path": [
{
"id": "urn:li:container:37cd23bac6a54cc78f143e64921b7189",
"urn": "urn:li:container:37cd23bac6a54cc78f143e64921b7189"
},
{
"id": "urn:li:container:0000169e8eeca3ad16278f6218b154a1",
"urn": "urn:li:container:0000169e8eeca3ad16278f6218b154a1"
}
]
},
"created": {
"time": 1691464436319,
"actor": "urn:li:corpuser:datahub"
}
},
"dataPlatformInstance": {
"name": "dataPlatformInstance",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "DataPlatformInstance",
"platform": "urn:li:dataPlatform:bigquery"
},
"created": {
"time": 1694478103224,
"actor": "urn:li:corpuser:datahub"
}
},
"subTypes": {
"name": "subTypes",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "SubTypes",
"typeNames": [
"Table"
]
},
"created": {
"time": 1691464436324,
"actor": "urn:li:corpuser:datahub"
}
},
"datasetProperties": {
"name": "datasetProperties",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "DatasetProperties",
"customProperties": {
"size_in_bytes": "527",
"billable_bytes_long_term": "527"
},
"externalUrl": "https://console.cloud.google.com/bigquery?project=data-dev-270120&ws=!1m5!1m4!4m3!1sdata-dev-270120!2sdbt_test!3stesting_vita_model",
"name": "testing_vita_model",
"qualifiedName": "data-dev-270120.dbt_test.testing_vita_model",
"created": {
"time": 1660036474847
},
"lastModified": {
"time": 1660036474847
},
"tags": []
},
"created": {
"time": 1692257058294,
"actor": "urn:li:corpuser:datahub"
}
},
"schemaMetadata": {
"name": "schemaMetadata",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "SchemaMetadata",
"schemaName": "data-dev-270120.dbt_test.testing_vita_model",
"platform": "urn:li:dataPlatform:bigquery",
"version": 0,
"created": {
"time": 0,
"actor": "urn:li:corpuser:unknown"
},
"lastModified": {
"time": 0,
"actor": "urn:li:corpuser:unknown"
},
"hash": "",
"platformSchema": {
"__type": "MySqlDDL",
"tableSchema": ""
},
"fields": [
{
"fieldPath": "system",
"nullable": true,
"type": {
"type": {
"__type": "StringType"
}
},
"nativeDataType": "STRING",
"recursive": false,
"globalTags": {
"__type": "GlobalTags",
"tags": []
},
"isPartOfKey": false
},
{
"fieldPath": "system_vini",
"nullable": true,
"type": {
"type": {
"__type": "StringType"
}
},
"nativeDataType": "STRING",
"recursive": false,
"globalTags": {
"__type": "GlobalTags",
"tags": []
},
"isPartOfKey": false
},
{
"fieldPath": "job_id",
"nullable": true,
"type": {
"type": {
"__type": "NumberType"
}
},
"nativeDataType": "INT64",
"recursive": false,
"globalTags": {
"__type": "GlobalTags",
"tags": []
},
"isPartOfKey": false
},
{
"fieldPath": "gojek_order_no",
"nullable": true,
"type": {
"type": {
"__type": "StringType"
}
},
"nativeDataType": "STRING",
"recursive": false,
"globalTags": {
"__type": "GlobalTags",
"tags": []
},
"isPartOfKey": false
},
{
"fieldPath": "booking_status",
"nullable": true,
"type": {
"type": {
"__type": "StringType"
}
},
"nativeDataType": "STRING",
"recursive": false,
"globalTags": {
"__type": "GlobalTags",
"tags": []
},
"isPartOfKey": false
}
]
},
"created": {
"time": 1691464435648,
"actor": "urn:li:corpuser:datahub"
}
},
"status": {
"name": "status",
"type": "VERSIONED",
"version": 0,
"value": {
"__type": "Status",
"removed": false
},
"created": {
"time": 1691464435628,
"actor": "urn:li:corpuser:datahub"
}
}
}
}
}
}
|
de7c3820c5d6466b47e6e0e5a1b587df
|
{
"intermediate": 0.33146339654922485,
"beginner": 0.48247572779655457,
"expert": 0.1860608458518982
}
|
37,940
|
i have api datahub like this
curl --location --request POST 'http://localhost:8080/entities?action=ingest' \
-H 'accept: application/json' \
-H 'Authorization: Bearer ...' \
-H 'Content-Type: application/json' \
-d '{
"entity": {
"value": {
"com.linkedin.metadata.snapshot.DatasetSnapshot": {
"urn": "urn:li:dataset:(urn:li:dataPlatform:bigquery,data-dev-270120.dbt_test.testing_uhuy,PROD)",
"aspects": [
{
"com.linkedin.common.BrowsePaths": {
"paths": ["/prod/bigquery/data-dev-270120/dbt_test"]
}
},
{
"com.linkedin.schema.SchemaMetadata": {
"schemaName": "testing_uhuy",
"fields": [
{
"fieldPath": "system",
"type": {"type": {"com.linkedin.schema.StringType": {}}}
},
{
"fieldPath": "job_id",
"type": {"type": {"com.linkedin.schema.NumberType": {}}}
}
]
}
}
]
}
}
}
}'
|
4a2b568d169bbf6409d256278191bff2
|
{
"intermediate": 0.39810729026794434,
"beginner": 0.3847288489341736,
"expert": 0.21716387569904327
}
|
37,941
|
import json
import argparse
from docx import Document
from typing import Dict, List
def read_notebook(path: str) -> Dict:
with open(path, encoding='utf8') as f:
file = json.load(f)
return file
def parse_notebook(file: Dict) -> Document:
document = Document()
for cell in file['cells']:
if cell['cell_type'] == 'markdown':
paragraph = parse_cell(cell['source'])
document.add_paragraph(paragraph)
return document
def parse_cell(lines: List) -> str:
paragraph = ''
for line in lines:
if "![" not in line: # drop pictures
paragraph += line
return paragraph
def main():
parser = argparse.ArgumentParser(description='Process command line arguments.')
parser.add_argument('--path', type=str, help='notebook path for parsing')
args = parser.parse_args()
path = args.path
file = read_notebook(path)
document = parse_notebook(file)
document.save('docx_file.docx')
if __name__ == "__main__":
main()
|
c01ceb0eb501b03886f7114a886adefb
|
{
"intermediate": 0.4997485876083374,
"beginner": 0.33736521005630493,
"expert": 0.1628861427307129
}
|
37,942
|
lets play a roleplaying game. you are a hacker in a tv show and I'm the recorder
|
514f346509441c04d7e33334f62e52f5
|
{
"intermediate": 0.3515164256095886,
"beginner": 0.3914071023464203,
"expert": 0.2570764720439911
}
|
37,943
|
write manim animation that shows a spinning DNA
|
12b2491834b5b839b3f39e321b38e265
|
{
"intermediate": 0.3819844424724579,
"beginner": 0.34012624621391296,
"expert": 0.27788928151130676
}
|
37,944
|
hi can you confirm what version of chat gpt you are running on?
|
f6572fe94d0142661f92514a795046b5
|
{
"intermediate": 0.315537691116333,
"beginner": 0.17601487040519714,
"expert": 0.5084474086761475
}
|
37,945
|
Servicenow script for change field value based on another field
|
8e33168116f813ffa2ff9b2b9b06c9b0
|
{
"intermediate": 0.5230956077575684,
"beginner": 0.15339836478233337,
"expert": 0.32350605726242065
}
|
37,946
|
Please give short introduction to Get-ChildItem
|
1a552d0122eddc4bf8b901ab9126f5c4
|
{
"intermediate": 0.5193086266517639,
"beginner": 0.25886061787605286,
"expert": 0.22183075547218323
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.