row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
903
|
Develop class of wideband spectrum generator for radio signals in C++. This class implements methods of generating frequency spectrum of signals with different modulation (implement AM). The generator takes the frequency range (start and end), sample rate, noise floor (dbm), noise standard deviation, list of signal information: struct Signal {double power//dbm; double frequency; double bandwidth;}. First it generates a noize floor in frequency range. Then has to calculate signal, then calculate its complex spectrum and than get power spectrum. After all signal spectra have been generated, they have to be added to frequency range. The output is an vector of spectrum values in logarithmic scale.
|
63469c934da3b02bf0de9fdec90e816b
|
{
"intermediate": 0.43604403734207153,
"beginner": 0.21590547263622284,
"expert": 0.3480505049228668
}
|
904
|
Develop class of wideband spectrum generator for radio signals in C++. This class implements methods of generating frequency spectrum of signals with different modulation (implement AM). The generator takes the frequency range (start and end), sample rate, noise floor (dbm), noise standard deviation, list of signal information: struct Signal {double power//dbm; double frequency; double bandwidth;}. First it generates a noize floor in frequency range. Then has to calculate signal, then calculate its complex spectrum and than get power spectrum. After all signal spectra have been generated, they have to be added to frequency range. The output is an vector of spectrum values in logarithmic scale.
|
9f2197759ca79eab5371e7e0603844fa
|
{
"intermediate": 0.43604403734207153,
"beginner": 0.21590547263622284,
"expert": 0.3480505049228668
}
|
905
|
Develop class of wideband spectrum generator for radio signals in C++. This class implements methods of generating frequency spectrum of signals with different modulation (implement AM). The generator takes the frequency range (start and end), sample rate, noise floor (dbm), signal-to-noise ratio(dbm), list of signal information: struct Signal {double power//dbm; double frequency; double bandwidth;}. First it generates a noize floor in frequency range. Then has to calculate signal, then calculate its complex spectrum and than get power spectrum. After all signal spectra have been generated, they have to be added to frequency range. The output is an vector of spectrum values in logarithmic scale.
|
34bb4e443493d69d6c5725c098f5994a
|
{
"intermediate": 0.43447184562683105,
"beginner": 0.21884417533874512,
"expert": 0.34668397903442383
}
|
906
|
Write aim, objective, algorithm, Matlab code along with the code to display the graph, interpretation for Gauss Elimination Method
|
cd15143009368fb00560c34c520326a9
|
{
"intermediate": 0.12114480137825012,
"beginner": 0.09466629475355148,
"expert": 0.7841888666152954
}
|
907
|
Write aim, objective, algorithm, Matlab code along with the code to display the graph, interpretation for L-U decomposition method
|
029e5e3dc280f21a702fe7ed88f38018
|
{
"intermediate": 0.16963320970535278,
"beginner": 0.11300589144229889,
"expert": 0.7173609137535095
}
|
908
|
analizar para ver que hace este codigo: "from collections import deque
from typing import Dict, List, Optional
from langchain import LLMChain, OpenAI, PromptTemplate
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.llms import BaseLLM
from langchain.vectorstores import FAISS
from langchain.vectorstores.base import VectorStore
from pydantic import BaseModel, Field
import streamlit as st
class TaskCreationChain(LLMChain):
@classmethod
def from_llm(cls, llm: BaseLLM, objective: str, verbose: bool = True) -> LLMChain:
"""Get the response parser."""
task_creation_template = (
"You are an task creation AI that uses the result of an execution agent"
" to create new tasks with the following objective: {objective},"
" The last completed task has the result: {result}."
" This result was based on this task description: {task_description}."
" These are incomplete tasks: {incomplete_tasks}."
" Based on the result, create new tasks to be completed"
" by the AI system that do not overlap with incomplete tasks."
" Return the tasks as an array."
)
prompt = PromptTemplate(
template=task_creation_template,
partial_variables={"objective": objective},
input_variables=["result", "task_description", "incomplete_tasks"],
)
return cls(prompt=prompt, llm=llm, verbose=verbose)
def get_next_task(self, result: Dict, task_description: str, task_list: List[str]) -> List[Dict]:
"""Get the next task."""
incomplete_tasks = ", ".join(task_list)
response = self.run(result=result, task_description=task_description, incomplete_tasks=incomplete_tasks)
new_tasks = response.split('\n')
return [{"task_name": task_name} for task_name in new_tasks if task_name.strip()]
class TaskPrioritizationChain(LLMChain):
"""Chain to prioritize tasks."""
@classmethod
def from_llm(cls, llm: BaseLLM, objective: str, verbose: bool = True) -> LLMChain:
"""Get the response parser."""
task_prioritization_template = (
"You are an task prioritization AI tasked with cleaning the formatting of and reprioritizing"
" the following tasks: {task_names}."
" Consider the ultimate objective of your team: {objective}."
" Do not remove any tasks. Return the result as a numbered list, like:"
" #. First task"
" #. Second task"
" Start the task list with number {next_task_id}."
)
prompt = PromptTemplate(
template=task_prioritization_template,
partial_variables={"objective": objective},
input_variables=["task_names", "next_task_id"],
)
return cls(prompt=prompt, llm=llm, verbose=verbose)
def prioritize_tasks(self, this_task_id: int, task_list: List[Dict]) -> List[Dict]:
"""Prioritize tasks."""
task_names = [t["task_name"] for t in task_list]
next_task_id = int(this_task_id) + 1
response = self.run(task_names=task_names, next_task_id=next_task_id)
new_tasks = response.split('\n')
prioritized_task_list = []
for task_string in new_tasks:
if not task_string.strip():
continue
task_parts = task_string.strip().split(".", 1)
if len(task_parts) == 2:
task_id = task_parts[0].strip()
task_name = task_parts[1].strip()
prioritized_task_list.append({"task_id": task_id, "task_name": task_name})
return prioritized_task_list
class ExecutionChain(LLMChain):
"""Chain to execute tasks."""
vectorstore: VectorStore = Field(init=False)
@classmethod
def from_llm(cls, llm: BaseLLM, vectorstore: VectorStore, verbose: bool = True) -> LLMChain:
"""Get the response parser."""
execution_template = (
"You are an AI who performs one task based on the following objective: {objective}."
" Take into account these previously completed tasks: {context}."
" Your task: {task}."
" Response:"
)
prompt = PromptTemplate(
template=execution_template,
input_variables=["objective", "context", "task"],
)
return cls(prompt=prompt, llm=llm, verbose=verbose, vectorstore=vectorstore)
def _get_top_tasks(self, query: str, k: int) -> List[str]:
"""Get the top k tasks based on the query."""
results = self.vectorstore.similarity_search_with_score(query, k=k)
if not results:
return []
sorted_results, _ = zip(*sorted(results, key=lambda x: x[1], reverse=True))
return [str(item.metadata['task']) for item in sorted_results]
def execute_task(self, objective: str, task: str, k: int = 5) -> str:
"""Execute a task."""
context = self._get_top_tasks(query=objective, k=k)
return self.run(objective=objective, context=context, task=task)
class Message:
exp: st.expander
ai_icon = "./img/robot.png"
def __init__(self, label: str):
message_area, icon_area = st.columns([10, 1])
icon_area.image(self.ai_icon, caption="BabyAGI")
# Expander
self.exp = message_area.expander(label=label, expanded=True)
def __enter__(self):
return self
def __exit__(self, ex_type, ex_value, trace):
pass
def write(self, content):
self.exp.markdown(content)
class BabyAGI(BaseModel):
"""Controller model for the BabyAGI agent."""
objective: str = Field(alias="objective")
task_list: deque = Field(default_factory=deque)
task_creation_chain: TaskCreationChain = Field(...)
task_prioritization_chain: TaskPrioritizationChain = Field(...)
execution_chain: ExecutionChain = Field(...)
task_id_counter: int = Field(1)
def add_task(self, task: Dict):
self.task_list.append(task)
def print_task_list(self):
with Message(label="Task List") as m:
m.write("### Task List")
for t in self.task_list:
m.write("- " + str(t["task_id"]) + ": " + t["task_name"])
m.write("")
def print_next_task(self, task: Dict):
with Message(label="Next Task") as m:
m.write("### Next Task")
m.write("- " + str(task["task_id"]) + ": " + task["task_name"])
m.write("")
def print_task_result(self, result: str):
with Message(label="Task Result") as m:
m.write("### Task Result")
m.write(result)
m.write("")
def print_task_ending(self):
with Message(label="Task Ending") as m:
m.write("### Task Ending")
m.write("")
def run(self, max_iterations: Optional[int] = None):
"""Run the agent."""
num_iters = 0
while True:
if self.task_list:
self.print_task_list()
# Step 1: Pull the first task
task = self.task_list.popleft()
self.print_next_task(task)
# Step 2: Execute the task
result = self.execution_chain.execute_task(
self.objective, task["task_name"]
)
this_task_id = int(task["task_id"])
self.print_task_result(result)
# Step 3: Store the result in Pinecone
result_id = f"result_{task['task_id']}"
self.execution_chain.vectorstore.add_texts(
texts=[result],
metadatas=[{"task": task["task_name"]}],
ids=[result_id],
)
# Step 4: Create new tasks and reprioritize task list
new_tasks = self.task_creation_chain.get_next_task(
result, task["task_name"], [t["task_name"] for t in self.task_list]
)
for new_task in new_tasks:
self.task_id_counter += 1
new_task.update({"task_id": self.task_id_counter})
self.add_task(new_task)
self.task_list = deque(
self.task_prioritization_chain.prioritize_tasks(
this_task_id, list(self.task_list)
)
)
num_iters += 1
if max_iterations is not None and num_iters == max_iterations:
self.print_task_ending()
break
@classmethod
def from_llm_and_objectives(
cls,
llm: BaseLLM,
vectorstore: VectorStore,
objective: str,
first_task: str,
verbose: bool = False,
) -> "BabyAGI":
"""Initialize the BabyAGI Controller."""
task_creation_chain = TaskCreationChain.from_llm(
llm, objective, verbose=verbose
)
task_prioritization_chain = TaskPrioritizationChain.from_llm(
llm, objective, verbose=verbose
)
execution_chain = ExecutionChain.from_llm(llm, vectorstore, verbose=verbose)
controller = cls(
objective=objective,
task_creation_chain=task_creation_chain,
task_prioritization_chain=task_prioritization_chain,
execution_chain=execution_chain,
)
controller.add_task({"task_id": 1, "task_name": first_task})
return controller
def main():
st.set_page_config(
initial_sidebar_state="expanded",
page_title="BabyAGI Streamlit",
layout="centered",
)
with st.sidebar:
openai_api_key = st.text_input('Your OpenAI API KEY', type="password")
st.title("BabyAGI Streamlit")
objective = st.text_input("Input Ultimate goal", "Solve world hunger")
first_task = st.text_input("Input Where to start", "Develop a task list")
max_iterations = st.number_input("Max iterations", value=3, min_value=1, step=1)
button = st.button("Run")
embedding_model = HuggingFaceEmbeddings()
vectorstore = FAISS.from_texts(["_"], embedding_model, metadatas=[{"task":first_task}])
if button:
try:
baby_agi = BabyAGI.from_llm_and_objectives(
llm=OpenAI(openai_api_key=openai_api_key),
vectorstore=vectorstore,
objective=objective,
first_task=first_task,
verbose=False
)
baby_agi.run(max_iterations=max_iterations)
except Exception as e:
st.error(e)
if __name__ == "__main__":
main()"
|
e6a03b905306868eeb1fa20361825ef9
|
{
"intermediate": 0.43235886096954346,
"beginner": 0.41792061924934387,
"expert": 0.14972054958343506
}
|
909
|
Write aim, objective, algorithm, Matlab code along with the code to display the graph, interpretation for Jacobi method
|
71853ac12396fec8d9713ba063cddee5
|
{
"intermediate": 0.16742254793643951,
"beginner": 0.1286376416683197,
"expert": 0.7039397954940796
}
|
910
|
Write aim, objective, algorithm, Matlab code along with the code to display the graph, interpretation for Gauss - Seidel method
|
54479b61534aa5f432184c4ab57c3f3b
|
{
"intermediate": 0.1705058217048645,
"beginner": 0.12588593363761902,
"expert": 0.7036082148551941
}
|
911
|
Write aim, objective, algorithm, Matlab code along with the code to display the graph, interpretation for Thomas Algorithm
|
30de1e99ba5624b0a2a670d6ae4c5ecc
|
{
"intermediate": 0.12363427877426147,
"beginner": 0.10452652722597122,
"expert": 0.7718392014503479
}
|
912
|
Mixed metal is an alloy composed of two or more different metals. The physical and chemical properties of mixed metals are often superior to those of single metals because they combine the advantages of various metals. For example, copper and tin mixed together can form a material that is harder and more corrosion-resistant than copper alone, making bronze a very popular material for construction and art. Now we know that there are three different types of metal are melted to produce several alloys, but we do not know the specific types. Luckily you collected the volume of each metal that is used during the production and save the data as one one cell array, “unknown”. Each row of the cell array represents one alloy and contains 4 pieces of information (volume of three types of metal, and total weight). Here is the table:
metal x, [cm^3] metal y, [cm^3] metal z, [cm^3] total weight [g]
2 3 4 638
3 3 4 710
5 2 3 706
In this problem, first you need to figure out teh densities of all three metals and store as “density”. Then you need to find out each metal’s weight percentage of three alloys and store the results as one cell array. Four columns are alloy labels, and three weight percentages in order. Your cell array should be like this table:
Alloy x y z
“Alloy1” 22.5705 46.0815 31.3480
“Alloy 2” 30.4225 41.4085 28.1690
“Alloy 3” 50.9915 27.7620 21.2465
You are given the following code in matlab just fill it in:
function [density,known] = alloy(unknown)
end
|
0b100bbd5e6d508059604714aee99524
|
{
"intermediate": 0.4227672219276428,
"beginner": 0.41070008277893066,
"expert": 0.1665327101945877
}
|
913
|
Develop class of wideband spectrum generator for radio signals in C++. This class implements methods of generating frequency spectrum of signals with different modulation (implement AM). The generator takes the frequency range (start and end), sample rate, noise floor (dbm), noise standart deviation, list of signal information: struct Signal {double power//dbm; double frequency; double bandwidth;}. First it generates a noize floor in frequency range. Then has to calculate signal, then calculate its complex spectrum and than get power spectrum. After all signal spectra have been generated, they have to be added to frequency range. The output is an vector of spectrum values in logarithmic scale.
|
2e4e3beaca86991bca74afdefef006d3
|
{
"intermediate": 0.44789907336235046,
"beginner": 0.2080966979265213,
"expert": 0.34400418400764465
}
|
914
|
Hi, I've implemented the following AlexNet and train_model() function to train the model based on a images dataset. I believe that there is still room for some improvements and also Tuning and fixing few lines of code. Reduce the redundancy and modifications for better memory efficient.
# Define AlexNet and ImageDataset classes
from torch.optim.lr_scheduler import ReduceLROnPlateau
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 96, kernel_size=11, stride=4),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(96, 256, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(256, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.classifier = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(p=0.5),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, len(folder_names)),
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
from torchvision import transforms
# Preprocessing transform
transform = transforms.Compose([
transforms.Resize((227, 227)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
batch_size = 32
image_dataset = ImageDataset(folder_names, transform)
all_indices = np.arange(len(image_dataset))
train_indices, test_indices = train_test_split(all_indices, test_size=0.2, random_state=42, stratify=image_dataset.y)
class ImageDataset(Dataset):
def __init__(self, folder_names, transform=None):
self.folder_names = folder_names
self.transform = transform
self.y = self.get_labels()
def get_labels(self):
labels = []
for i, folder in enumerate(self.folder_names):
labels.extend([i] * len(os.listdir(folder)))
return labels
def __len__(self):
return sum(len(os.listdir(folder)) for folder in self.folder_names)
def __getitem__(self, idx):
for i, folder_name in enumerate(self.folder_names):
if idx < len(os.listdir(folder_name)):
file = os.listdir(folder_name)[idx]
img = Image.open(os.path.join(folder_name, file))
if self.transform:
img = self.transform(img)
label = i
return img, label
idx -= len(os.listdir(folder_name))def train_model(model, train_loader, test_loader, epochs = None, learning_rate = None, optimization_technique = None, patience=None, scheduler_patience=None,num_batches = None, **kwargs):
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience:
scheduler = ReduceLROnPlateau(optimizer, 'min', patience=scheduler_patience, verbose=True)
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
best_loss = float('inf')
stopping_counter = 0
with_dropout = model.classifier[6]
without_dropout = nn.Sequential(*[layer for layer in model.classifier if layer != with_dropout])
for epoch in range(epochs):
running_train_loss = 0.0
running_train_acc = 0
num_batches_train = 0
for X_batch, y_batch in itertools.islice(train_loader, 0, num_batches):
# for X_batch, y_batch in train_loader:
optimizer.zero_grad()
y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
loss.backward()
optimizer.step()
running_train_loss += loss.item()
running_train_acc += accuracy_score(y_batch.numpy(), y_pred.argmax(dim=1).numpy())
num_batches_train += 1
train_losses.append(running_train_loss / num_batches_train)
train_accuracies.append(running_train_acc / num_batches_train)
# Testing segment
running_test_loss = 0.0
running_test_acc = 0
num_batches_test = 0
with torch.no_grad():
for X_batch, y_batch in itertools.islice(test_loader, 0, num_batches):
# with torch.no_grad():
# for X_batch, y_batch in test_loader:
y_pred = model(X_batch)
#y_pred_without_dropout = y_pred.view(y_pred.size(0), 256 * 6 * 6)
#y_pred_without_dropout = without_dropout(y_pred) # Use the classifier without dropout for testing
# y_pred = y_pred.view(y_pred.size(0), 256 * 6 * 6)
# y_pred = without_dropout(y_pred) # Use the classifier without dropout for testing
loss = criterion(y_pred, y_batch)
running_test_loss += loss.item()
running_test_acc += accuracy_score(y_batch.numpy(), y_pred.argmax(dim=1).numpy())
num_batches_test += 1
test_losses.append(running_test_loss / num_batches_test)
test_accuracies.append(running_test_acc / num_batches_test)
# Early stopping
if optimization_technique == 'early_stopping' and patience:
if test_losses[-1] < best_loss:
best_loss = test_losses[-1]
stopping_counter = 0
else:
stopping_counter += 1
if stopping_counter > patience:
print(f"Early stopping at epoch {epoch+1}/{epochs}")
break
# Learning rate scheduler
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience and scheduler:
scheduler.step(test_losses[-1])
if epoch % 10 == 0:
print(f"Epoch: {epoch+1}/{epochs}, Training Loss: {train_losses[-1]}, Test Loss: {test_losses[-1]}, Training Accuracy: {train_accuracies[-1]}, Test Accuracy: {test_accuracies[-1]}")
return train_losses, train_accuracies, test_losses, test_accuracies
# Train the model
train_loader = DataLoader(image_dataset, batch_size=batch_size, sampler=torch.utils.data.SubsetRandomSampler(train_indices))
test_loader = DataLoader(image_dataset, batch_size=batch_size, sampler=torch.utils.data.SubsetRandomSampler(test_indices))
alexnet = AlexNet()
train_losses, train_accuracies, test_losses, test_accuracies = train_model(
alexnet, train_loader, test_loader, epochs=5, learning_rate=0.01, optimization_technique=None, patience=10, num_batches=50)
|
4db53f5ee20b5d2e9dabde84ea451240
|
{
"intermediate": 0.256012886762619,
"beginner": 0.44879698753356934,
"expert": 0.29519015550613403
}
|
915
|
Mixed metal is an alloy composed of two or more different metals. The physical and chemical properties of mixed metals are often superior to those of single metals because they combine the advantages of various metals. For example, copper and tin mixed together can form a material that is harder and more corrosion-resistant than copper alone, making bronze a very popular material for construction and art. Now we know that there are three different types of metal are melted to produce several alloys, but we do not know the specific types. Luckily you collected the volume of each metal that is used during the production and save the data as one one cell array, "unknown". Each row of the cell array represents one alloy and contains 4 pieces of information (volume of three types of metal, and total weight). Here is the table:
metal x, [cm^3] metal y, [cm^3] metal z, [cm^3] total weight [g]
2 3 4 638
3 3 4 710
5 2 3 706
In this problem, first you need to figure out the densities of all three metals and store as "density". Then you need to find out each metal's weight percentage of three alloys and store the results as one cell array. Four columns are alloy labels, and three weight percentages in order. Your cell array should be like this table:
Alloy x y z
"Alloy 1" 22.5705 46.0815 31.3480
"Alloy 2" 30.4225 41.4085 28.1690
"Alloy 3" 50.9915 27.7620 21.2465
You are given the following code in matlab just fill it in:
function [density,known] = alloy(unknown)
end
|
10a530d896fec8dadda4eb0500c4392d
|
{
"intermediate": 0.31756144762039185,
"beginner": 0.4861214756965637,
"expert": 0.19631709158420563
}
|
916
|
Develop class of wideband spectrum generator for radio signals in C++. This class implements methods of generating frequency spectrum of signals with different modulation (implement AM). The generator takes the frequency range (start and end), sample rate, noise floor (dbm), noise standard deviation, list of signal information: struct Signal {double power//dbm; double frequency; double bandwidth;}. First it generates a noize floor in frequency range. Then has to calculate signal, then calculate its complex spectrum and than get power spectrum. After all signal spectra have been generated, they have to be added to frequency range. The output is an vector of spectrum values in logarithmic scale.
|
bae6548b1d60ba8fb86c7d9d9e846e23
|
{
"intermediate": 0.43604403734207153,
"beginner": 0.21590547263622284,
"expert": 0.3480505049228668
}
|
917
|
Write aim, objective, algorithm, Matlab code with graph, interpretation for Gauss Elimination Method
|
f2b5f5f4cb6685a78d3edf83fe08f639
|
{
"intermediate": 0.10866396874189377,
"beginner": 0.09533184766769409,
"expert": 0.7960041761398315
}
|
918
|
Create a hybrid model in which three different methods are incorporated to capture the linear and nonlinear features as well as other characteristics existing in the pertinent empirical time series with a designated weight comprised of a genetic algorithm for pinescript tradingview indicator pricing btc/usd not just a simple strategy but an evolved and advanced one help to identify patterns in data that would be invisible to humans. With display systems are almost always transparent. This can make it convenient for traders to understand how they work and why they make the decisions they do. This can help traders to make more informed decisions about when to buy and sell assets.
The hybrid model for btc/usd you are creating a script for pinescript tradingview indicator will incorporate the method. First method uses the ANFIS. In the second method, long-memory time series with autoregressive process is employed. Markov-switching model is also used as the third method. The ARFIMA model mainly captures linear relationships and patterns while the ANFIS and Markov-switching effectively model nonlinear relationships.
The pinescript tradingview indicator script small designating a weight factor for each individual model plays a pivotal role in improving the accuracy of the hybrid model. You shal thenceforth apply a multi-objective genetic algorithm for each model. Therefore, the individual models (ANFIS, ARFIMA, and Markov-switching) are weighted by generated by a multi-objective genetic algorithm to ascertain the paramount hybrid model with the least forecasting error. this model made from the script you are preparing to write for me models for me btc/usd comprising not just a simple strategy but an evolved and advanced one help to identify patterns in data that would be invisible to humans. With display systems are almost always transparent. This can make it convenient for traders to understand how they work and why they make the decisions they do. This can help traders to make more informed decisions about when to buy and sell assets
|
95093e16b51716ad0863d6d7a0cabe9d
|
{
"intermediate": 0.24684035778045654,
"beginner": 0.24747546017169952,
"expert": 0.5056841969490051
}
|
919
|
write a python class that will implement radio DSSS direct-sequence spread spectrum modulation and demodulation that will generate radio signal data for given data and carrier freq
|
640e0cc455f24d14932b564c5f769d47
|
{
"intermediate": 0.38270503282546997,
"beginner": 0.35432204604148865,
"expert": 0.262972891330719
}
|
920
|
Material take-off refers to a list of material swith quantities and types for construction. As one worker in the construction office, you just received one material take-off sheet for the past several months from the former worker, and one incomplete material take-off sheet for future months. (The numbers of past months and future months are both not fixed). When organizing all data in the first material take-off sheet, you store all materials’ quantities and total cost in order for the past several months as one cell array, “ptake”. One row represents one month. And materials’ names are stored in one extra string array, “materials”, like [“sand” “glass” “bricks”] in the same order as in “ptake”. Here is one example of input, “ptake”, you will get:
sand glass brick total
23 56 22 2211
34 72 53 3707
65 43 72 4037
34 64 12 2178
For the second, material sheet, you only store quantities of all materials in the same order in the cell array, “ftake”, as the total cost is not calculated yet. So the input, “ftake”, is almost the same as “ptake” except the last column.
In this question, you need to find out the unit cost of all materials first, and store them in the array, “ucost”. The order of the unit cost should follow the order of names in “materials”. Then you need to calculate the total cost for the future months. At last, you need to store materials’ quantity and total cost in the cell array, “ttake” like this:
Material Month1 Month2 … cost
“sand” 23 34 … 23523
“glass” 56 72 … 13232
“brick” 22 53 … 23287
Tips you have to use:
if “ptake”‘s month is not enough for you to obtain the unit cost of material, then “ttake” should be “Info is not enough”. You are given the following code in matlab just fill it in:
function [ucost, ttake] = takeoff(ptake, ftake, materials)
end.
You should output “ucost” a 3x1 double representing materials’ unitcost. You should also output “ttake”.
|
f180496a13290ef3b948f163182c3677
|
{
"intermediate": 0.3148854374885559,
"beginner": 0.4738043248653412,
"expert": 0.21131019294261932
}
|
921
|
Implement VGG-13 model and apply it to solve the cnn dataset which consists of three classes named dogs, food and vehicles and the directory structure is as follows: /content/dogs, /content/food, content/vehicles. Architecture to follow : The ReLU activation function
input (224 × 224 RGB image) ----> conv3-64 ; LRN ---> maxpool ---> conv3-128 --->maxpool ---> conv3-256 ; conv3-256 ----> maxpool --->conv3-512; conv3-512 --->maxpool --->conv3-512 ;conv3-512 ---> maxpool ----> FC-4096 ---> FC-4096 ----> FC-1000 ---> soft-max----> output : 3 (since classes are 3)
All the hidden layers use ReLU as its activation function. There is a padding of 1-pixel (same padding) done after each convolution layer to prevent the spatial feature of the image.
|
b876ba00956fa34ddfe73ee4a91cac28
|
{
"intermediate": 0.16348454356193542,
"beginner": 0.1141582503914833,
"expert": 0.7223572134971619
}
|
922
|
Write python code to create an app where a user can select where a question is and where the answer is (the image is from a camera). Then, the app should use OCR to know what the question is, send that to the OpenAI API, and finally convert that to gcode for a 3d printer converted into a plotter. The camera is on the top bar of the 3d printer. The paper is on the bed. Output the code for this app.
|
253cce27ccf02f36b149985ae5cbfef8
|
{
"intermediate": 0.6938273310661316,
"beginner": 0.11199713498353958,
"expert": 0.19417552649974823
}
|
923
|
Material take-off refers to a list of material swith quantities and types for construction. As one worker in the construction office, you just received one material take-off sheet for the past several months from the former worker, and one incomplete material take-off sheet for future months. (The numbers of past months and future months are both not fixed). When organizing all data in the first material take-off sheet, you store all materials' quantities and total cost in order for the past several months as one cell array, "ptake". One row represents one month. And materials' names are stored in one extra string array, "materials", like ["sand" "glass" "bricks"] in the same order as in "ptake". Here is one example of input, "ptake", you will get:
sand glass brick total
23 56 22 2211
34 72 53 3707
65 43 72 4037
34 64 12 2178
For the second, material sheet, you only store quantities of all materials in the same order in the cell array, "ftake", as the total cost is not calculated yet. So the input, "ftake", is almost the same as "ptake" except the last column.
In this question, you need to find out the unit cost of all materials first, and store them in the array, "ucost". The order of the unit cost should follow the order of names in "materials". Then you need to calculate the total cost for the future months. At last, you need to store materials' quantity and total cost in the cell array, "ttake" like this:
Material Month1 Month2 ... cost
"sand" 23 34 ... 23523
"glass" 56 72 ... 13232
"brick" 22 53 ... 23287
Tips you have to use:
if "ptake"'s month is not enough for you to obtain the unit cost of material, then "ttake" should be "Info is not enough". You are given the following code in matlab just fill it in:
function [ucost, ttake] = takeoff(ptake, ftake, materials)
end.
You should output "ucost" a 3x1 double representing materials' unitcost. You should also output "ttake".
|
3ac70cb009be97277d909c8047d32106
|
{
"intermediate": 0.3606398105621338,
"beginner": 0.37112319469451904,
"expert": 0.26823699474334717
}
|
924
|
Material take-off refers to a list of material swith quantities and types for construction. As one worker in the construction office, you just received one material take-off sheet for the past several months from the former worker, and one incomplete material take-off sheet for future months. (The numbers of past months and future months are both not fixed). When organizing all data in the first material take-off sheet, you store all materials’ quantities and total cost in order for the past several months as one cell array, “ptake”. One row represents one month. And materials’ names are stored in one extra string array, “materials”, like [“sand” “glass” “bricks”] in the same order as in “ptake”. Here is one example of input, “ptake”, you will get:
sand glass brick total
23 56 22 2211
34 72 53 3707
65 43 72 4037
34 64 12 2178
For the second, material sheet, you only store quantities of all materials in the same order in the cell array, “ftake”, as the total cost is not calculated yet. So the input, “ftake”, is almost the same as “ptake” except the last column.
In this question, you need to find out the unit cost of all materials first, and store them in the array, “ucost”. The order of the unit cost should follow the order of names in “materials”. Then you need to calculate the total cost for the future months. At last, you need to store materials’ quantity and total cost in the cell array, “ttake” like this:
Material Month1 Month2 … cost
“sand” 23 34 … 23523
“glass” 56 72 … 13232
“brick” 22 53 … 23287
Tips you have to use:
if “ptake”‘s month is not enough for you to obtain the unit cost of material, then “ttake” should be “Info is not enough”. You are given the following code in matlab just fill it in:
function [ucost, ttake] = takeoff(ptake, ftake, materials)
end.
The code I will use to call my function is: ptake = [23 56 22 2211; 34 72 53 3707;65 43 72 4037; 34 64 12 2178];
ftake = {44 22 33; 66 12 87; 32 45 84};
materials =[“sand”, “glass”, “brick”];
[ucost, ttake] = takeoff(ptake, ftake, materials). Give me the correct solution.
|
c060c3ac330f83b1acc05dc0bcf6edc1
|
{
"intermediate": 0.32163000106811523,
"beginner": 0.3830505311489105,
"expert": 0.29531946778297424
}
|
925
|
can you change the code so you can also givr the numbers 1 or 2
import random
artists_listeners = {
'Lil Baby': 58738173,
'Roddy Ricch': 34447081,
'DaBaby': 29659518,
'Polo G': 27204041,
'NLE Choppa': 11423582,
'Lil Tjay': 16873693,
'Lil Durk': 19827615,
'Megan Thee Stallion': 26685725,
'Pop Smoke': 32169881,
'Lizzo': 9236657,
'Migos': 23242076,
'Doja Cat': 33556496,
'Tyler, The Creator': 11459242,
'Saweetie': 10217413,
'Cordae': 4026278,
'Juice WRLD': 42092985,
'Travis Scott': 52627586,
'Post Malone': 65466387,
'Drake': 71588843,
'Kendrick Lamar': 33841249,
'J. Cole': 38726509,
'Kanye West': 29204328,
'Lil Nas X': 23824455,
'21 Savage': 26764030,
'Lil Uzi Vert': 40941950,
}
keys = list(artists_listeners.keys())
score = 0
while True:
first_artist = random.choice(keys)
second_artist = random.choice(keys)
while first_artist == second_artist:
second_artist = random.choice(keys)
while True:
guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ")
guess_lower = guess.strip().lower()
if guess_lower == 'quit':
print("Thanks for playing!")
quit()
elif guess_lower != first_artist.lower() and guess_lower != second_artist.lower():
print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.")
elif guess_lower == first_artist.lower() and artists_listeners[first_artist] > artists_listeners[second_artist]:
print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.")
score += 1
break
elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]:
print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.")
score += 1
break
else:
print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n")
score = 0
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == 'n':
print("Thanks for playing!")
quit()
print(f"\nYour score is {score}.")
|
7a0fd2b962a4d7e6a3be153584b8406a
|
{
"intermediate": 0.3300435245037079,
"beginner": 0.4277290999889374,
"expert": 0.24222734570503235
}
|
926
|
what does this error mean File "main.py", line 66
else:
^
IndentationError: unexpected indent
** Process exited - Return Code: 1 **
about the following code /
|
56895c12ec4e6edddeb030e5d9cf41ec
|
{
"intermediate": 0.4833957850933075,
"beginner": 0.3397473394870758,
"expert": 0.17685683071613312
}
|
927
|
Material take-off refers to a list of material swith quantities and types for construction. As one worker in the construction office, you just received one material take-off sheet for the past several months from the former worker, and one incomplete material take-off sheet for future months. (The numbers of past months and future months are both not fixed). When organizing all data in the first material take-off sheet, you store all materials’ quantities and total cost in order for the past several months as one cell array, “ptake”. One row represents one month. And materials’ names are stored in one extra string array, “materials”, like [“sand” “glass” “bricks”] in the same order as in “ptake”. Here is one example of input, “ptake”, you will get:
sand glass brick total
23 56 22 2211
34 72 53 3707
65 43 72 4037
34 64 12 2178
For the second, material sheet, you only store quantities of all materials in the same order in the cell array, “ftake”, as the total cost is not calculated yet. So the input, “ftake”, is almost the same as “ptake” except the last column.
In this question, you need to find out the unit cost of all materials first, and store them in the array, “ucost”. The order of the unit cost should follow the order of names in “materials”. Then you need to calculate the total cost for the future months. At last, you need to store materials’ quantity and total cost in the cell array, “ttake” like this:
Material Month1 Month2 … cost
“sand” 23 34 … 23523
“glass” 56 72 … 13232
“brick” 22 53 … 23287
Tips you have to use:
if “ptake”‘s month is not enough for you to obtain the unit cost of material, then “ttake” should be “Info is not enough”. You are given the following code in matlab just fill it in:
function [ucost, ttake] = takeoff(ptake, ftake, materials)
end.
The code I will use to call my function is: ptake = [23 56 22 2211; 34 72 53 3707;65 43 72 4037; 34 64 12 2178];
ftake = {44 22 33; 66 12 87; 32 45 84};
materials =[“sand”, “glass”, “brick”];
[ucost, ttake] = takeoff(ptake, ftake, materials). Give me the correct solution.
|
0c90177600fe4b0371625a9ffb67d5c1
|
{
"intermediate": 0.43593376874923706,
"beginner": 0.403958261013031,
"expert": 0.16010800004005432
}
|
928
|
Mixed metal is an alloy composed of two or more different metals. The physical and chemical properties of mixed metals are often superior to those of single metals because they combine the advantages of various metals. For example, copper and tin mixed together can form a material that is harder and more corrosion-resistant than copper alone, making bronze a very popular material for construction and art. Now we know that there are three different types of metal are melted to produce several alloys, but we do not know the specific types. Luckily you collected the volume of each metal that is used during the production and save the data as one one cell array, "unknown". Each row of the cell array represents one alloy and contains 4 pieces of information (volume of three types of metal, and total weight). Here is the table:
metal x, [cm^3] metal y, [cm^3] metal z, [cm^3] total weight [g]
2 3 4 638
3 3 4 710
5 2 3 706
In this problem, first you need to figure out teh densities of all three metals and store as "density". Then you need to find out each metal's weight percentage of three alloys and store the results as one cell array. Four columns are alloy labels, and three weight percentages in order. Your cell array should be like this table:
Alloy x y z
"Alloy1" 22.5705 46.0815 31.3480
"Alloy 2" 30.4225 41.4085 28.1690
"Alloy 3" 50.9915 27.7620 21.2465
You are given the following code in matlab just fill it in:
function [density,known] = alloy(unknown)
end. This is the code I will use to call my function, give me the correct solution:
unknown = {2 3 4 638; 3 3 4 710; 5 2 3 706};
[density,known] = alloy(unknown)
|
69974c4ae405accd18418e4c4df85bf8
|
{
"intermediate": 0.3619336187839508,
"beginner": 0.3074963688850403,
"expert": 0.3305700421333313
}
|
929
|
In Java, I have an array of strings. Generate a method that takes that array of strings as input and sorts it in ascending order.
|
8a7f56ba267337a015e15ce53da66cf5
|
{
"intermediate": 0.41679057478904724,
"beginner": 0.12976405024528503,
"expert": 0.4534453749656677
}
|
930
|
would this work?
|
ff98bde1c2df29f6f2f6252663e42afe
|
{
"intermediate": 0.3445911109447479,
"beginner": 0.2290261685848236,
"expert": 0.42638275027275085
}
|
931
|
import random
artists_listeners = {
'Lil Baby': 58738173,
'Roddy Ricch': 34447081,
'DaBaby': 29659518,
'Polo G': 27204041,
'NLE Choppa': 11423582,
'Lil Tjay': 16873693,
'Lil Durk': 19827615,
'Megan Thee Stallion': 26685725,
'Pop Smoke': 32169881,
'Lizzo': 9236657,
'Migos': 23242076,
'Doja Cat': 33556496,
'Tyler, The Creator': 11459242,
'Saweetie': 10217413,
'Cordae': 4026278,
'Juice WRLD': 42092985,
'Travis Scott': 52627586,
'Post Malone': 65466387,
'Drake': 71588843,
'Kendrick Lamar': 33841249,
'J. Cole': 38726509,
'Kanye West': 29204328,
'Lil Nas X': 23824455,
'21 Savage': 26764030,
'Lil Uzi Vert': 40941950,
}
keys = list(artists_listeners.keys())
score = 0
while True:
first_artist = random.choice(keys)
second_artist = random.choice(keys)
while first_artist == second_artist:
second_artist = random.choice(keys)
while True:
guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ")
guess_lower = guess.strip().lower()
if guess_lower == 'quit':
print("Thanks for playing!")
quit()
elif guess_lower in ['1', '2']:
if guess_lower == '1':
guess_artist = first_artist
else:
guess_artist = second_artist
if artists_listeners[first_artist] > artists_listeners[second_artist]:
correct_artist = first_artist
else:
correct_artist = second_artist
if guess_artist.lower() == correct_artist.lower():
print(f"You guessed correctly! {correct_artist.title()} had {int(artists_listeners[correct_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.")
score += 1
break
else:
print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n")
score = 0
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == 'n':
print("Thanks for playing!")
quit()
else:
break
print(f"\nYour score is {score}.")
would this work?
|
fb30137c46dd47042535f99c75fb4b4c
|
{
"intermediate": 0.3916667103767395,
"beginner": 0.3918173015117645,
"expert": 0.21651606261730194
}
|
932
|
Write a Matlab code with a code to display the graph(both in a single code) to get the solution of 2x1 - 3x2 + x3 = 7; x1 - x2 - 2x3 = -2; 3x1 + x2 - x3 = 0 using LU factorization method.
|
911d37637ee2af991179a99e027c10ef
|
{
"intermediate": 0.3177145719528198,
"beginner": 0.10968086868524551,
"expert": 0.5726045966148376
}
|
933
|
my code:
@bot.tree.command(name="pminesv3", description="⛏️ Predicts Mines | Buyer Reqired")
async def pminesv2(Interaction: discord.Interaction, mines:int,safe_amount_to_predict:int):
channel_id = Interaction.channel.id
allowed = Access.check_channel(channel_id)
invis = True
if allowed:
invis = False
access = Access.check_access(Interaction)
if access != True:
await Access.no_acces(Interaction)
e = discord.Embed(title=f"Mines", color=0xFF3333)
e.set_footer(text="Space Predictor")
e.add_field(name=f"**Please wait**", value=f"Loading. This can take a few seconds to complete", inline=False)
e.set_thumbnail(url="https://cdn.discordapp.com/attachments/1025786107322978416/1094392372206510250/preview.jpg")
await Interaction.response.send_message(content=f"<@{int(Interaction.user.id)}> ", embed=e,ephemeral=invis)
user_info = db.get(user.userId == Interaction.user.id)
if not user_info:
e = discord.Embed(title=f"No Account", color=0xFF3333)
e.set_footer(text="Space Predictor")
e.add_field(name=f"**Missing**", value=f"You've no account linked", inline=False)
e.set_thumbnail(url="https://cdn.discordapp.com/attachments/1025786107322978416/1094392372206510250/preview.jpg")
await Interaction.edit_original_response(content=f"<@{int(Interaction.user.id)}> ", embed=e)
return
xToken = user_info["x-auth-token"]
headers = {"x-auth-token": xToken}
mines_found = 0
num_mines = int(mines)
all_mine_locations = []
headers = {"x-auth-token": xToken}
json = scraper.get(
f"https://rest-bf.blox.land/games/mines/history?size=0&page=0",
headers=headers,
).json()
while mines_found < num_mines * 10:
for game in json["data"]:
if game["minesAmount"] == int(num_mines):
all_mine_locations.extend(game["mineLocations"])
mines_found += num_mines # Den skal ikke være 1
if mines_found >= num_mines * 10:
break
paid.fix_mines_locations(all_mine_locations)
print(all_mine_locations)
raaa = scraper.get(f"https://rest-bf.blox.land/user/wallet-history?size=1&page=0",headers=headers,).json()
searchabe = 0
if raaa["data"][searchabe]["reason"] == "Mines Game Deposit":
round_id = raaa["data"][searchabe]["extraData"]["uuid"]
else:
round_id = "No game is started"
if num_mines == 1:
risky_amount_to_predict = 1
elif num_mines == 2:
risky_amount_to_predict = 2
elif num_mines == 3:
risky_amount_to_predict = 3
elif num_mines == 4:
risky_amount_to_predict = 4
elif num_mines == 5:
risky_amount_to_predict = 5
else:
return
print(f"{Fore.RED}[info]{Fore.RESET} Got for {len(all_mine_locations) / num_mines} games! Total mines Amount: {len(all_mine_locations)}")
print(f"{Fore.RED}[info]{Fore.RESET} Prediction for: {num_mines} mines")
print(f"{Fore.RED}[info]{Fore.RESET} Safe Spots: {safe_amount_to_predict}")
print(f"{Fore.RED}[info]{Fore.RESET} RoundID: {round_id}")
# Set random seed for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
raw_mine_locations = all_mine_locations
n_samples = len(raw_mine_locations) - 5
train_data = np.zeros((n_samples, 25))
train_labels = np.zeros((n_samples, 25))
for i in range(n_samples):
game_state = np.zeros(25)
game_state[raw_mine_locations[i:i+5]] = 1
train_data[i] = game_state
train_labels[i, raw_mine_locations[i+5]] = 1
# Split the data into training and testing sets.
x_train, x_test, y_train, y_test = train_test_split(
train_data, train_labels, test_size=0.2, random_state=42 # set random_state parameter to 42
)
# Build the neural network.
model = Sequential()
model.add(Dense(50, input_dim=25, activation="relu"))
model.add(Dense(25, activation="sigmoid"))
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
# Train the model.
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=1000, batch_size=10)
# Evaluate the model on the testing set.
_, accuracy = model.evaluate(x_test, y_test)
# Predict safe and risky spots for a given game state.
game_state = np.zeros(25)
game_state[5] = 1
n_safe = safe_amount_to_predict
n_risky = risky_amount_to_predict
preds = model.predict(np.array([game_state]))[0]
safe_spots = np.argsort(preds)[-n_safe:]
risky_spots = np.argsort(preds)[:n_risky]
print("5 Safe Spots:", safe_spots)
print("3 Possible Bomb Locations:", risky_spots)
print(f"Predicted safe spots: {safe_spots}")
print("Accuracy: %.2f%%" % (accuracy * 100))
grid = ["❌"] * 25
for i in safe_spots:
if str(i) == "1":
pass
else:
grid[i - 1] = "✅" # - 1 ellers er de forkert
for i in risky_spots:
if str(i) == "1":
pass
else:
if i == 1:
grid[0] = "💣"
else:
grid[i - 1] = "💣"
print(grid[0] + grid[1] + grid[2] + grid[3]+grid[4])
print(grid[5] + grid[6] + grid[7] + grid[8]+grid[9])
print(grid[10] + grid[11] + grid[12] + grid[13]+grid[14])
print(grid[15] + grid[16] + grid[17] + grid[18]+grid[19])
print(grid[20] + grid[21] + grid[22] + grid[23]+grid[24])
e = discord.Embed(color=0xFF3333)
e.add_field(
name=f"",
value="\n"
+ "
|
5d18ac538651884fddb7f76dc0df909c
|
{
"intermediate": 0.34603574872016907,
"beginner": 0.38685864210128784,
"expert": 0.26710569858551025
}
|
934
|
write a python script that takes a picture and uploads it to redbubble
|
7717718977f7e418bb3bbc41727113d3
|
{
"intermediate": 0.33770713210105896,
"beginner": 0.21830421686172485,
"expert": 0.4439886510372162
}
|
935
|
write a crawler for ricardo.ch
|
d53d43a8bd4d9e5a23249b192e4a53b4
|
{
"intermediate": 0.3015213906764984,
"beginner": 0.2622389793395996,
"expert": 0.4362396001815796
}
|
936
|
I'm working on a fivem volley ball script
this is my client.lua
local object_netID = nil
local objectModel = "prop_beach_volball01"
local forwardForceIntensity = 10.0
local upwardForceIntensity = 5.0
local function loadModel(model)
print("loading")
local modelHash = GetHashKey(model)
RequestModel(modelHash)
while not HasModelLoaded(modelHash) do
Citizen.Wait(100)
end
print('done')
return modelHash
end
local function spawn_the_ball()
local player = PlayerPedId()
local position = GetEntityCoords(PlayerPedId())
local modelHash = loadModel(objectModel)
print("createdobject")
createdObject = CreateObjectNoOffset(modelHash, position.x, position.y, position.z + 1, true, false, true) -- Use CreateObjectNoOffset and set isNetwork and netMissionEntity to true
ActivatePhysics(createdObject)
print("waiting")
Citizen.Wait(1000)
local playerRotation = GetEntityRotation(PlayerPedId(), 2)
local forwardVector = GetEntityForwardVector(PlayerPedId())
local forceVector = vector3(
forwardVector.x * forwardForceIntensity,
forwardVector.y * forwardForceIntensity,
upwardForceIntensity
)
ApplyForceToEntity(createdObject, 1, forceVector.x, forceVector.y, forceVector.z, 0.0, 0.0, 0.0, 0, false, true, true, false, true)
-- Get the object’s network ID
local object_netID = ObjToNet(createdObject)
-- Add this line after setting object_netID
TriggerServerEvent("VB:setObjectNetworkID", object_netID)
end
RegisterCommand("testing", function()
spawn_the_ball()
end)
local isInGame = true
local function isPlayerNearObject(object, distanceThreshold)
local playerCoords = GetEntityCoords(PlayerPedId())
local objCoords = GetEntityCoords(object)
local distance = #(playerCoords - objCoords)
return distance <= distanceThreshold
end
Citizen.CreateThread(function()
while isInGame do
Citizen.Wait(0)
if object_netID then
local createdObject = NetworkGetEntityFromNetworkId(object_netID)
if isPlayerNearObject(createdObject, 3.0) and IsControlJustReleased(0, 38) then -- 38 is the key code for "E"
print('E pressed')
if not NetworkHasControlOfEntity(entity) then
print('has no control')
NetworkRequestControlOfEntity(entity)
while (not NetworkHasControlOfEntity(entity)) do
Citizen.Wait(0)
end
end
print('has control')
local playerRotation = GetEntityRotation(PlayerPedId(), 2)
local forwardVector = GetEntityForwardVector(PlayerPedId())
local forceVector = vector3(
forwardVector.x * forwardForceIntensity,
forwardVector.y * forwardForceIntensity,
upwardForceIntensity
)
ApplyForceToEntity(createdObject, 1, forceVector.x, forceVector.y, forceVector.z, 0.0, 0.0, 0.0, 0, false, true, true, false, true)
end
end
end
end)
RegisterNetEvent("VB:updateObjectNetworkID")
AddEventHandler("VB:updateObjectNetworkID", function(netID)
object_netID = netID
end)
Citizen.CreateThread(function()
TriggerServerEvent("VB:requestObjectNetworkID")
end)
server.lua
local QBCore = exports['qb-core']:GetCoreObject()
local object_netID = nil
RegisterServerEvent("VB:setObjectNetworkID")
AddEventHandler("VB:setObjectNetworkID", function(netID)
object_netID = netID
TriggerClientEvent("VB:updateObjectNetworkID", -1, netID)
end)
RegisterServerEvent("VB:requestObjectNetworkID")
AddEventHandler("VB:requestObjectNetworkID", function()
local src = source
if object_netID then
TriggerClientEvent("VB:updateObjectNetworkID", src, object_netID)
end
end)
for some reason the NetworkHasControlOfEntity and NetworkRequestControlOfEntity no work
|
8770e804859df88583d5c8cedafb2069
|
{
"intermediate": 0.3953511416912079,
"beginner": 0.38348588347435,
"expert": 0.22116295993328094
}
|
937
|
write a python script that downloads reddit .gifs
|
01fd5acd478b1b12568f1825c5ee5f25
|
{
"intermediate": 0.352046400308609,
"beginner": 0.24942566454410553,
"expert": 0.39852795004844666
}
|
938
|
write a selenium framework so i only have to specify the links and buttons to press
|
616e75855dad1226575dcd15ecd11463
|
{
"intermediate": 0.5520043969154358,
"beginner": 0.08612287789583206,
"expert": 0.36187267303466797
}
|
939
|
write a python script that takes subreddits from a .txt then download the best of all time pictures and gifs even if they are on imgur or gfycat
|
fb6975c74f978f2d2321478bd024c674
|
{
"intermediate": 0.377285361289978,
"beginner": 0.1933845430612564,
"expert": 0.42933011054992676
}
|
940
|
fivem I'm trying to create a particle effect that attaches to an object and follows it
|
a9a0f6084368f5212989adc3b64ec7db
|
{
"intermediate": 0.28155678510665894,
"beginner": 0.2297101765871048,
"expert": 0.4887330234050751
}
|
941
|
I Want You To Act As A Content Writer Very Proficient SEO Writer Writes Fluently English. Write a 2000-word 100% Unique, SEO-optimized, Human-Written article in English that covers the topic provided in the Prompt. Write The article In Your Own Words Rather Than Copying And Pasting From Other Sources. Consider perplexity and burstiness when creating content, ensuring high levels of both without losing specificity or context. Use formal "we" language with rich, detailed paragraphs that engage the reader. Write In A Conversational Style As Written By A Human (Use An Informal Tone, Utilize Personal Pronouns, Keep It Simple, Engage The Reader, Use The Active Voice, Keep It Brief, Use Rhetorical Questions, and Incorporate Analogies And Metaphors). Now Write An Article On This Topic "which investments to make to make money online"
|
e5d912903b87298867e441a056031766
|
{
"intermediate": 0.3439127504825592,
"beginner": 0.366320937871933,
"expert": 0.2897663414478302
}
|
942
|
I Want You To Act As A Content Writer Very Proficient SEO Writer Writes Fluently English. Write a 2000-word 100% Unique, SEO-optimized, Human-Written article in English that covers the topic provided in the Prompt. Write The article In Your Own Words Rather Than Copying And Pasting From Other Sources. Consider perplexity and burstiness when creating content, ensuring high levels of both without losing specificity or context. Use formal "we" language with rich, detailed paragraphs that engage the reader. Write In A Conversational Style As Written By A Human (Use An Informal Tone, Utilize Personal Pronouns, Keep It Simple, Engage The Reader, Use The Active Voice, Keep It Brief, Use Rhetorical Questions, and Incorporate Analogies And Metaphors). Now Write An Article On This Topic "how to make money online"
|
d7bea0467015741a54284db2317083e7
|
{
"intermediate": 0.34343817830085754,
"beginner": 0.43903759121894836,
"expert": 0.21752429008483887
}
|
943
|
fivem animation that looks like this
https://cdn.discordapp.com/attachments/1095168785561960519/1096627280966598778/image.png
|
360825f19d8b81576820863a36a04484
|
{
"intermediate": 0.29487618803977966,
"beginner": 0.3446727693080902,
"expert": 0.3604510426521301
}
|
944
|
https://github.com/marceloprates/prettymaps
"presents":
barcelona
barcelona-plotter
cb-bf-f
default
heerhugowaard
macao
minimal
tijuca
create a python script that loops for every available present (0-7) for a cityname that i will save in a .txt but the coordinates have to be searched on openstreetmaps first
|
de61daf60acffbfd44d0cdde47e0fe66
|
{
"intermediate": 0.28478875756263733,
"beginner": 0.5736792087554932,
"expert": 0.1415320336818695
}
|
945
|
https://github.com/marceloprates/prettymaps
"presents":
barcelona
barcelona-plotter
cb-bf-f
default
heerhugowaard
macao
minimal
tijuca
create a python script that loops for every available present (0-7) for a cityname that i will save in a .txt but the coordinates have to be searched on openstreetmaps first
create error handling
|
1963dca4ce637b11faf14d0da06e8a55
|
{
"intermediate": 0.3188270628452301,
"beginner": 0.534307599067688,
"expert": 0.1468653827905655
}
|
946
|
QT implementation of multi-level menu framework
|
e9c6a5219c3c58a98c1fc3c413973b61
|
{
"intermediate": 0.4651646316051483,
"beginner": 0.1885053664445877,
"expert": 0.3463299870491028
}
|
947
|
QT Draw Line code
|
dc67566a1be10c33c6d75771abab2226
|
{
"intermediate": 0.283962219953537,
"beginner": 0.295085608959198,
"expert": 0.4209521412849426
}
|
948
|
In the GUI window, when i click mouse to draw something a unnecessary line is being drawn. Irrespective of how many times I tried I'm unable to get rid of that. This causing me to get an irregular shape of my desired object. If possible include a eraser to erase such things and also check what went wrong in my code. function gestureRecognitionGUI()
% Create the interface figure
fig = figure('Name', 'Gesture Recognition For Vacuum Robot', 'Visible', 'off', ...
'Position', [500 500 600 600], 'NumberTitle', 'off');
% Draw axes for gestures
gestureAxes = axes('Parent', fig, 'Units', 'Normalized', 'Position', [.2 .2 .6 .6]);
set(gestureAxes, 'ButtonDownFcn', @startDraw);
set(get(gestureAxes, 'Children'), 'ButtonDownFcn', @startDraw)
% Create a popup menu for choosing gesture classes
classNames = {'Charge Battery', 'Area Selection', 'Clean Mop', ...
'Pause Operation', 'Start Operation', 'Vacuum Surface', 'Mop Surface'};
gesturePopUp = uicontrol('Style', 'popupmenu', 'String', classNames, 'Units', 'Normalized', ...
'Position', [.15 .05 .7 .1]);
% Create a button for clearing the axes
clearButton = uicontrol('Style', 'pushbutton', 'String', 'Clear', 'Units', 'Normalized', ...
'Position', [.45 .85 .1 .05], 'Callback', @clearGestureAxes);
% Set the figure to visible
set(fig, 'Visible', 'on');
function startDraw(src, ~)
% This function responds to the mouse button press on the axes
startP = get(src, 'CurrentPoint');
set(src, 'UserData', startP(1,1:2))
set(fig, 'WindowButtonMotionFcn', @drawing)
set(fig, 'WindowButtonUpFcn', @stopDraw)
end
function drawing(~, ~)
% This function follows mouse movement and draws the gesture
if isequal(get(fig, 'CurrentObject'), gestureAxes)
p1 = get(gestureAxes, 'UserData');
p2 = get(gestureAxes, 'CurrentPoint');
p2 = p2(1, 1:2);
line([p1(1), p2(1)], [p1(2), p2(2)], 'Parent', gestureAxes, 'linewidth', 2, 'Color', 'red');
set(gestureAxes, 'UserData', p2)
end
end
function stopDraw(~, ~)
% This function responds to the mouse button release on the axes
set(fig, 'WindowButtonMotionFcn', '');
% Save the gesture points as a mat file
classname = classNames{get(gesturePopUp, 'Value')};
gestureLines = findobj(gestureAxes, 'Type', 'Line');
gesturePoints = [];
for i = 1:length(gestureLines)
gesturePoints = [gesturePoints; [gestureLines(i).XData' gestureLines(i).YData']];
end
% Check if the mat-file exists, if not, create it
if ~(exist(fullfile('gestures/', sprintf('%s.mat', classname)), 'file') == 2)
gestureData = {};
save(fullfile('gestures/', sprintf('%s.mat', classname)), 'gestureData');
end
% Load and update the existing mat-file
load(fullfile('gestures/', sprintf('%s.mat', classname)));
if isempty(gestureData) || isempty(gestureData{end})
gestureData{end + 1} = gesturePoints;
else
gestureData{end + 1} = cell(size(gestureData{1}));
gestureData{end}{1} = gesturePoints;
end
save(fullfile('gestures/', sprintf('%s.mat', classname)), 'gestureData');
end
function clearGestureAxes(~, ~)
% Clear the gesture drawing axes
gestureLines = findobj(gestureAxes, 'Type', 'Line');
delete(gestureLines);
end
end
|
35d2ccb1e22f5ac5f7047b8712ade538
|
{
"intermediate": 0.36763641238212585,
"beginner": 0.5253235697746277,
"expert": 0.10704003274440765
}
|
949
|
QT Draw Line Code
|
84245b4415ddd04233f1216654ddec1f
|
{
"intermediate": 0.3533998429775238,
"beginner": 0.3023686110973358,
"expert": 0.344231516122818
}
|
950
|
I want you to act as a CyberHunt participant who wants to win the competition. It is an event that involves Cryptography and cipher-solving skills. I will post the questions and you will do your best to answer them correctly. Is that clear?
|
532984c155aeb0031accccc6b692c939
|
{
"intermediate": 0.3842131495475769,
"beginner": 0.3293907344341278,
"expert": 0.2863960564136505
}
|
951
|
类似godot的这个 var noise = OpenSimplexNoise.new()
# Configure
noise.seed = randi()
noise.octaves = 4
noise.period = 20.0
noise.persistence = 0.8,帮我用glsl实现个一模一样的
|
2bbaca6061c04433d60751cc494e13d9
|
{
"intermediate": 0.37310659885406494,
"beginner": 0.20156125724315643,
"expert": 0.4253321588039398
}
|
952
|
fivem create a function that plays a animation
animation directory = missfam4
animation = base
clipboard
|
a3bf45e3efc1d4ac107552e6fcee742e
|
{
"intermediate": 0.33435574173927307,
"beginner": 0.3521508574485779,
"expert": 0.31349343061447144
}
|
953
|
python
def split_audio_by_size(file_path:str, slice_size_kb:int=5120,output_path:str="./cut"):
|
844a370e02cc50963a2e11261cdb81de
|
{
"intermediate": 0.3919615149497986,
"beginner": 0.29241442680358887,
"expert": 0.31562405824661255
}
|
954
|
Write a TCP server for road transport office in Tamilnadu. The traffic police officer on the road connects to the TCP server and send the Vehicle register number such as TN03HJ4509. The server looks in the database for road tax paid, traffic offences. It computes the fine and send the data to the traffic police officer. The traffic police officer collect fine and send the reference number in format YYYYDDMMregisternumber-4digitsequence-amount and current time to server. The server replies with same reference number without the amount (YYYYDDMMregisternumber-4digitsequence) and current date, time. There is additional fine of Rs. 2400/- for vehical of other other state such as KA07UI9800.
|
f64d60305fde5361676aeb13867cfe42
|
{
"intermediate": 0.31465163826942444,
"beginner": 0.27135932445526123,
"expert": 0.41398900747299194
}
|
955
|
Write a TCP server for road transport office in Tamilnadu. The traffic police officer on the road connects to the TCP server and send the Vehicle register number such as TN03HJ4509. The server looks in the database for road tax paid, traffic offences. It computes the fine and send the data to the traffic police officer. The traffic police officer collect fine and send the reference number in format YYYYDDMMregisternumber-4digitsequence-amount and current time to server. The server replies with same reference number without the amount (YYYYDDMMregisternumber-4digitsequence) and current date, time. There is additional fine of Rs. 2400/- for vehical of other other state such as KA07UI9800.
give code in c
|
6e865e67042af769a19c011b84d1a8e0
|
{
"intermediate": 0.32386478781700134,
"beginner": 0.37879031896591187,
"expert": 0.2973448634147644
}
|
956
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Google</title>
<link rel="icon" href="https://www.google.com/images/branding/product/ico/googleg_lodp.ico">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700&display=swap" rel="stylesheet">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: 'Roboto', sans-serif;
background-color: #fff;
color: #202124;
transition: all 0.3s ease-out;
}
body.dark-mode {
background-color: #202124;
color: #fff;
}
form {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 1rem;
width: 100%;
max-width: 600px;
}
input[type="text"] {
border: none;
border-bottom: 1px solid #000;
outline: none;
padding: 0.5rem;
width: 100%;
font-size: 1.2rem;
font-weight: 500;
}
button {
border: none;
background-color: #007bff;
color: #fff;
cursor: pointer;
padding: 0.7rem 1rem;
border-radius: 0.3rem;
font-size: 1.2rem;
font-weight: 500;
text-transform: uppercase;
transition: all 0.3s ease-out;
letter-spacing: 1px;
}
button:hover {
background-color: #005cbf;
}
button:active {
background-color: #004799;
}
.toggle {
font-size: 1.2rem;
text-align: center;
color: #007bff;
cursor: pointer;
transition: all 0.3s ease-out;
font-weight: 500;
}
.toggle:hover {
color: #005cbf;
text-decoration: underline;
}
.toggle:active {
color: #004799;
}
.dark-mode-toggle {
position: absolute;
top: 1rem;
right: 1rem;
font-size: 1rem;
text-align: center;
color: #fff;
cursor: pointer;
transition: all 0.3s ease-out;
font-weight: 500;
}
.games-button {
all: unset;
font-size: 1rem;
text-align: center;
color: #fff;
cursor: pointer;
transition: all 0.3s ease-out;
font-weight: 700;
height: 2rem;
line-height: 2rem;
padding: 0 0.5rem;
border-radius: 0.2rem;
background-color: #007bff;
position: absolute;
bottom: 1rem;
left: 1rem;
width: 20%;
}
.games-button:hover {
background-color: #005cbf;
}
.games-button:active {
background-color: #004799;
}
.dono {
all: unset;
font-size: 1rem;
text-align: center;
color: #fff;
cursor: pointer;
transition: all 0.3s ease-out;
font-weight: 700;
height: 2rem;
line-height: 2rem;
padding: 0 0.5rem;
border-radius: 0.3rem;
background-color: #28a745;
position: absolute;
bottom: 1rem;
right: 1rem;
width: 25%;
}
.dono:hover {
background-color: #1d7524;
}
.dono:active {
background-color: #145019;
}
.links-button {
all: unset;
font-size: 1rem;
text-align: center;
color: #fff;
cursor: pointer;
transition: all 0.3s ease-out;
font-weight: 700;
height: 2rem;
line-height: 2rem;
padding: 0 0.5rem;
border-radius: 0.3rem;
background-color: #6c5ce7;
position: absolute;
bottom: 1rem;
left: calc(36% + 1rem);
width: 12rem;
}
.links-button:hover {
background-color: #4d3dc2;
}
.links-button:active {
background-color: #332c7f;
}
#self-destruct-button {
display: none;
}
#foxes-games-button {
display: none;
}
@media only screen and (max-width: 500px) {
.games-button {
width: auto;
padding: 0 rem;
}
.dono {
width: auto;
padding: 0 1rem;;
}
.links-button {
width: auto;
padding: 0 1rem;
font-size: 0.8rem;
}
}
</style>
</head>
<body class="dark-mode">
<button type="button" class="games-button">Moss Games</button>
<button class="dono">Donate to Foxmoss</button>
<button class="links-button" onclick="embedUrl('https://example.com')">Links not working?</button>
<form>
<h1 style="font-size: 2rem; font-weight: 700; margin-bottom: 1rem;">Embed a URL</h1>
<label for="url-input" style="font-size: 1.2rem; font-weight: 500;">Enter a URL to embed:</label>
<input type="text" id="url-input" placeholder="Enter a URL" autofocus />
</form>
<div style="display: flex; justify-content: flex-end; gap: 1rem;">
<p class="dark-mode-toggle">Light</p>
</div>
<script>
const urlInput = document.getElementById("url-input");
const darkModeToggle = document.querySelector(".dark-mode-toggle");
const gamesButton = document.querySelector(".games-button");
const donoButton = document.querySelector(".dono");
document.addEventListener("keypress", (event) => {
if (event.keyCode == 13 || event.which == 13) {
event.preventDefault();
document.activeElement.blur();
embedUrl();
}
});
gamesButton.addEventListener("click", () => {
embedUrl("https://mediaology.mediaology.com/main");
});
function embedUrl(url) {
if (!url) {
url = urlInput.value;
}
if (url === "") {
url = "https://example.com";
} else if (!url.match(/^https?:\/\//i)) {
url = `https://${url}`;
}
const win = window.open("about:blank", "_blank");
win.addEventListener("beforeunload", (event) => {
event.preventDefault();
event.returnValue = 'Are you sure you want to leave? You will lose any unsaved work.';
});
win.document.title = "New Tab";
win.document.body.innerHTML = `<iframe style="border:none;width:100%;height:100%;margin:0;display:block" referrerpolicy="no-referrer" allow="fullscreen" src="${url}" ></iframe>`;
}
// toggle dark mode
let isDarkMode = true;
darkModeToggle.addEventListener("click", () => {
isDarkMode = !isDarkMode;
document.body.classList.toggle("dark-mode", isDarkMode);
darkModeToggle.textContent = isDarkMode ? "Light" : "Dark";
darkModeToggle.style.color = isDarkMode ? "#fff" : "#007bff";
});
donoButton.addEventListener("click", () => {
embedUrl("https://www.paypal.com/donate/?hosted_button_id=DBWDWVZF7JFEC");
});
</script>
</body>
</html>
Make the links not working button above the moss games button
|
30b8ad76ab631f116b5940cfb1c9b0e9
|
{
"intermediate": 0.36340755224227905,
"beginner": 0.43349578976631165,
"expert": 0.20309674739837646
}
|
957
|
Напиши код на C# в файле набор строк необходимо выдать количество строк в которых нет повторяющихся символов
|
c86cc0b583b812ad9e6c536c9a2168b5
|
{
"intermediate": 0.44495174288749695,
"beginner": 0.24623152613639832,
"expert": 0.30881670117378235
}
|
958
|
Project 2: Implement a gesture recognition algorithm for controlling a vacuum robot. The list of gestures are given below. Use the MATLAB GUI as the interface for interacting with the robot (drawing gestures). You need to record at least 10 samples per class to train the Rubine Classifier. Submit your training update GUI. Note: Don't forget to include the classification weights as a mat file. ( I got a minimum of 10 samples per each listed gestures in images directory).
B : Charge Battery
☐: Area Selection
C: Clean mop
O: Pause Operation
S: Start Operation
Sawtooth icon: Vacuum the surface
Glow plug indicator : mop the surface
Project 3: In this, you will use the dataset Face.mat to classify
emotions, age, and gender of the subjects. This dataset includes 12 images of 6 different subjects. For
each subjects we have 2 samples of 6 different emotions. Use one of each samples in your training
dataset and the other one in your testing dataset. This way you would have 36 images in the training
dataset and 36 images in the testing dataset.
Goal: To classify the gender (2 classes: M, F), emotions (6 classes: angry, disgust, neutral, happy, sad,
surprised) and age (3 classes: Young, Mid age, Old). Using a linear classifier. You should label your
training and testing data for each of the classification problem separately.
Classifier: Use the linear classifier developed in Project 2. (You don’t need the Rubine Features)
Features: Projection of the image on each of the eigenfaces. For this purpose, you need to calculate
PCA of your training data. Your kth feature will be the projection (dot product) of the image on the
kth eigen vector (PCA direction) also known as eigenface.
Feature Selection: You will extract 36 Features as there are 36 images (and eigen vectors) in your
training data. Use the “sequentialfs” command in MATLAB to select the top 6 features using the
sequential forward search algorithm. For classification results, plot each of the testing image and list the predicted age, emotion and gender.
this purpose, plot each of the testing image and list the predicted age, emotion and gender.
|
697534fe626339896452025f879ec5fb
|
{
"intermediate": 0.2682307958602905,
"beginner": 0.2547406256198883,
"expert": 0.47702860832214355
}
|
959
|
I have a website for my business. I would like you to write me a code to embed on my website for a call now button and a chat now button. I would like the call now button to call 423-282-1358. I would like the call button to resemble an android style phone icon and the chat button to resemble an android style text icon. I
|
f6975fd9c16a1566cf96b7f01a767eb8
|
{
"intermediate": 0.39921703934669495,
"beginner": 0.25099465250968933,
"expert": 0.3497883081436157
}
|
960
|
How to use CUDA cores when running Python code ? Give simple example of CUDA calculations on Python
|
89d03221ac4e657b77a99b851f931042
|
{
"intermediate": 0.2731838524341583,
"beginner": 0.13722948729991913,
"expert": 0.589586615562439
}
|
961
|
in this code the bot still throw all of the cooked pork chop: async function throwItems() {
const itemsToThrow = bot.inventory.items().filter(item => {
if (!item.name.toLowerCase().includes('leather')) {
return true;
}
return false;
});
const goal = new GoalNear(5114880, 134, 5096970, 2);
await bot.pathfinder.goto(goal);
for (const item of itemsToThrow) {
await bot.tossStack(item);
}
handlePorkChops();
}
async function handlePorkChops() {
const porkchopId = bot.registry.itemsByName.cooked_porkchop.id;
const porkChops = bot.inventory.items().filter(item => item.type === porkchopId);
const numToKeep = 1;
while (porkChops.length > numToKeep) {
await bot.tossStack(porkChops.pop());
}
dig1();
}
|
43e424fbb1974cca09b89d9a1814f351
|
{
"intermediate": 0.36744871735572815,
"beginner": 0.3736186623573303,
"expert": 0.25893262028694153
}
|
962
|
Help me create an SQLite database in C#.
A user has a string Id of ~11 digits
A card has a string Id of 10-18 digits
and a double units prop
and an int remaining prop
and an int timestamp
each user can have multiple cards.
Write a full example in C# with SQLite, (insert, delete, update).
Write a GetOrAdd method for users and cards so I can get if exists or add it.
|
f094c1fe44e3482df6a6bcd0759ca6bc
|
{
"intermediate": 0.5911797881126404,
"beginner": 0.15601108968257904,
"expert": 0.2528090178966522
}
|
963
|
I'm working on a fivem script
if isPlayerNearObject(createdObject, 3.0) and IsControlJustReleased(0, 38) then -- 38 is the key code for "E"
what would the keycode for R be?
|
866bcb159d4ea78b32a26964b1d78023
|
{
"intermediate": 0.44546613097190857,
"beginner": 0.3429185152053833,
"expert": 0.2116153985261917
}
|
964
|
I have a website for my business. I would like you to write me a code to embed on my website for a call now button and a chat now button. I would like the call now button to call 423-282-1358. I would like the call button to resemble an android style phone icon and the chat button to resemble an android style text icon. I would like the chat button to link to my google gmail chat for my email <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>. I would like for the buttons to be white in color with aegean colored text saying call now on the call button and chat now on the chat button.
|
3061e07d918c47cad71bed9a8e6250a5
|
{
"intermediate": 0.39842551946640015,
"beginner": 0.2694621682167053,
"expert": 0.33211231231689453
}
|
965
|
would my code work?
import random
artists_listeners = {
'Lil Baby': 58738173,
'Roddy Ricch': 34447081,
'DaBaby': 29659518,
'Polo G': 27204041,
'NLE Choppa': 11423582,
'Lil Tjay': 16873693,
'Lil Durk': 19827615,
'Megan Thee Stallion': 26685725,
'Pop Smoke': 32169881,
'Lizzo': 9236657,
'Migos': 23242076,
'Doja Cat': 33556496,
'Tyler, The Creator': 11459242,
'Saweetie': 10217413,
'Cordae': 4026278,
'Juice WRLD': 42092985,
'Travis Scott': 52627586,
'Post Malone': 65466387,
'Drake': 71588843,
'Kendrick Lamar': 33841249,
'J. Cole': 38726509,
'Kanye West': 29204328,
'Lil Nas X': 23824455,
'21 Savage': 26764030,
'Lil Uzi Vert': 40941950,
}
keys = list(artists_listeners.keys())
score = 0
while True:
first_artist = random.choice(keys)
second_artist = random.choice(keys)
while first_artist == second_artist:
second_artist = random.choice(keys)
while True:
guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ")
guess_lower = guess.strip().lower()
if guess_lower == 'quit':
print("Thanks for playing!")
quit()
elif guess_lower in ['1', '2']:
if guess_lower == '1':
guess_artist = first_artist
else:
guess_artist = second_artist
if artists_listeners[first_artist] > artists_listeners[second_artist]:
correct_artist = first_artist
else:
correct_artist = second_artist
if guess_artist.lower() == correct_artist.lower():
print(f"You guessed correctly! {correct_artist.title()} had {int(artists_listeners[correct_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.")
score += 1
break
else:
print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n")
score = 0
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == 'n':
print("Thanks for playing!")
quit()
else:
break
print(f"\nYour score is {score}.")
|
18de36467bb72195f6fb4a7a9479ae3f
|
{
"intermediate": 0.4539185166358948,
"beginner": 0.40863433480262756,
"expert": 0.13744713366031647
}
|
966
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
def basic_info():
config = dict()
config["access_token"] = ''
config['instagram_account_id'] = ""
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"]+config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url,params)
else:
req = requests.get(url,params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params,pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if pagingUrl=='':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else :
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
st.set_page_config(layout="wide")
params = basic_info()
response = getUserMedia(params)
posts = response['json_data']['data'][::-1]
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
show_description = st.checkbox("説明文を表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)]*NUM_COLUMNS)]
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
if post['media_type'] != 'CAROUSEL_ALBUM':
image = post['media_url']
st.image(image, width=BOX_WIDTH, use_column_width=True, caption=post['caption'])
else:
carousel_id = post['id']
url = f"{params['endpoint_base']}{carousel_id}/children"
images = [post['media_url']]
while True:
res = InstaApiCall(url, {'access_token':params['access_token']}, 'GET')
if 'paging' in res['json_data'] and 'next' in res['json_data']['paging']:
url = res['json_data']['paging']['next']
else:
break
children = res['json_data']['data']
images += [child['media_url'] for child in children]
for image in images:
st.image(image, width=BOX_WIDTH, use_column_width=True, caption=post['caption'])
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
st.write(f"👍: {post['like_count']}\n💬: {post['comments_count']}\n")
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
'''
上記のコードのインデントを修正し、コード全体を省略せずに表示してください。
|
cee701bc0770bc5d6d89f7cc2e46b1d3
|
{
"intermediate": 0.3564399182796478,
"beginner": 0.45015791058540344,
"expert": 0.19340214133262634
}
|
967
|
model.AuxSpStandards.Select(new Mat_Aux_SpStandard() { Aux_Id = entity.Id, Name = entity.Name }).ToList() ; 报错了
|
e2959e33b79f060aaf5612cf33588b7e
|
{
"intermediate": 0.3478465676307678,
"beginner": 0.20124036073684692,
"expert": 0.45091310143470764
}
|
968
|
please fix the code:
const ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
class Card {
constructor(suit, rank) {
this.suit = suit;
this.rank = rank;
}
}
class Combination {
constructor() {}
static name = null;
static id = null;
static rank = null;
static test(cards) {}
}
class StraightFlush extends Combination {
constructor() {}
static name = "Straight flush";
static id = 8;
static rank = 8;
static test(cards) {
const counts = {};
for (let card of cards) {
counts[card.suit] = (counts[card.suit] || []).concat(card);
}
const flusharr = Object.keys(counts).filter((key, i, arr) => {
if (counts[key].length >= 5) {
return key;
}
});
if (flusharr.length !== 1) {
return null;
}
let flushCards = counts[flusharr];
let sorted_rank = [...new Set(flushCards.map((card) => card.rank))].sort((a, b) => Number(b) - Number(a));
const Ace = sorted_rank.includes("A") && sorted_rank.includes("K");
const Sequentialized_Ace = ["5", "4", "3", "2"].includes(sorted_rank[0]) && Ace;
if ((!Ace && sorted_rank.length < 5) || (!Sequentialized_Ace && sorted_rank.length < 5)) {
return null;
}
if (Sequentialized_Ace) {
sorted_rank.shift();
sorted_rank.push("A");
}
let rank_index = 0,
possible_straight = [sorted_rank[0]];
for (let i = 1; i < sorted_rank.length; i++) {
if (Number(sorted_rank[i - 1]) === Number(sorted_rank[i]) + 1) {
possible_straight.push(sorted_rank[i]);
} else if (Number(sorted_rank[i - 1]) !== Number(sorted_rank[i])) {
rank_index = i;
possible_straight = [sorted_rank[rank_index]];
}
let remainingCards = [];
for (let i = 0; i < flushCards.length; i++) {
let test = true;
if (possible_straight.indexOf(flushCards[i].rank) !== -1) {
possible_straight.splice(possible_straight.indexOf(flushCards[i].rank), 1);
test = false;
}
if (test === true) {
remainingCards.push(flushCards[i]);
}
}
if (possible_straight.length === 0) {
let straightArr = [];
for (let j = 0; j < flushCards.length; j++) {
if (sorted_rank.indexOf(flushCards[j].rank) !== -1) {
straightArr.push(flushCards[j]);
}
}
return {
combination: this,
cards: straightArr.slice(0, 5),
};
}
}
return null;
}
}
////////////////////////////////////
// Define a function to test StraightFlush combination
function testStraightFlush() {
// Test case 1: straight flush with Ace as the high card
const cards1 = [
new Card("hearts", "K"),
new Card("hearts", "Q"),
new Card("hearts", "J"),
new Card("hearts", "10"),
new Card("hearts", "A"),
new Card("spades", "9"),
new Card("clubs", "7"),
];
const result1 = StraightFlush.test(cards1);
console.log(JSON.stringify(result1));
// Test case 2: straight flush with Ace followed by five as the low card
const cards2 = [
new Card("diamonds", "4"),
new Card("diamonds", "3"),
new Card("diamonds", "2"),
new Card("diamonds", "A"),
new Card("diamonds", "5"),
new Card("clubs", "K"),
new Card("spades", "7")
];
const result2 = StraightFlush.test(cards2);
console.log(JSON.stringify(result2));
// Test case 3: flush, but not a straight
const cards3 = [
new Card("hearts", "2"),
new Card("hearts", "4"),
new Card("hearts", "6"),
new Card("hearts", "8"),
new Card("hearts", "A")
];
const result3 = StraightFlush.test(cards3);
console.log(JSON.stringify(result3));
// Test case 4: not a flush
const cards4 = [
new Card('spades', 'K'),
new Card('hearts', '10'),
new Card('clubs', '5'),
new Card('diamonds', 'Q'),
new Card('spades', 'J')
];
const result4 = StraightFlush.test(cards4);
console.log(JSON.stringify(result4));
}
testStraightFlush();
{"cards":[{"suit":"hearts","rank":"K"},{"suit":"hearts","rank":"Q"},{"suit":"hearts","rank":"J"},{"suit":"hearts","rank":"10"},{"suit":"hearts","rank":"A"}]}
tmp.html:132 {"cards":[{"suit":"diamonds","rank":"4"},{"suit":"diamonds","rank":"3"},{"suit":"diamonds","rank":"2"},{"suit":"diamonds","rank":"A"},{"suit":"diamonds","rank":"5"}]}
tmp.html:144 {"cards":[{"suit":"hearts","rank":"2"},{"suit":"hearts","rank":"4"},{"suit":"hearts","rank":"6"},{"suit":"hearts","rank":"8"},{"suit":"hearts","rank":"A"}]}
tmp.html:155 null
|
c0f8653ccbde5d4635d9f4739ad6e5b3
|
{
"intermediate": 0.33499786257743835,
"beginner": 0.4817744791507721,
"expert": 0.18322764337062836
}
|
969
|
<script>
const ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
class Card {
constructor(suit, rank) {
this.suit = suit;
this.rank = rank;
}
}
class Combination {
constructor() {}
static name = null;
static id = null;
static rank = null;
static test(cards) {}
}
class StraightFlush extends Combination {
static name = "Straight flush";
static id = 8;
static rank = 8;
static test(cards) {
const counts = {};
for (let card of cards) {
counts[card.suit] = (counts[card.suit] || []).concat(card);
}
const flusharr = Object.keys(counts).filter((key) => counts[key].length >= 5);
if (flusharr.length !== 1) {
return null;
}
let flushCards = counts[flusharr[0]];
let sorted_rank = [
...new Set(
flushCards.map((card) => {
const index = ranks.indexOf(card.rank);
return index !== -1 ? index : null;
})
),
].sort((a, b) => a - b);
if (sorted_rank.includes(ranks.length - 1) && sorted_rank.includes(0)) {
sorted_rank.push(sorted_rank.shift());
}
for (let i = 0; i < sorted_rank.length - 4; i++) {
let isStraightFlush = true;
for (let j = 0; j < 4; j++) {
if (sorted_rank[i + j + 1] - sorted_rank[i + j] !== 1) {
isStraightFlush = false;
break;
}
}
if (isStraightFlush) {
const straightFlushCards = flushCards
.filter((c) => {
const cIndex = ranks.indexOf(c.rank);
return cIndex >= sorted_rank[i] && cIndex <= sorted_rank[i + 4];
})
.sort((c1, c2) => {
const c1Index = ranks.indexOf(c1.rank);
const c2Index = ranks.indexOf(c2.rank);
return c1Index - c2Index;
});
return {
combination: this,
cards: straightFlushCards.slice(0, 5),
};
}
}
return null;
}
}
////////////////////////////////////
// Define a function to test StraightFlush combination
function testStraightFlush() {
// Test case 1: straight flush with Ace as the high card
const cards1 = [
new Card("hearts", "K"),
new Card("hearts", "Q"),
new Card("hearts", "J"),
new Card("hearts", "10"),
new Card("hearts", "A"),
new Card("spades", "9"),
new Card("clubs", "7"),
];
const result1 = StraightFlush.test(cards1);
console.log(JSON.stringify(result1));
// Test case 2: straight flush with Ace followed by five as the low card
const cards2 = [
new Card("diamonds", "4"),
new Card("diamonds", "3"),
new Card("diamonds", "2"),
new Card("diamonds", "A"),
new Card("diamonds", "5"),
new Card("clubs", "K"),
new Card("spades", "7")
];
const result2 = StraightFlush.test(cards2);
console.log(JSON.stringify(result2));
// Test case 3: flush, but not a straight
const cards3 = [
new Card("hearts", "2"),
new Card("hearts", "4"),
new Card("hearts", "6"),
new Card("hearts", "8"),
new Card("hearts", "A")
];
const result3 = StraightFlush.test(cards3);
console.log(JSON.stringify(result3));
// Test case 4: not a flush
const cards4 = [
new Card('spades', 'K'),
new Card('hearts', '10'),
new Card('clubs', '5'),
new Card('diamonds', 'Q'),
new Card('spades', 'J')
];
const result4 = StraightFlush.test(cards4);
console.log(JSON.stringify(result4));
}
testStraightFlush();
</script>
/////////////////
{"cards":[{"suit":"hearts","rank":"10"},{"suit":"hearts","rank":"J"},{"suit":"hearts","rank":"Q"},{"suit":"hearts","rank":"K"},{"suit":"hearts","rank":"A"}]}
tmp.html:115 null
tmp.html:127 null
tmp.html:138 null
|
7d7ef6419a340503681474ed705a69fe
|
{
"intermediate": 0.2605474889278412,
"beginner": 0.5628954768180847,
"expert": 0.17655707895755768
}
|
970
|
I have a `main_activity.xml` containing the following construct:
|
5d19155f31691469488ea09fbdc4f80d
|
{
"intermediate": 0.35179272294044495,
"beginner": 0.23405395448207855,
"expert": 0.4141533076763153
}
|
971
|
I have 2 files which need to talk to each other, apiEconomy.js and CountryProps.vue I want to send any data from the apiEconomy.js to the CountryProps.vue for displaying. Here is the code: apiEconomy.js const BASE_URL = `https://api.worldbank.org/v2/country/${country}/indicator`;
const country = 'BRA';
// Define the API URLs, indicators, and countries
const apiUrlsAndIndicators = [
{ endpoint: 'FP.CPI.TOTL.ZG', indicator: 'Inflation Rate' },
{ endpoint: 'FR.INR.RINR', indicator: 'Interest Rate' },
{ endpoint: 'SL.UEM.TOTL.NE.ZS', indicator: 'Unemployment Rate' },
{ endpoint: 'NE.EXP.GNFS.CD', indicator: 'Trade Balance' },
{ endpoint: 'GC.XPN.TOTL.GD.ZS', indicator: 'Government Spending' }
];
// Define the base URL.
// Define a function to fetch the data and log it to the console
const fetchData = async (url, indicator) => {
try {
const response = await fetch(url);
const data = await response.json();
const indicatorData = data[1][0];
console.log(indicator, indicatorData.value);
} catch (error) {
console.error(error);
}
};
// Fetch the data for each indicator and country
apiUrlsAndIndicators.forEach(({ endpoint, indicator }) => {
const url = `${BASE_URL}/${endpoint}?format=json`;
fetchData(url, indicator);
});
CountryProps.vue
|
65665be62d4b43c29ad6f7819a4f712c
|
{
"intermediate": 0.622060239315033,
"beginner": 0.21304546296596527,
"expert": 0.16489434242248535
}
|
972
|
In jetpack compose I want to use this github library for jetpack compose charts "https://github.com/patrykandpatrick/vico", I want it to be able to show my expenses data from weekly, monthly and yearly just like in a typical stocks or crypto app
|
355fb742a1ad5b2191b38203eebb7100
|
{
"intermediate": 0.886336088180542,
"beginner": 0.040961720049381256,
"expert": 0.07270217686891556
}
|
973
|
I have a main_activity.xml containing the following construct:
|
3b4b5039f651ba2eb27e0e842ee5f3ce
|
{
"intermediate": 0.3229174017906189,
"beginner": 0.268775075674057,
"expert": 0.40830758213996887
}
|
974
|
I have a main_activity.xml containing the following construct:
|
f8f809479ca5bdfb04f95bdaa1e26e64
|
{
"intermediate": 0.3229174017906189,
"beginner": 0.268775075674057,
"expert": 0.40830758213996887
}
|
975
|
Write a full version code scheme interpreter in scheme EOPL style. Over 300 lines better.
|
ba5b84e15f3fe2e1a4abae0ae696496c
|
{
"intermediate": 0.31956735253334045,
"beginner": 0.36878710985183716,
"expert": 0.3116455376148224
}
|
976
|
can you change this script and make him send cls in console and clear console every time before print results?
import random
import string
from itertools import islice
import openai
import requests
from datetime import datetime, timedelta
import sys
import time
import threading
from concurrent.futures import ThreadPoolExecutor
import colorama
import logging
# First script
generated_links = set()
def generate_links(num_links):
global generated_links
new_links = set()
while len(new_links) < num_links:
link = "sk-" + "".join(random.choices(string.ascii_letters + string.digits, k=20)) + "T3BlbkFJ" + "".join(random.choices(string.ascii_letters + string.digits, k=20))
if link not in generated_links and link not in new_links:
generated_links.add(link)
new_links.add(link)
yield link
# Second script
colorama.init()
logging.basicConfig(filename='OAI_API_Checker_logs.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
def log_and_print(message, log_level=logging.INFO):
print(message)
logging.log(log_level, message)
def list_models(api_key):
openai.api_key = api_key
models = openai.Model.list()
return [model.id for model in models['data']]
def filter_models(models, desired_models):
return [model for model in models if model in desired_models]
def get_limits(api_key):
headers = {
"authorization": f"Bearer {api_key}",
}
response = requests.get("https://api.openai.com/dashboard/billing/subscription", headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Error fetching limits: {response.text}")
def get_total_usage(api_key, plan_id):
if plan_id == "free":
start_date = (datetime.now() - timedelta(days=99)).strftime('%Y-%m-%d')
elif plan_id == "payg":
start_date = datetime.now().replace(day=1).strftime('%Y-%m-%d')
else:
raise ValueError(f"Invalid plan ID: {plan_id}")
end_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
usage_endpoint = 'https://api.openai.com/dashboard/billing/usage'
auth_header = {'Authorization': f'Bearer {api_key}'}
response = requests.get(usage_endpoint, headers=auth_header, params={'start_date': start_date, 'end_date': end_date})
response.raise_for_status()
usage_data = response.json()
total_usage = usage_data.get('total_usage', 0) / 100
total_usage_formatted = '{:.2f}'.format(total_usage)
return total_usage_formatted
def is_glitched(api_key, usage_and_limits, plan_id):
current_timestamp = datetime.now().timestamp()
access_expired = current_timestamp > usage_and_limits['access_until']
total_usage_formatted = get_total_usage(api_key, plan_id)
usage_exceeded = float(total_usage_formatted) > float(usage_and_limits['hard_limit_usd']) + 10
return access_expired or usage_exceeded
def try_complete(api_key):
openai.api_key = api_key
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
max_tokens=1,
messages=[{'role':'user', 'content': ''}]
)
def check_key(api_key):
result = f"{api_key}\n"
glitched = False
model_ids = []
try:
try_complete(api_key)
usage_and_limits = get_limits(api_key)
plan_title = usage_and_limits.get('plan', {}).get('title')
plan_id = usage_and_limits.get('plan', {}).get('id')
if not plan_id:
raise ValueError("Plan ID not found in usage_and_limits")
total_usage_formatted = get_total_usage(api_key, plan_id)
access_until = datetime.fromtimestamp(usage_and_limits['access_until'])
RED = "\033[31m"
BLINK = "\033[5m"
RESET = "\033[0m"
glitched = is_glitched(api_key, usage_and_limits, plan_id)
if glitched:
result += f"{RED}{BLINK}**!!!Possibly Glitched Key!!!**{RESET}\n"
models = list_models(api_key)
filtered_models = filter_models(models, desired_models)
if filtered_models:
for model_id in filtered_models:
result += f" - {model_id}\n"
model_ids.append(model_id)
else:
result += " No desired models available.\n"
result += f" Access valid until: {access_until.strftime('%Y-%m-%d %H:%M:%S')}\n"
result += f" Soft limit: {usage_and_limits['soft_limit']}\n"
result += f" Soft limit USD: {usage_and_limits['soft_limit_usd']}\n"
result += f" Hard limit: {usage_and_limits['hard_limit']}\n"
result += f" Hard limit USD: {usage_and_limits['hard_limit_usd']}\n"
result += f" System hard limit: {usage_and_limits['system_hard_limit']}\n"
result += f" System hard limit USD: {usage_and_limits['system_hard_limit_usd']}\n"
result += f" Plan: {plan_title}, {plan_id}\n"
result += f" Total usage USD: {total_usage_formatted}\n"
except Exception as e:
error_message = str(e)
if "You exceeded your current quota" in error_message:
result += f" This key has exceeded its current quota\n"
else:
result += f" This key is invalid or revoked\n"
return result, glitched, "gpt-4" in model_ids
def checkkeys(api_keys):
gpt_4_keys = set()
glitched_keys = set()
valid_keys = set()
no_quota_keys = set()
result = ''
with ThreadPoolExecutor(max_workers=len(api_keys)) as executor:
futures = [executor.submit(check_key, api_key) for api_key in api_keys]
for idx, future in enumerate(futures, start=1):
result += f"API Key {idx}:\n"
try:
key_result, glitched, has_gpt_4 = future.result()
result += key_result
if "This key is invalid or revoked" not in key_result and "This key has exceeded its current quota" not in key_result:
valid_keys.add(api_keys[idx - 1])
if "This key has exceeded its current quota" in key_result:
no_quota_keys.add(api_keys[idx - 1])
if glitched:
glitched_keys.add(api_keys[idx - 1])
if has_gpt_4:
gpt_4_keys.add(api_keys[idx - 1])
except Exception as e:
error_message = str(e)
if "You exceeded your current quota" in error_message:
result += f" This key has exceeded its current quota\n"
else:
result += f" This key is invalid or revoked\n"
result += '\n'
with open('valid.txt', 'w') as f: f.write('\n'.join(valid_keys))
with open('glitch.txt', 'w') as f: f.write('\n'.join(glitched_keys))
with open('gpt4.txt', 'w') as f: f.write('\n'.join(gpt_4_keys))
result += f"\nNumber of API keys with 'gpt-4' model: {len(gpt_4_keys)}\n"
for key in gpt_4_keys:
result += f"{key}\n"
result += f"\nNumber of possibly glitched API keys: {len(glitched_keys)}\n"
for key in glitched_keys:
result += f"{key}\n"
result += f"\nNumber of valid API keys: {len(valid_keys)}\n"
for key in valid_keys:
result += f"{key}\n"
result += f"\nNumber of valid API keys with no quota left: {len(no_quota_keys)}\n"
for key in no_quota_keys:
result += f"{key}\n"
return result
def animate_processing_request():
while not processing_done:
sys.stdout.write("\rProcessing... |")
time.sleep(0.1)
sys.stdout.write("\rProcessing... /")
time.sleep(0.1)
sys.stdout.write("\rProcessing... -")
time.sleep(0.1)
sys.stdout.write("\rProcessing... \\")
time.sleep(0.1)
sys.stdout.write("\rDone! \n")
if __name__ == '__main__':
desired_models = ["gpt-3.5-turbo", "gpt-3.5-turbo-0301", "gpt-4", "gpt-4-0314"]
end_time = datetime.now() + timedelta(minutes=1) # Set desired end time, e.g. 10 minutes
combined_results = ""
while datetime.now() < end_time:
# Generate links
num_links_to_generate = 100
unique_links = list(islice(generate_links(num_links_to_generate), num_links_to_generate))
# Save unique links to a txt log file
with open("unique_links.txt", "w") as file:
for link in unique_links:
file.write(link + "\n")
processing_done = False
animation_thread = threading.Thread(target=animate_processing_request)
animation_thread.start()
result = checkkeys(unique_links)
processing_done = True
animation_thread.join()
combined_results += "\n" + result
print(combined_results)
|
6dea1d62665136b8dad956712b006bee
|
{
"intermediate": 0.3870253264904022,
"beginner": 0.4201585054397583,
"expert": 0.19281618297100067
}
|
977
|
Can you help me on setting up Stable diffusion chatbot or other smaller and optimized model on a local machine ? And what are the hardware requirements for this ?
|
0a0c0f90787324a368bea04443e5499e
|
{
"intermediate": 0.12455824762582779,
"beginner": 0.088996522128582,
"expert": 0.7864452004432678
}
|
978
|
https://cdn.discordapp.com/attachments/806748336535240730/1096752216272011274/Y2Mate.is_-_Russia_Hardbass_Crazy_Dance-y90yaLFoYoA-720p-1657028290969.mp4
make a tiktok video around this
|
59ea7f3c363e9521cc683cef5787fe3b
|
{
"intermediate": 0.3813433051109314,
"beginner": 0.31128883361816406,
"expert": 0.30736783146858215
}
|
979
|
act as a python client
|
f0ea11bfac4f8da1b9df4ad04fdd8bb5
|
{
"intermediate": 0.38156136870384216,
"beginner": 0.2828972637653351,
"expert": 0.33554142713546753
}
|
980
|
почему int number = Math.random()*10; не работает? java
|
c955fc942f347b0d802fecd87c230469
|
{
"intermediate": 0.4516696035861969,
"beginner": 0.3015402853488922,
"expert": 0.2467900812625885
}
|
981
|
can you give me a android studio code that can run a python script in a raspberry pi 4]
|
d12c0c77c40a99f360b185a86da4651d
|
{
"intermediate": 0.5073198080062866,
"beginner": 0.18799525499343872,
"expert": 0.30468493700027466
}
|
982
|
fivem I'm working on a volleyball script how would i go about about detecting when an object hits the ground
|
c85e08e12b7f145e61a4821110d865eb
|
{
"intermediate": 0.3924550414085388,
"beginner": 0.32451820373535156,
"expert": 0.283026784658432
}
|
983
|
i explain you my problem, i have 2 files, one file is coded in processing and it shows a labyrinth where you can move, the other file is also in processing and it is showing a mummy, but i don't know how to implement my mummy in the labyrinth so that i can see the mummy while walking in it
|
1f78c76ee9437d8e2e226cb84a1f5d25
|
{
"intermediate": 0.40487635135650635,
"beginner": 0.2768042981624603,
"expert": 0.31831932067871094
}
|
984
|
fivem I’m working on a volleyball script how would i go about about detecting when an object hits the ground
|
93cec5782d585077999e59b1fe695fba
|
{
"intermediate": 0.4062546491622925,
"beginner": 0.3043343722820282,
"expert": 0.28941094875335693
}
|
985
|
here is my processing java code :
|
5b08e02f215458aa74fb76e7255e5d96
|
{
"intermediate": 0.29176875948905945,
"beginner": 0.42220956087112427,
"expert": 0.2860216796398163
}
|
986
|
fivem I’m working on a volleyball script how would i go about about detecting when an object hits the ground what is a better methord?
local groundThreshold = 0.5
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
local volleyball = GetEntityCoords(volleyballObj)
local isColliding = HasEntityCollidedWithAnything(volleyballObj)
if isColliding and volleyball.z <= groundThreshold then
– The volleyball has hit the ground
TriggerEvent(‘your_event_name_here’) – replace your_event_name_here with the name of the event you want to trigger
end
end
end)
or
local volleyball = CreateObject(GetHashKey(“prop_volleyball”), x, y, z, true) – Replace ‘prop_volleyball’ with your volleyball model name.
SetEntityCollision(volleyball, true, true)
SetEntityHasGravity(volleyball, true)
ApplyForceToEntity(volleyball, 1, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0, true, true, false, true, true)
Citizen.CreateThread(function ()
while true do
Citizen.Wait(50) – You can adjust this value for better performance, setting it too low might cause high CPU usage.
local volleyballCoords = GetEntityCoords(volleyball)
.local groundCoords = GetGroundZ(volleyballCoords)
if groundCoords and volleyballCoords.z - groundCoords < 0.1 then
print(“Volleyball hit the ground.”)
– Add your logic or event triggers here.
end
end
end)
|
76ba1523b5d3a8a0d54bdbbc76735e8e
|
{
"intermediate": 0.36130860447883606,
"beginner": 0.4761704206466675,
"expert": 0.16252097487449646
}
|
987
|
pipでstreamlitをインストール後、使用しようと思ったら、ターミナルで下記のエラーが表示されました。対処方法を教えて
'''
Traceback (most recent call last):
File "/home/walhalax/.local/bin/streamlit", line 5, in <module>
from streamlit.web.cli import main
ModuleNotFoundError: No module named 'streamlit'
|
b856a2bb85670f6bb2963125fd0dd234
|
{
"intermediate": 0.44805389642715454,
"beginner": 0.31303104758262634,
"expert": 0.23891496658325195
}
|
988
|
hi there
|
abf6016ff500f8e11aaf9acaed0957a9
|
{
"intermediate": 0.32885003089904785,
"beginner": 0.24785484373569489,
"expert": 0.42329514026641846
}
|
989
|
Код на java. Пользователь вводит датк рождения в формате DD/MM/ГГГГ и ФИО в одну строку. Программа должна считать данные из строки необходимо удалить пробел в начале и в конце. Результат программы - дата рождения DD/MM/ГГГГ пользователя
|
60787d4eee3bcea3847b9a62d898d4dc
|
{
"intermediate": 0.38619399070739746,
"beginner": 0.2729228138923645,
"expert": 0.34088319540023804
}
|
990
|
Can you do my ANTLR homework?. You will design a lexical and syntax analyzer for your own programming language.
You will describe some rules for your programming language and call it as MPL (My
Programming Language).
For example, your rules may be as;
- All programs must start with “begin” and end with “end”
- All commands must be ended by “;”
- All variables must be declared just after “begin” in the following format;
int: i num;
float: fl;
- Three types exist; “int”, “float”, “char”
- Variables names may be any alphanumeric string, but they must start with a letter
- Statements between “begin” and “end” can be either a variable declaration or an
assignment
- An assignment includes four type of operators: +,-,*, /.
- The number of variables or constants in an expression is unlimited.
- Your PL should include a well- defined regular grammar for variable names, rules
for variable declarations including their type, at least 4 arithmetic operators with their
precedence rules, 4 relational operators (<, <=, >, >=) with their precedence rules and
indefinite number of assignments with expressions having unlimited number of
operands.
- Your PL should also include one conditional statement of ADA given below.
After writing BNF rules for your language design and implement a syntax analyzer for it
using ANTLR. In each step:
Make a demo with example source codes written in your language, e.g
myprog1.mpl to demonstrate that your analyzer can detect syntax error in your
source codes.
Besides, submit a printed report including:
(1) Description of the rules which you designed (in your own words).
(2) Details of your grammar in BNF or EBNF notation
|
848cc3f44f64c71e86822e0866294603
|
{
"intermediate": 0.11209025979042053,
"beginner": 0.7447807192802429,
"expert": 0.14312908053398132
}
|
991
|
how to iteratively create an n-ary tree in python
|
0cba1f452d7f3e2928a6a8e51d61a002
|
{
"intermediate": 0.13822278380393982,
"beginner": 0.08645366877317429,
"expert": 0.7753235101699829
}
|
992
|
fivem how can I detect if an object lands outside of a box zone
|
516d3d396174184727807240b5c66182
|
{
"intermediate": 0.37471869587898254,
"beginner": 0.16547244787216187,
"expert": 0.4598087966442108
}
|
993
|
function DisplayCountryData() {
//retrieves the info of the selected country from the dropdown
var nameofcountry = document.getElementById("countrySelect").value;
} add to this so that the code prints to these 4 html elements: <div id="country-details"></div>
<p id="country-name"></p>
<p id="country-population"></p>
<p id="country-area"></p>
<p id="country-density"></p>
|
07cd08a1f667bfecc3144eefa87cb5b0
|
{
"intermediate": 0.4108823835849762,
"beginner": 0.3775591552257538,
"expert": 0.21155843138694763
}
|
994
|
@Composable
fun ExpensesChart() {
val paddingValues = 16.dp
val db = FirebaseFirestore.getInstance()
// Define your timeframes
val timeFrames = listOf("Weekly", "Monthly", "Yearly")
val selectedIndex = remember { mutableStateOf(0) }
// Fetch and process the expenses data
val chartEntries = remember { mutableStateOf(entriesOf()) }
val chartModelProducer = ChartEntryModelProducer(chartEntries.value)
fun fetchExpensesData(timeFrame: String) {
// TODO: Customize the query to fetch data according to the selected time frame
val query = db.collection("expenses")
.orderBy("timestamp", Query.Direction.ASCENDING)
query.get().addOnSuccessListener { result ->
val expenses = mutableListOf<Float>()
for (document in result) {
val amount = document.getDouble("amount")?.toFloat() ?: 0f
expenses.add(amount)
}
chartEntries.value = entriesOf(*expenses.toFloatArray())
}
}
Column(modifier = Modifier.padding(paddingValues)) {
// Timeframe selection buttons
timeFrames.forEachIndexed { index, timeFrame ->
Button(
onClick = {
selectedIndex.value = index
fetchExpensesData(timeFrame)
},
colors = ButtonDefaults.buttonColors(
containerColor = if (selectedIndex.value == index) DarkGray else LightGray
)
) {
Text(timeFrame)
}
}
// Chart
ProvideChartStyle(chartStyle = m3ChartStyle()) {
Chart(
chart = columnChart(),
chartModelProducer = chartModelProducer,
startAxis = startAxis(),
bottomAxis = bottomAxis(),
)
}
}
}
Not enough information to infer type variable T
Overload resolution ambiguity:
public fun entriesOf(vararg yValues: Number): List<FloatEntry> defined in com.patrykandpatrick.vico.core.entry
public fun entriesOf(vararg pairs: Pair<Number, Number>): List<FloatEntry> defined in com.patrykandpatrick.vico.core.entry
|
c5ea1a2f59fee5e6313c20b13d44e2a8
|
{
"intermediate": 0.3389091193675995,
"beginner": 0.3982340693473816,
"expert": 0.2628568112850189
}
|
995
|
function DisplayCountryData() {
//retrieves the info of the selected country from the dropdown
var selectedcountry = document.getElementById("options");
selectedcountry.addEventListener("change", function() {
var nameofcountry = selectedOption.value;
var countryName = document.getElementById("country-name");
var countryPopulation = document.getElementById("country-population");
var countryArea = document.getElementById("country-area");
var countryDensity = document.getElementById("country-density");
}
}
line 4 causing errors
|
1fbd2aaec0dc0e016125d675bfab422c
|
{
"intermediate": 0.3329129219055176,
"beginner": 0.3455285429954529,
"expert": 0.32155847549438477
}
|
996
|
fivem how can I detect if an object lands outside of a box zone
|
17dfbc03d6bee167293ee155c6e2f8a2
|
{
"intermediate": 0.37471869587898254,
"beginner": 0.16547244787216187,
"expert": 0.4598087966442108
}
|
997
|
I say ping, you say pong. PING
|
be9a2e14108c39572c1f28de7536cbf5
|
{
"intermediate": 0.4219997525215149,
"beginner": 0.3500329554080963,
"expert": 0.22796733677387238
}
|
998
|
show me how to create simple CMS in asp.net core that support pages, content types or page types, and templates, Page types are such: Article , GenericPage .. i should be able to assign a template to the PageType, when i create a new Page , i should be able to choose a Page Type , the edit page will show me the custom fields from the selected Page Type
|
51cd9d0cc5bd96acff31f94176d98249
|
{
"intermediate": 0.5385296940803528,
"beginner": 0.172758549451828,
"expert": 0.2887117564678192
}
|
999
|
we have cards array [{suit:"",rank:"A"},{suit:"",rank:"K"},...] write holdem poker evaluator javascript func to return higher combination in format {combinationRank:9,combination:"flush royal",cards:[instance1, instance2,...]}; DON't create new card objects use existed card objects from input array;
|
62f8b60ee1c0955e90205b6846b73102
|
{
"intermediate": 0.6368985772132874,
"beginner": 0.23662403225898743,
"expert": 0.1264774054288864
}
|
1,000
|
'execute(Params...)' is deprecated as of API 30: Android 11.0 (R)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUp = (Button) findViewById(R.id.btnUp);
btnDown = (Button) findViewById(R.id.btnDown);
txtAddress = (EditText) findViewById(R.id.ipAddress);
btnUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Set the wifiModuleIp and wifiModulePort variables to the Raspberry Pi's IP address and SSH port, respectively
MainActivity.wifiModuleIp = "192.168.1.100";
MainActivity.wifiModulePort = 22;
// Set the CMD variable to the command to execute the Python script
MainActivity.CMD = "python /path/to/script.py";
// Execute the command on the Raspberry Pi using SSH
Soket_AsyncTask task = new Soket_AsyncTask();
task.execute();
}
});
}
|
580ae03f6b42014d8ab921464b7b1c54
|
{
"intermediate": 0.45923250913619995,
"beginner": 0.30471861362457275,
"expert": 0.2360488325357437
}
|
1,001
|
Hi, ChatGPT! Make a python code using google scholar api to parse the results of search request such as title, abstract, date, authors, doi and make json file. The input parameter is search request
|
26cbbd82fda186f64dfeccfdeec3fd51
|
{
"intermediate": 0.5489673614501953,
"beginner": 0.16221928596496582,
"expert": 0.28881335258483887
}
|
1,002
|
Draw a circle
|
2eabe21e46e4baa890eb008cde0a8d23
|
{
"intermediate": 0.32066893577575684,
"beginner": 0.3381657600402832,
"expert": 0.3411652743816376
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.