row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
33,127
|
Can you explain what these settings do in process lasso?
[PowerManagement]
StartWithPowerPlan=Ultimate Performance
Display=
PC=
[PowerSaver]
PowerSaver_IdleTime=7200
EnergySaverEnabled=true
EnergySaverForceActivePowerProfile=true
EnergySaverUpPowerProfileName=Ultimate Performance
EnergySaverEvents=true
DisableEnergySaverDuringGamingMode=true
PowerSaver_Exclusions=
|
13478de17b5e85e827d04a9c8afb2b7e
|
{
"intermediate": 0.4501276910305023,
"beginner": 0.2512042224407196,
"expert": 0.2986680865287781
}
|
33,128
|
Для балансировки АВЛ-дерева при операциях вставки и удаления производятся левые и правые повороты. Левый поворот в вершине производится, когда баланс этой вершины больше 1, аналогично, правый поворот производится при балансе, меньшем 1.
Существует два разных левых (как, разумеется, и правых) поворота: большой и малый левый поворот.
Малый левый поворот осуществляется следующим образом:
{скоро тут будет иллюстрация}
Заметим, что если до выполнения малого левого поворота был нарушен баланс только корня дерева, то после его выполнения все вершины становятся сбалансированными, за исключением случая, когда у правого ребенка корня баланс до поворота равен 1. В этом случае вместо малого левого поворота выполняется большой левый поворот, который осуществляется так:
{скоро тут будет иллюстрация}
Дано дерево, в котором баланс дерева равен 2. Сделайте левый поворот.
Входные данные
Входные данные содержат описание двоичного дерева.
В первой строке файла находится число
�
n (
1
≤
�
≤
2
⋅
1
0
5
1≤n≤2⋅10
5
) - число вершин в дереве. В последующих
�
n строках файла находятся описания вершин дерева. В (
�
+
1
i+1)-ой строке айла (
1
≤
�
≤
�
1≤i≤n) находится описание
�
i-ой вершины, состоящее из трех чисел
�
�
K
i
,
�
�
L
i
,
�
�
R
i
, разделенных пробелами ключа в
�
i-ой вершине (
∣
�
�
∣
<
=
1
0
9
∣Ki∣<=10
9
), номера левого ребенка
�
i-ой вершины (
�
<
�
�
≤
�
i<L
i
≤n или
�
�
=
0
L
i
=0, если левого ребенка нет) и номера правого ребенка
�
i-ой вершины (
�
<
�
�
≤
�
i<R
i
≤n или
�
�
=
0
R
i
=0, если правого ребенка нет).
Все ключи различны. Гарантируется, что данное дерево является деревом поиска. Все ключи различны. Баланс корня дерева (вершины с номером 1) равен 2, баланс всех остальных вершин находится в пределах от -1 до 1.
Выходные данные
Выведите в том же формате дерево после осуществления левого поворота. Нумерация вершин может быть произвольной при условии соблюдения формата. Так, номер вершины должен быть меньше номера ее детей.
STDIN STDOUT
7
-2 7 2
8 4 3
9 0 0
3 5 6
0 0 0
6 0 0
-7 0 0
7
3 2 3
-2 4 5
8 6 7
-7 0 0
0 0 0
6 0 0
9 0 0
реши на cpp
|
bbaf76fa1f3b9161cc9c241131762f6f
|
{
"intermediate": 0.11882809549570084,
"beginner": 0.689632773399353,
"expert": 0.19153915345668793
}
|
33,129
|
// Decompiled by AS3 Sorcerer 6.78
// www.buraks.com/as3sorcerer
//alternativa.tanks.models.battlefield.BattlefieldMessages
package alternativa.tanks.models.battlefield
{
import flash.display.Sprite;
import __AS3__.vec.Vector;
import flash.filters.GlowFilter;
import __AS3__.vec.*;
public class BattlefieldMessages extends Sprite
{
private var maxMessages:int;
private var fontSize:int;
private var verticalInterval:int;
private var numMessages:int;
private var messages:Vector.<Message> = new Vector.<Message>();
private var numPooledMessages:int;
private var messagePool:Vector.<Message> = new Vector.<Message>();
public function BattlefieldMessages(maxMessages:int, fontSize:int, verticalInterval:int)
{
this.maxMessages = maxMessages;
this.fontSize = fontSize;
this.verticalInterval = verticalInterval;
filters = [new GlowFilter(0, 1, 6, 6)];
}
public function addMessage(color:uint, text:String):void
{
if (this.numMessages == this.maxMessages)
{
this.removeMessage(0);
};
var message:Message = (this.messages[this.numMessages] = this.createMessage());
addChild(message.label);
message.label.color = color;
message.label.text = text;
message.label.x = (-0.5 * message.label.width);
message.label.y = (this.verticalInterval * this.numMessages);
this.numMessages++;
}
public function update(deltaMsec:uint):void
{
var message:Message;
var i:int;
while (i < this.numMessages)
{
message = this.messages[i];
if (message.isDead)
{
this.removeMessage(i);
i--;
}
else
{
message.update(deltaMsec);
};
i++;
};
}
private function removeMessage(index:int):void
{
var message:Message = this.messages[index];
this.destroyMessage(message);
var i:int = (index + 1);
while (i < this.numMessages)
{
message = (this.messages[int((i - 1))] = this.messages[i]);
message.label.y = (message.label.y - this.verticalInterval);
i++;
};
this.numMessages--;
}
private function destroyMessage(message:Message):void
{
removeChild(message.label);
var _local_2:* = this.numPooledMessages++;
this.messagePool[_local_2] = message;
}
private function createMessage():Message
{
var message:Message;
if (this.numPooledMessages == 0)
{
message = new Message(this.fontSize);
}
else
{
message = this.messagePool[--this.numPooledMessages];
this.messagePool[this.numPooledMessages] = null;
};
message.init();
return (message);
}
}
}//package alternativa.tanks.models.battlefield
import controls.Label;
import __AS3__.vec.Vector;
import __AS3__.vec.*;
class Message
{
/*private*/ static const FLASH_TIME:int = 100;
/*private*/ static const FADE_TIME:int = 300;
/*private*/ static const LIFE_TIME1:int = 1500;
/*private*/ static const LIFE_TIME2:int = 10000;
/*private*/ static const ALPHA:Number = 0.6;
public var label:Label = new Label();
public var isDead:Boolean;
/*private*/ var states:Vector.<IMessageState>;
/*private*/ var currentStateIndex:int;
public function Message(fontSize:int)
{
this.states = Vector.<IMessageState>([new StateAlpha(this, FLASH_TIME, 0, 1), new StateNormal(this, LIFE_TIME1), new StateAlpha(this, FADE_TIME, 1, ALPHA), new StateNormal(this, LIFE_TIME2), new StateAlpha(this, FADE_TIME, ALPHA, 0)]);
this.label.size = fontSize;
this.label.bold = true;
}
public function init():void
{
this.isDead = false;
this.currentStateIndex = 0;
this.states[0].init();
}
public function update(timeDelta:int):void
{
if (this.isDead)
{
return;
};
var state:IMessageState = this.states[this.currentStateIndex];
if ((!(state.update(timeDelta))))
{
if (++this.currentStateIndex == this.states.length)
{
this.isDead = true;
}
else
{
this.states[this.currentStateIndex].init();
};
};
}
}
interface IMessageState
{
function init():void;
function update(_arg_1:int):Boolean;
}
class StateNormal implements IMessageState
{
/*private*/ var message:Message;
/*private*/ var lifeTime:int;
/*private*/ var timeLeft:int;
public function StateNormal(message:Message, lifeTime:int)
{
this.message = message;
this.lifeTime = lifeTime;
}
public function init():void
{
this.timeLeft = this.lifeTime;
}
public function update(timeDelta:int):Boolean
{
if (this.timeLeft <= 0)
{
return (false);
};
this.timeLeft = (this.timeLeft - timeDelta);
return (true);
}
}
class StateAlpha implements IMessageState
{
/*private*/ var message:Message;
/*private*/ var transitionTime:int;
/*private*/ var timeLeft:int;
/*private*/ var alpha1:Number;
/*private*/ var alpha2:Number;
/*private*/ var deltaAlpha:Number;
public function StateAlpha(message:Message, transitionTime:int, alpha1:Number, alpha2:Number)
{
this.message = message;
this.transitionTime = transitionTime;
this.alpha1 = alpha1;
this.alpha2 = alpha2;
this.deltaAlpha = (alpha2 - alpha1);
}
public function init():void
{
this.message.label.alpha = this.alpha1;
this.timeLeft = this.transitionTime;
}
public function update(timeDelta:int):Boolean
{
if (this.timeLeft <= 0)
{
return (false);
};
this.timeLeft = (this.timeLeft - timeDelta);
if (this.timeLeft < 0)
{
this.timeLeft = 0;
};
this.message.label.alpha = (this.alpha2 - ((this.deltaAlpha * this.timeLeft) / this.transitionTime));
return (true);
}
}
как сделать чтобы сообщение плавно появлялалсь и пропадало
|
e6695d31b7347558cfd9305719832f33
|
{
"intermediate": 0.3960490822792053,
"beginner": 0.388383686542511,
"expert": 0.21556729078292847
}
|
33,130
|
Fix the error in this MatLab code. The line "plot(n_steps*a, msd_x*a^2, 'b')" has an error and Figure 2 isn't correct.
%% RANDOM WALKTS, BROWNIAN MOTION, AND DIFFUSION
% ————————— parameters
width = 5; % width of pipe in mm
a = 0.01; % lattice constant in mm
pw = 0; % probability of waiting
num_steps = 1000000; % # steps for histograms
num_walks = 1000000; % # random walks for histograms
% ————————— calculate lattice size based on width
lattice_size = round(width/a);
% ————————— initialize random walker position
x = 0;
y = lattice_size/2;
% ————————— initialize mean squared displacement variables
msd_x = zeros(1,num_steps);
msd_y = zeros(1,num_steps);
% ————————— loop over the # of steps
for step = 2:num_steps+1
% choice: does walker wait or make a step?
if rand<=pw
% walker waits
continue;
else
% walker makes a step
% calculate the step direction
dx = randi([-1,1]);
dy = randi([-1,1]);
% update walker position
x = x+dx;
y = y+dy;
% reflect at the y-direction boundary
if y<1
y = 2-y;
elseif y>lattice_size
y = 2*lattice_size - y - 1;
end
% calculate mean squared displacement in each direction
msd_x(step) = (x*a)^2;
msd_y(step) = ((y-(lattice_size/2))*a)^2;
end
end
% —————————— 1) visualize the random walk trajectories
figure;
plot((0:num_steps)*a, (msd_y*a), 'b.')
title('Random Walk Trajectories');
xlabel('x (mm)');
ylabel('y (mm)');
xlim([0,num_steps*a]);
% ————————— 2) mean squared displacement in x-direction
figure;
n_steps = 1:num_steps;
msd_x = cumsum(msd_x) ./ (1:num_steps+1);
plot(n_steps*a, msd_x*a^2, 'b')
title('Mean Squared Displacement in the x-Direction');
xlabel('Number of Steps');
ylabel('Mean Squared Displacement');
xlim([0, num_steps*a]);
% ————————— 3) mean squared displacement in y-direction
figure;
msd_y = cumsum(msd_y) ./ (1:num_steps+1);
plot(n_steps*a, msd_y*a^2, 'b')
title('Mean Squared Displacement in the y-Direction');
xlabel('Number of Steps');
ylabel('Mean Squared Displacement');
xlim([0, num_steps*a]);
% ————————— 4) histogram of locations in x-direction
figure;
for num_steps = [100,1000,10000,100000,1000000]
x_hist = zeros(1,lattice_size+1);
for walk = 1:num_walks
x=0;
for step = 1:num_steps
dx = randi([-1,1]);
x = x+dx;
if x<0
x=0;
elseif x>lattice_size
x = lattice_size;
end
end
x_hist(x+1) = x_hist(x+1) + 1;
end
subplot(2,3,find([100,1000,10000,100000,1000000] == num_steps));
bar(0:lattice_size, x_hist / num_walks, 'b');
title(['Histogram of x-locations after ', num2str(num_steps), ' steps']);
xlabel('x');
ylabel('Probability');
end
% ————————— 5) histogram of locations in y-direction
figure;
for num_steps = [100,1000,10000,100000,1000000]
y_hist = zeros(1,lattice_size+1);
for walk = 1:num_walks
x = 0;
y = lattice_size/2;
for step = 1:num_steps
dx = randi([-1,1]);
dy = randi([-1,1]);
x = x+dx;
y = y+dy;
if y<1
y = 2-y;
elseif y>lattice_size
y = 2*lattice_size - y - 1;
end
end
y_hist(y+1) = y_hist(y+1) + 1;
end
subplot(2,3,find([100,1000,10000,100000,1000000] == num_steps));
bar(0:lattice_size, y_hist / num_walks, 'b');
title(['Histogram of y-locations after ', num2str(num_steps), ' steps']);
xlabel('y');
ylabel('Probability');
end
% ————————— 6) calculate avg time per step for given diffusion constant
D_desired = 1e-7; % desired diffusion constant in cm^2/sec
t = D_desired / (a^2); % avg time per step in sec
% ————————— 7) calculate diffusion constant in the x-direction
figure;
diffusion_x = gradient(msd_x*a^2) / (2*t);
plot(n_steps*a, diffusion_x);
title('Diffusion Constant in the x-Direction');
xlabel('Time (mm)');
ylabel('Diffusion Constant');
xlim([0, num_steps*a]);
|
d8a3c47ea419649e21c1f2de787d1fd5
|
{
"intermediate": 0.33039215207099915,
"beginner": 0.508634090423584,
"expert": 0.16097375750541687
}
|
33,131
|
INTRODUCTION
OSI Security Architecture - Classical Encryption Techniques – CipherPrinciples–
DataEncryptionStandard–BlockCipherDesignPrinciples and Modes of Operation–
Evaluation Criteria for AES–AES Cipher– Triple DES– Placement of Encryption
Function–Traffic Confidentiality.
PUBLICKEYCRYPTOGRAPHY
9 Hours
Introduction to Number Theory -Key Management - Diffie-Hellman Key Exchange
– Elliptic Curve Architecture and Cryptography – Confidentiality using Symmetric
Encryption– Public Key Cryptography and RSA.
AUTHENTICATIONANDHASHFUNCTION
9 Hours
Authentication Requirements – Authentication Functions – Message Authentication
Codes–Hash Functions–Security of Hash Functions and MACs – Secure Hash Algorithm –
HMAC Digital Signatures – Authentication Protocols–Digital Signature Standard.
NETWORKSECURITY
9 Hours
Authentication Applications: Kerberos – X.509 Authentication Service– Electronic Mail
Security–PGP–S/MIME-IP Security–Web Security- Practical implementation of security
using GPG Suite.
SYSTEMLEVELSECURITY
8 Hours
Intrusion Detection ––Firewall Design Principles–Trusted Systems. Case study: Biometric
authentication and Ethical Hacking
remove the hours, give me in markdown task list form ( break down subtopics more if you see fit )
|
714b4142c2f86f3de04d777a37f75eed
|
{
"intermediate": 0.4241573214530945,
"beginner": 0.2916148900985718,
"expert": 0.28422781825065613
}
|
33,132
|
Есть программа. Она должна принимать текстовый файл data.txt, делать из его строк АВЛ-дерево и выводить его элементы, но по какой-то причине ничего не выводит. Вот программа: #include <iostream>
#include<fstream>
#include<string>
using namespace std;
struct Key
{
char f1;
int* f2 = new int[4];
};
struct Node
{
Key key;
int count;
Node* left;
Node* right;
int balance;
};
void search(Key x, Node*& p, short h) // поиск и добавление элемента
{
if (x.f1 != 'Б')
{
return;
}
else if (p == NULL) // слова нет в дереве; включить его
{
p = new Node;
p->key = x;
p->count = 1;
p->balance = 0;
p->left = NULL;
p->right = NULL;
}
else if (x.f2 < p->key.f2)
{
search(x, p->left, h);
if (h != 0) // выросла левая ветвь
{
switch (p->balance)
{
case 1:
p->balance = 0;
h = 0;
break;
case 0:
p->balance = -1;
break;
case -1: // балансировка
Node * p1 = p->left;
if (p1->balance == -1) // L-поворот
{
p->left = p1->right;
p1->right = p;
p->balance = 0;
p = p1;
}
else // LR-поворот
{
Node* p2 = p1->right;
p1->right = p2->left;
p2->left = p1;
p->left = p2->right;
p2->right = p;
if (p2->balance == -1)
p->balance = 1;
else
p->balance = 0;
if (p2->balance == 1)
p1->balance = -1;
else
p1->balance = 0;
p = p2;
}
p->balance = 0;
h = 0;
break;
}
}
}
else if (x.f2 > p->key.f2)
{
search(x, p->right, h);
if (h != 0) // выросла правая ветвь
{
switch (p->balance)
{
case -1:
p->balance = 0;
h = 0;
break;
case 0:
p->balance = 1;
break;
case 1: // балансировка
Node * p1 = p->right;
if (p1->balance == 1) //R-поворот
{
p->right = p1->left;
p1->left = p;
p->balance = 0;
p = p1;
}
else // RL-поворот
{
Node* p2 = p1->left;
p1->left = p2->right;
p2->right = p1;
p->right = p2->left;
p2->left = p;
if (p2->balance == 1)
p->balance = -1;
else
p->balance = 0;
if (p2->balance == -1)
p1->balance = 1;
else
p1->balance = 0;
p = p2;
}
p->balance = 0;
h = 0;
break;
}
}
}
else
{
p->count += 1;
h = 0;
}
}
void balance1(Node* p, short h)
{
Node* p1, * p2;
short b1, b2;
switch (p->balance)
{
case -1:
p->balance = 0;
break;
case 0:
p->balance = 1;
h = 0;
break;
case 1: // балансировка
p1 = p->right;
b1 = p1->balance;
if (b1 >= 0) // R-поворот
{
p->right = p1->left;
p1->left = p;
if (b1 == 0)
{
p->balance = 1;
p1->balance = -1;
h = 0;
}
else
{
p->balance = 0;
p1->balance = 0;
}
p = p1;
}
else // RL-поворот
{
p2 = p1->left;
b2 = p2->balance;
p1->left = p2->right;
p2->right = p1;
p->right = p2->left;
p2->left = p;
if (b2 == 1)
p->balance = -1;
else
p->balance = 0;
if (b2 == -1)
p1->balance = 1;
else
p1->balance = 0;
p = p2;
p2->balance = 0;
}
}
}
void balance2(Node* p, short h)
{
Node* p1, * p2;
short b1, b2;
switch (p->balance)
{
case 1:
p->balance = 0;
break;
case 0:
p->balance = 0;
h = 0;
break;
case -1:
p1 = p->left;
b1 = p1->balance;
if (b1 <= 0) // L-поворот
{
p->left = p1->right;
p1->right = p;
if (b1 == 0)
{
p->balance = -1;
p1->balance = 1;
h = 0;
}
else
{
p->balance = 0;
p1->balance = 0;
}
p = p1;
}
else // LR-поворот
{
p2 = p1->right;
b2 = p2->balance;
p1->right = p2->left;
p2->left = p1;
p->left = p2->right;
p2->right = p;
if (b2 == -1)
p->balance = 1;
else
p->balance = 0;
if (b2 == 1)
p1->balance = -1;
else
p1->balance = 0;
p = p2;
p2->balance = 0;
}
}
}
Node* del(Node* r, Node* q, short h)
{
if (r->right != NULL)
{
r->right = del(r->right, q, h);
if (h != 0)
balance2(r, h);
return r;
}
else
{
q->key = r->key;
q->count = r->count;
Node* left = r->left;
delete r;
h = 1;
return left;
}
}
void delet(Key x, Node*& p, short h) // удаление элемента, выше вспомогательные подпрограммы
{
Node* q;
if (p == NULL || x.f1 != 'Б')
{
cout << "Key is not in tree" << endl;
h = 0;
}
else if (x.f2 < p->key.f2)
{
delet(x, p->left, h);
if (h != 0)
balance1(p, h);
}
else if (x.f2 > p->key.f2)
{
delet(x, p->right, h);
if (h != 0)
balance2(p, h);
}
else
{
q = p;
if (q->right == NULL)
{
p = q->left;
delete q;
h = 1;
}
else if (q->left == NULL)
{
p = q->right;
delete q;
h = 1;
}
else
{
del(q->left, q, h);
if (h != 0)
balance1(p, h);
}
}
}
void printtree(Node* t, short h) // печать дерева
{
if (t != NULL)
{
printtree(t->right, h + 1);
for (int i = 1; i <= h; i++)
{
cout << ' ';
}
cout << t->key.f1 << t->key.f2 << endl;
printtree(t->left, h + 1);
}
}
int main()
{
Node* root = NULL;
Key key;
string line;
ifstream in("data.txt");
if (in.is_open())
{
while (getline(in, line))
{
key.f1 = line[0];
for (int i = 1; i < 5; i++)
{
key.f2[i - 1] = line[i] - '0';
}
search(key, root, 0);
}
}
printtree(root, 0);
return 0;
} Вот содержимое data.txt: Б9122
Б9120
Б9122
Б8120
Б8120
Б9222
Б9320
|
6248c45717f83c52cac0f65347a6720c
|
{
"intermediate": 0.2793925106525421,
"beginner": 0.5766108632087708,
"expert": 0.14399664103984833
}
|
33,133
|
In unreal engine, how can i handle a custom collision on a Pawn having a UMovementComponent attached to it?
|
09460929bb0f32e873e146551b5a0edd
|
{
"intermediate": 0.24816592037677765,
"beginner": 0.1751706302165985,
"expert": 0.5766634941101074
}
|
33,134
|
Hi, lets create a bash script. It should find the fresh transaction from pacman.log (the last line that contains "transaction started") and starting from that line and until the end of the file collect all the upgraded or installed packages and write them (with previous and current versions) into a file called UpdatedPkgList. The lines for upgraded packages usually contain something like this: "upgraded package_name (2.39.1-1 -> 2.39.2-1)". And similar for installed packages: "installed package_name (0.40.0-3)". Same for removed ones. Then, for each package in the file, it should search files in the two recent folders from PacTreeHistory directory which contains folders named with dates in this format: YYYY-MM-DD_H-MM. Each of the folders hold files with dependency trees for each of the system packages. The files named after corresponding packages. The script should look for files which names are in a separate predefined list, let's call it MonitoredAppList. So, if an updated/installed/removed package is in a file within those two folders, the script should write its name, versions and the corresponding filename from the folders in a separate file, let's call it UpdatedDepsOfMonitoredApps. So, basically, we need to know, what dependencies were updated for each of the monitored apps. Feel free to suggest more rational way of doing this if there's any.
|
a6679d17e769e1a4beea0cc9eab0a481
|
{
"intermediate": 0.3059592545032501,
"beginner": 0.3412114083766937,
"expert": 0.3528292775154114
}
|
33,135
|
help me improve on this and also float doesn't have split:
classes = []
# Loop through each sorted prediction and add the "class" to the classes list
for prediction in sorted_predictions:
classes.append(prediction["class"])
# Join the classes into a single string
classes_string = "".join(classes)
# remove everything that's not a number from the string
classes_string = re.sub("[^0-9.]", "", classes_string)
print(classes_string + " hey")
while float(classes_string) > 3:
classes_string = float(classes_string) / 10
print(classes_string)
# now times it by 10 if the numbers behind the , is more than 3
try:
if classes_string.split(".")[1] > 3:
print("found more than 3")
classes_string = float(classes_string) * 10
except Exception as e:
print(e)
print(classes_string)
|
e7ad282e129e1684f955d45f585650cc
|
{
"intermediate": 0.12320498377084732,
"beginner": 0.8069130778312683,
"expert": 0.06988193839788437
}
|
33,136
|
continue this schedule:
6th – 12 th November Helen Sidebotham
13th – 19 th November Ian & Diane Vella
20th – 26 th November Louis and Marline Ciancio
27th – 3 rd December Eman & Anne Marie Vella
Maria Cachia – ONLY Vists (Preferably Mornings)
Date Volunteer
6th – 12 th November Eman & Anne Marie Vella
13th – 19 th November Lawrence & Louise Attard
20th – 26 th November Justin & Audrey Baldacchino
27th – 3 rd December Helen Sidebotham
|
f891f600930955808528e00e0d65bba9
|
{
"intermediate": 0.3197445273399353,
"beginner": 0.3514639139175415,
"expert": 0.3287915289402008
}
|
33,137
|
Есть программа. Она должна принимать текстовый файл data.txt, делать из его строк АВЛ-дерево и выводить его элементы, но по какой-то причине ничего не выводит. Вот программа: #include
#include<fstream>
#include<string>
using namespace std;
struct Key
{
char f1;
int* f2 = new int[4];
};
struct Node
{
Key key;
int count;
Node* left;
Node* right;
int balance;
};
void search(Key x, Node*& p, short h) // поиск и добавление элемента
{
if (x.f1 != ‘Б’)
{
return;
}
else if (p == NULL) // слова нет в дереве; включить его
{
p = new Node;
p->key = x;
p->count = 1;
p->balance = 0;
p->left = NULL;
p->right = NULL;
}
else if (x.f2 < p->key.f2)
{
search(x, p->left, h);
if (h != 0) // выросла левая ветвь
{
switch (p->balance)
{
case 1:
p->balance = 0;
h = 0;
break;
case 0:
p->balance = -1;
break;
case -1: // балансировка
Node * p1 = p->left;
if (p1->balance == -1) // L-поворот
{
p->left = p1->right;
p1->right = p;
p->balance = 0;
p = p1;
}
else // LR-поворот
{
Node* p2 = p1->right;
p1->right = p2->left;
p2->left = p1;
p->left = p2->right;
p2->right = p;
if (p2->balance == -1)
p->balance = 1;
else
p->balance = 0;
if (p2->balance == 1)
p1->balance = -1;
else
p1->balance = 0;
p = p2;
}
p->balance = 0;
h = 0;
break;
}
}
}
else if (x.f2 > p->key.f2)
{
search(x, p->right, h);
if (h != 0) // выросла правая ветвь
{
switch (p->balance)
{
case -1:
p->balance = 0;
h = 0;
break;
case 0:
p->balance = 1;
break;
case 1: // балансировка
Node * p1 = p->right;
if (p1->balance == 1) //R-поворот
{
p->right = p1->left;
p1->left = p;
p->balance = 0;
p = p1;
}
else // RL-поворот
{
Node* p2 = p1->left;
p1->left = p2->right;
p2->right = p1;
p->right = p2->left;
p2->left = p;
if (p2->balance == 1)
p->balance = -1;
else
p->balance = 0;
if (p2->balance == -1)
p1->balance = 1;
else
p1->balance = 0;
p = p2;
}
p->balance = 0;
h = 0;
break;
}
}
}
else
{
p->count += 1;
h = 0;
}
}
void balance1(Node* p, short h)
{
Node* p1, * p2;
short b1, b2;
switch (p->balance)
{
case -1:
p->balance = 0;
break;
case 0:
p->balance = 1;
h = 0;
break;
case 1: // балансировка
p1 = p->right;
b1 = p1->balance;
if (b1 >= 0) // R-поворот
{
p->right = p1->left;
p1->left = p;
if (b1 == 0)
{
p->balance = 1;
p1->balance = -1;
h = 0;
}
else
{
p->balance = 0;
p1->balance = 0;
}
p = p1;
}
else // RL-поворот
{
p2 = p1->left;
b2 = p2->balance;
p1->left = p2->right;
p2->right = p1;
p->right = p2->left;
p2->left = p;
if (b2 == 1)
p->balance = -1;
else
p->balance = 0;
if (b2 == -1)
p1->balance = 1;
else
p1->balance = 0;
p = p2;
p2->balance = 0;
}
}
}
void balance2(Node* p, short h)
{
Node* p1, * p2;
short b1, b2;
switch (p->balance)
{
case 1:
p->balance = 0;
break;
case 0:
p->balance = 0;
h = 0;
break;
case -1:
p1 = p->left;
b1 = p1->balance;
if (b1 <= 0) // L-поворот
{
p->left = p1->right;
p1->right = p;
if (b1 == 0)
{
p->balance = -1;
p1->balance = 1;
h = 0;
}
else
{
p->balance = 0;
p1->balance = 0;
}
p = p1;
}
else // LR-поворот
{
p2 = p1->right;
b2 = p2->balance;
p1->right = p2->left;
p2->left = p1;
p->left = p2->right;
p2->right = p;
if (b2 == -1)
p->balance = 1;
else
p->balance = 0;
if (b2 == 1)
p1->balance = -1;
else
p1->balance = 0;
p = p2;
p2->balance = 0;
}
}
}
Node* del(Node* r, Node* q, short h)
{
if (r->right != NULL)
{
r->right = del(r->right, q, h);
if (h != 0)
balance2(r, h);
return r;
}
else
{
q->key = r->key;
q->count = r->count;
Node* left = r->left;
delete r;
h = 1;
return left;
}
}
void delet(Key x, Node*& p, short h) // удаление элемента, выше вспомогательные подпрограммы
{
Node* q;
if (p == NULL || x.f1 != ‘Б’)
{
cout << “Key is not in tree” << endl;
h = 0;
}
else if (x.f2 < p->key.f2)
{
delet(x, p->left, h);
if (h != 0)
balance1(p, h);
}
else if (x.f2 > p->key.f2)
{
delet(x, p->right, h);
if (h != 0)
balance2(p, h);
}
else
{
q = p;
if (q->right == NULL)
{
p = q->left;
delete q;
h = 1;
}
else if (q->left == NULL)
{
p = q->right;
delete q;
h = 1;
}
else
{
del(q->left, q, h);
if (h != 0)
balance1(p, h);
}
}
}
void printtree(Node* t, short h) // печать дерева
{
if (t != NULL)
{
printtree(t->right, h + 1);
for (int i = 1; i <= h; i++)
{
cout << ’ ';
}
cout << t->key.f1 << t->key.f2 << endl;
printtree(t->left, h + 1);
}
}
int main()
{
Node* root = NULL;
Key key;
string line;
ifstream in(“data.txt”);
if (in.is_open())
{
while (getline(in, line))
{
key.f1 = line[0];
for (int i = 1; i < 5; i++)
{
key.f2[i - 1] = line[i] - ‘0’;
}
search(key, root, 0);
}
}
printtree(root, 0);
return 0;
} Вот содержимое data.txt: Б9122
Б9120
Б9122
Б8120
Б8120
Б9222
Б9320
|
1fe7e3c17d3dd88c9535573bcdb81e69
|
{
"intermediate": 0.31491076946258545,
"beginner": 0.50103759765625,
"expert": 0.18405161798000336
}
|
33,138
|
select emplyee list from oracle database with salaries
|
358556c05072bd34187facdd52a8f51b
|
{
"intermediate": 0.3869975805282593,
"beginner": 0.3160443603992462,
"expert": 0.2969580590724945
}
|
33,139
|
#include <iostream>
struct Node {
int data;
int height;
Node* left;
Node* right;
Node* parent;
};
struct BinTree {
Node* top = nullptr;
int height(Node* N) {
if (N == nullptr)
return 0;
return N->height;
}
Node* newNode(int value) {
Node* node = new Node();
node->data = value;
node->left = nullptr;
node->right = nullptr;
node->parent = nullptr;
node->height = 1;
return(node);
}
Node* rightRotate(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
y->height = std::max(height(y->left), height(y->right)) + 1;
x->height = std::max(height(x->left), height(x->right)) + 1;
return x;
}
Node* leftRotate(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = std::max(height(x->left), height(x->right)) + 1;
y->height = std::max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(Node* N) {
if (N == nullptr)
return 0;
return height(N->left) - height(N->right);
}
Node* MinValueNode(Node* node) {
Node* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
Node* Delete(Node* root, int value) {
if (root == nullptr)
return root;
if (value < root->data)
root->left = Delete(root->left, value);
else if(value > root->data)
root->right = Delete(root->right, value);
else {
if((root->left == nullptr) || (root->right == nullptr)) {
Node* temp = root->left ? root->left : root->right;
if(temp == nullptr) {
temp = root;
root = nullptr;
} else
*root = *temp;
free(temp);
} else {
Node* temp = MinValueNode(root->right);
root->data = temp->data;
root->right = Delete(root->right, temp->data);
}
}
if (root == nullptr)
return root;
root->height = 1 + std::max(height(root->left), height(root->right));
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
Node* Insert(Node* node, int value) {
if (node == nullptr)
return(newNode(value));
if (value < node->data)
node->left = Insert(node->left, value);
else if (value > node->data)
node->right = Insert(node->right, value);
else
return node;
node->height = 1 + std::max(height(node->left), height(node->right));
int balance = getBalance(node);
if (balance > 1 && value < node->left->data)
return rightRotate(node);
if (balance < -1 && value > node->right->data)
return leftRotate(node);
if (balance > 1 && value > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && value < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void Exists(int value) {
Node* current = top;
while (current != nullptr) {
if (value < current->data) {
current = current->left;
} else if (value > current->data) {
current = current->right;
} else {
std::cout << "true" << '\n';
return;
}
}
std::cout << "false" << '\n';
}
void prev(Node* current, int value) {
Node* ans_root = nullptr;
while (current != nullptr) {
if (value > current->data) {
ans_root = current;
current = current->right;
} else {
current = current->left;
}
}
if (ans_root != nullptr) {
std::cout << ans_root->data << '\n';
} else {
std::cout << "none" << '\n';
}
}
void next(Node* current, int value) {
Node* ans_root = nullptr;
while (current != nullptr) {
if (value < current->data) {
ans_root = current;
current = current->left;
} else {
current = current->right;
}
}
if (ans_root != nullptr) {
std::cout << ans_root->data << '\n';
} else {
std::cout << "none" << '\n';
}
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
std::string cmd;
BinTree tree;
while (std::cin >> cmd) {
if (cmd == "insert") {
int x;
std::cin >> x;
tree.top = tree.Insert(tree.top, x);
} else if (cmd == "delete") {
int x;
std::cin >> x;
tree.top = tree.Delete(tree.top, x);
} else if (cmd == "exists") {
int x;
std::cin >> x;
tree.Exists(x);
} else if (cmd == "next") {
int x;
std::cin >> x;
tree.next(tree.top, x);
} else if (cmd == "prev") {
int x;
std::cin >> x;
tree.prev(tree.top, x);
}
}
}
используй этот код для решения задачи ниже
Для балансировки АВЛ-дерева при операциях вставки и удаления производятся левые и правые повороты. Левый поворот в вершине производится, когда баланс этой вершины больше 1, аналогично, правый поворот производится при балансе, меньшем 1.
Существует два разных левых (как, разумеется, и правых) поворота: большой и малый левый поворот.
Малый левый поворот осуществляется следующим образом:
{скоро тут будет иллюстрация}
Заметим, что если до выполнения малого левого поворота был нарушен баланс только корня дерева, то после его выполнения все вершины становятся сбалансированными, за исключением случая, когда у правого ребенка корня баланс до поворота равен 1. В этом случае вместо малого левого поворота выполняется большой левый поворот, который осуществляется так:
{скоро тут будет иллюстрация}
Дано дерево, в котором баланс дерева равен 2. Сделайте левый поворот.
Входные данные
Входные данные содержат описание двоичного дерева.
В первой строке файла находится число
�
n (
1
≤
�
≤
2
⋅
1
0
5
1≤n≤2⋅10
5
) - число вершин в дереве. В последующих
�
n строках файла находятся описания вершин дерева. В (
�
+
1
i+1)-ой строке айла (
1
≤
�
≤
�
1≤i≤n) находится описание
�
i-ой вершины, состоящее из трех чисел
�
�
K
i
,
�
�
L
i
,
�
�
R
i
, разделенных пробелами ключа в
�
i-ой вершине (
∣
�
�
∣
<
=
1
0
9
∣Ki∣<=10
9
), номера левого ребенка
�
i-ой вершины (
�
<
�
�
≤
�
i<L
i
≤n или
�
�
=
0
L
i
=0, если левого ребенка нет) и номера правого ребенка
�
i-ой вершины (
�
<
�
�
≤
�
i<R
i
≤n или
�
�
=
0
R
i
=0, если правого ребенка нет).
Все ключи различны. Гарантируется, что данное дерево является деревом поиска. Все ключи различны. Баланс корня дерева (вершины с номером 1) равен 2, баланс всех остальных вершин находится в пределах от -1 до 1.
|
74af658f8190cd360e2ec5ad73297d8c
|
{
"intermediate": 0.3312165439128876,
"beginner": 0.39291319251060486,
"expert": 0.27587026357650757
}
|
33,140
|
// Decompiled by AS3 Sorcerer 6.78
// www.buraks.com/as3sorcerer
//alternativa.tanks.models.battlefield.BattlefieldMessages
package alternativa.tanks.models.battlefield
{
import flash.display.Sprite;
import __AS3__.vec.Vector;
import flash.filters.GlowFilter;
import __AS3__.vec.*;
public class BattlefieldMessages extends Sprite
{
private var maxMessages:int;
private var fontSize:int;
private var verticalInterval:int;
private var numMessages:int;
private var messages:Vector.<Message> = new Vector.<Message>();
private var numPooledMessages:int;
private var messagePool:Vector.<Message> = new Vector.<Message>();
public function BattlefieldMessages(maxMessages:int, fontSize:int, verticalInterval:int)
{
this.maxMessages = maxMessages;
this.fontSize = fontSize;
this.verticalInterval = verticalInterval;
filters = [new GlowFilter(0, 1, 6, 6)];
}
public function addMessage(color:uint, text:String):void
{
if (this.numMessages == this.maxMessages)
{
this.removeMessage(0);
};
var message:Message = (this.messages[this.numMessages] = this.createMessage());
addChild(message.label);
message.label.color = color;
message.label.text = text;
message.label.x = (-0.5 * message.label.width);
message.label.y = (this.verticalInterval * this.numMessages);
this.numMessages++;
}
public function update(deltaMsec:uint):void
{
var message:Message;
var i:int;
while (i < this.numMessages)
{
message = this.messages[i];
if (message.isDead)
{
this.removeMessage(i);
i--;
}
else
{
message.update(deltaMsec);
};
i++;
};
}
private function removeMessage(index:int):void
{
var message:Message = this.messages[index];
this.destroyMessage(message);
var i:int = (index + 1);
while (i < this.numMessages)
{
message = (this.messages[int((i - 1))] = this.messages[i]);
message.label.y = (message.label.y - this.verticalInterval);
i++;
};
this.numMessages--;
}
private function destroyMessage(message:Message):void
{
removeChild(message.label);
var _local_2:* = this.numPooledMessages++;
this.messagePool[_local_2] = message;
}
private function createMessage():Message
{
var message:Message;
if (this.numPooledMessages == 0)
{
message = new Message(this.fontSize);
}
else
{
message = this.messagePool[--this.numPooledMessages];
this.messagePool[this.numPooledMessages] = null;
};
message.init();
return (message);
}
}
}//package alternativa.tanks.models.battlefield
import controls.Label;
import __AS3__.vec.Vector;
import __AS3__.vec.*;
class Message
{
/*private*/ static const FLASH_TIME:int = 100;
/*private*/ static const FADE_TIME:int = 300;
/*private*/ static const LIFE_TIME1:int = 1500;
/*private*/ static const LIFE_TIME2:int = 10000;
/*private*/ static const ALPHA:Number = 0.6;
public var label:Label = new Label();
public var isDead:Boolean;
/*private*/ var states:Vector.<IMessageState>;
/*private*/ var currentStateIndex:int;
public function Message(fontSize:int)
{
this.states = Vector.<IMessageState>([new StateAlpha(this, FLASH_TIME, 0, 1), new StateNormal(this, LIFE_TIME1), new StateAlpha(this, FADE_TIME, 1, ALPHA), new StateNormal(this, LIFE_TIME2), new StateAlpha(this, FADE_TIME, ALPHA, 0)]);
this.label.size = fontSize;
this.label.bold = true;
}
public function init():void
{
this.isDead = false;
this.currentStateIndex = 0;
this.states[0].init();
}
public function update(timeDelta:int):void
{
if (this.isDead)
{
return;
};
var state:IMessageState = this.states[this.currentStateIndex];
if ((!(state.update(timeDelta))))
{
if (++this.currentStateIndex == this.states.length)
{
this.isDead = true;
}
else
{
this.states[this.currentStateIndex].init();
};
};
}
}
interface IMessageState
{
function init():void;
function update(_arg_1:int):Boolean;
}
class StateNormal implements IMessageState
{
/*private*/ var message:Message;
/*private*/ var lifeTime:int;
/*private*/ var timeLeft:int;
public function StateNormal(message:Message, lifeTime:int)
{
this.message = message;
this.lifeTime = lifeTime;
}
public function init():void
{
this.timeLeft = this.lifeTime;
}
public function update(timeDelta:int):Boolean
{
if (this.timeLeft <= 0)
{
return (false);
};
this.timeLeft = (this.timeLeft - timeDelta);
return (true);
}
}
class StateAlpha implements IMessageState
{
/*private*/ var message:Message;
/*private*/ var transitionTime:int;
/*private*/ var timeLeft:int;
/*private*/ var alpha1:Number;
/*private*/ var alpha2:Number;
/*private*/ var deltaAlpha:Number;
public function StateAlpha(message:Message, transitionTime:int, alpha1:Number, alpha2:Number)
{
this.message = message;
this.transitionTime = transitionTime;
this.alpha1 = alpha1;
this.alpha2 = alpha2;
this.deltaAlpha = (alpha2 - alpha1);
}
public function init():void
{
this.message.label.alpha = this.alpha1;
this.timeLeft = this.transitionTime;
}
public function update(timeDelta:int):Boolean
{
if (this.timeLeft <= 0)
{
return (false);
};
this.timeLeft = (this.timeLeft - timeDelta);
if (this.timeLeft < 0)
{
this.timeLeft = 0;
};
this.message.label.alpha = (this.alpha2 - ((this.deltaAlpha * this.timeLeft) / this.transitionTime));
return (true);
}
} как сделать плавное появление и пропадание сообщения
|
736596b3afb0c9df2a50632a577ed5cf
|
{
"intermediate": 0.3960490822792053,
"beginner": 0.388383686542511,
"expert": 0.21556729078292847
}
|
33,141
|
how swipe photos right and left flutter
|
9401de863250223146415b94d64bab74
|
{
"intermediate": 0.37777724862098694,
"beginner": 0.3111204206943512,
"expert": 0.31110233068466187
}
|
33,142
|
[SerializeField] private Sprite _flippedSprite;
[SerializeField] private float _flipDelay = 1f;
[SerializeField] private float _flipDuration = 2f;
private bool _isFlipping = false;
private float _flipTimer = 0f;
private SpriteRenderer _spriteRenderer;
private Quaternion _startRotation;
private Quaternion _endRotation = Quaternion.Euler(0, -180, 0);
private void Start()
{
_spriteRenderer = GetComponent<SpriteRenderer>();
StartCoroutine(StartFlipAfterDelay(_flipDelay));
}
private IEnumerator StartFlipAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
_startRotation = transform.rotation;
_isFlipping = true;
}
private void Update()
{
if (_isFlipping)
{
_flipTimer += Time.deltaTime;
float t = Mathf.Clamp01(_flipTimer / _flipDuration);
transform.rotation = Quaternion.Slerp(_startRotation, _endRotation, t);
if (t >= 1f)
{
// End the flip process
_isFlipping = false;
_flipTimer = 0f;
_spriteRenderer.sprite = _flippedSprite;
}
}
}
Измени спрайт менялся тогда когда позиция карты ровно 90
|
f55a39b51627172e7bd43a4a282859d3
|
{
"intermediate": 0.3861669898033142,
"beginner": 0.37111303210258484,
"expert": 0.24271991848945618
}
|
33,143
|
#pragma once
#include <iostream>
#include <cstdint>
class Array{
public:
Array(int x, int y, int z);
~Array();
static Array MakeArray(int x, int y, int z);
void resetState();
int getIndex(int x, int y, int z) const;
Array& operator[](int index);
friend std::ostream& operator<<(std::ostream& stream, Array& val);
void storeValue(uint32_t value, int x, int y, int z);
uint32_t getValue(int x, int y, int z) const;
Array& operator=(uint32_t x);
private:
uint32_t* arr_;
int x_;
int y_;
int z_;
mutable int current_x_, current_y_, current_z_;
};
#include "/Users/alishashelby/Desktop/labwork5-alishashelby/lib/3DArray.h"
Array::Array(int x, int y, int z) {
x_ = x;
y_ = y;
z_ = z;
arr_ = new uint32_t[x * y * z];
for (int i = 0; i < x * y * z; ++i) {
arr_[i] = 0;
}
}
Array::~Array() {
delete[] arr_;
}
Array Array::MakeArray(int x, int y, int z) {
return Array(x, y, z);
}
void Array::resetState() {
operator_count_ = 0;
len_ = 0;
}
int Array::getIndex(int x, int y, int z) const {
return ((x * y_ + y) * z_ + z) * 17;
}
Array& Array::operator[](int index) {
static int dimension = 0;
switch (dimension) {
case 0: current_x_ = index; break;
case 1: current_y_ = index; break;
case 2: {
current_z_ = index;
dimension = -1; // Reset for the next time
break;
}
}
++dimension;
return *this;
}
std::ostream& operator<<(std::ostream& stream, const Array& val) {
uint32_t number = val.getValue(val.current_x_, val.current_y_, val.current_z_); // The same here
for (int i = 16; i >= 0; --i) {
stream << ((number >> i) & 1);
}
return stream;
}
void Array::storeValue(uint32_t value, int x, int y, int z) {
int bit_start = getIndex(x, y, z);
//std::cout << bit_start<< '\n';
for (int i = 0; i < 17; ++i) {
int bitPos = bit_start % 32;
if ((value >> i) & 1) {
arr_[bit_start / 32] |= (1UL << bitPos);
} else {
arr_[bit_start / 32] &= ~(1UL << bitPos);
}
++bit_start;
}
}
uint32_t Array::getValue(int x, int y, int z) const {
int bitPos = getIndex(x, y, z);
uint32_t value = 0;
for (int i = 0; i < 17; ++i, ++bitPos) {
int index = bitPos / 32;
int offset = bitPos % 32;
if (arr_[index] & (1U << offset)) {
value |= (1U << i);
}
}
return value;
}
Array& Array::operator=(uint32_t x) {
storeValue(x, current_x_, current_y_, current_z_); // Assume these are properly set by operator[]
return *this;
} fix it
|
70936ef3c657a6772322a88da30e374a
|
{
"intermediate": 0.319328635931015,
"beginner": 0.4701548218727112,
"expert": 0.2105165421962738
}
|
33,144
|
primevue : add filter on name
<template>
<div class="card">
<DataTable
stripedRows
:value="files"
removableSort
paginator
dataKey="id"
:rows="7"
:loading="loading"
:rowsPerPageOptions="[5, 10, 20, 50]"
tableStyle="min-width: 50rem"
>
<Column field="name" header="Name" sortable style="width: 25%"></Column>
<Column field="size" header="Size" sortable style="width: 25%"></Column>
<Column field="size" header="Type" style="width: 25%"></Column>
<Column field="tag" header="Tag" sortable style="width: 25%"></Column>
<Column field="url" header="Download" style="width: 25%"></Column>
<template #footer>
In total there are {{ files ? files.length : 0 }} Files.
</template>
</DataTable>
</div>
</template>
<script>
import axios from "axios";
import "primevue/resources/themes/lara-light-green/theme.css";
import DataTable from "primevue/datatable";
import Column from "primevue/column";
export default {
name: "files-list2",
components: {
DataTable,
Column,
},
data() {
return {
files: [],
};
},
/* data: () => ({
files: [],
}), */
async mounted() {
this.getFilesList();
},
methods: {
getFilesList() {
axios
.get("http://localhost:8080/files")
.then((response) => {
this.files = response.data;
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
|
8c8d2f6d334f3404da41035a896cf3f5
|
{
"intermediate": 0.48816704750061035,
"beginner": 0.2646130621433258,
"expert": 0.24721990525722504
}
|
33,145
|
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
std::vector<int> v;
int main()
{
int n;
while(~scanf("%d", &n))
{
v.push_back(n);
}
sort(v.begin(), v.end());
int m = 0, s = 0;
for(auto it = v.begin(); it != v.end(); it++)
{
s += *it;
if(s > 5000) break;
else m++;
}
std::cout << m << std::endl;
}
|
3a14ec43d3f1646fc3c267ba09563f67
|
{
"intermediate": 0.33819344639778137,
"beginner": 0.46569639444351196,
"expert": 0.19611021876335144
}
|
33,146
|
crea un form in React con username, email e checkbox(terms&conditions). Usa useReducer
|
e7e8ad34ae1ce184c63aa2cb308d38ec
|
{
"intermediate": 0.41973477602005005,
"beginner": 0.22519858181476593,
"expert": 0.35506659746170044
}
|
33,147
|
write me the code for a Tetris game using python
|
ef6b69d4e08dcb965aaa22c78b9acbf2
|
{
"intermediate": 0.346342533826828,
"beginner": 0.43083271384239197,
"expert": 0.22282470762729645
}
|
33,148
|
In wpf how make visibility in checking if a proporty is null or not
|
86a48ccd746c62db36ef0ae43a459849
|
{
"intermediate": 0.4964097738265991,
"beginner": 0.137046679854393,
"expert": 0.36654356122016907
}
|
33,150
|
I used 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' and orderId is None and clientOrderId is None:
try:
active_signal = 'buy'
buy_entry_price = mark_price
print("Buy entry price:", buy_entry_price)
order = client.new_order(symbol=symbol, side='BUY' , type='MARKET', quantity=quantity)
print("Order opened: ", order)
orderId = order['orderId']
clientOrderId = order['clientOrderId']
except binance.error.ClientError as e:
print(f"Error executing long order: {e}")
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.")
if 'buy' in signals and orderId is not None and clientOrderId is not None:
try:
client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId)
print("Order closed successfully")
orderId = None
clientOrderId = None
order = client.new_order(symbol=symbol, side='BUY' , type='MARKET', quantity=quantity)
orderId = order['orderId']
clientOrderId = order['clientOrderId']
active_signal = 'buy'
buy_entry_price = mark_price
print("Buy entry price:", buy_entry_price)
print("Order opened: ", order)
except binance.error.ClientError as e:
print(f"Error closing order: {e}")
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 orderId is None and clientOrderId is None:
try:
active_signal = 'sell'
sell_entry_price = mark_price
print("Sell entry price", sell_entry_price)
order = client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
orderId = order['orderId']
clientOrderId = order['clientOrderId']
print("Order opened: ", order)
except binance.error.ClientError as e:
print(f"Error opening order: {e}")
if 'sell' in signals and orderId is not None and clientOrderId is not None:
try:
client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId)
print("Order closed successfully")
orderId = None
clientOrderId = None
active_signal = 'sell'
sell_entry_price = mark_price
print("Sell entry price", sell_entry_price)
order = client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
orderId = order['orderId']
clientOrderId = order['clientOrderId']
print("Order opened: ", order)
except binance.error.ClientError as e:
print(f"Error closing order: {e}")
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)
But i getting ERROR: Error opening order: (400, -4164, "Order's notional must be no smaller than 20 (unless you choose reduce only).", {'Date': 'Thu, 30 Nov 2023 15:26:01 GMT', 'Content-Type': 'application/json', 'Content-Length': '99', 'Connection': 'keep-alive', 'Server': 'Tengine', 'x-mbx-used-weight-1m': '-1', 'x-mbx-order-count-10s': '1', 'x-mbx-order-count-1m': '1', 'x-response-time': '0ms', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS'})
|
f2ff43d3b9f3e1a6fa2e58c8361b8127
|
{
"intermediate": 0.29066020250320435,
"beginner": 0.3510013520717621,
"expert": 0.35833844542503357
}
|
33,151
|
使用visualpython online完成以下任务
1.用这个colab笔记本内的内容替换wine数据 笔记本外链:https://
colab.research.google.com/drive/1jm4M6t1z5OAo7XHKRhDTTY79MtYD8njy
2.使用Gridsearch创建最佳决策树
3.直接发我文本代码就可以
数据如下:
mport pandas as pd
from sklearn.datasets import load_wine
wine = load_wine()
df = pd.DataFrame(wine.data, columns=wine.feature_names)
df['class'] = wine.target
df.tail(
|
ac55c5d0803213efc8f3db8aa7b84ae7
|
{
"intermediate": 0.3828299641609192,
"beginner": 0.34645333886146545,
"expert": 0.2707166373729706
}
|
33,152
|
使用visualpython online完成以下任务
1.用这个colab笔记本内的内容替换wine数据 笔记本外链:https://
colab.research.google.com/drive/1jm4M6t1z5OAo7XHKRhDTTY79MtYD8njy
2.使用Gridsearch创建最佳决策树
3.直接发我文本代码就可以
数据如下:
mport pandas as pd
from sklearn.datasets import load_wine
wine = load_wine()
df = pd.DataFrame(wine.data, columns=wine.feature_names)
df['class'] = wine.target
df.tail(
|
8c8363249b842a4056091c34516ed769
|
{
"intermediate": 0.3828299641609192,
"beginner": 0.34645333886146545,
"expert": 0.2707166373729706
}
|
33,153
|
#include <iostream>
#include <vector>
struct Node {
int data;
int left;
int right;
int height;
};
int CalcHeight(int index, Node arr[]) {
if (index == -1) return 0;
if (arr[index].height > 0) return arr[index].height;
arr[index].height = 1 + std::max(CalcHeight(arr[index].left, arr), CalcHeight(arr[index].right, arr));
return arr[index].height;
}
int CalcBalance(int index, Node arr[]) {
if (index == -1) return 0;
return CalcHeight(arr[index].right, arr) - CalcHeight(arr[index].left, arr);
}
void LeftRotate(Node arr[]) {
}
int main() {
int n;
int data;
int left;
int right;
std::cin >> n;
Node arr[n];
for (int i = 0; i < n; ++i) {
std::cin >> data >> left >> right;
arr[i].data = data;
arr[i].left = left - 1;
arr[i].right = right - 1;
arr[i].height = 0;
}
for (int i = 0; i < n; ++i) {
arr[i].height = CalcHeight(i, arr);
}
for (int i = 0; i < n; ++i) {
std::cout << CalcBalance(i, arr) << '\n';
}
}
напиши левый поворот относительно вершины дерева
|
2962e9c1bba7be276b9bb30539a9ff34
|
{
"intermediate": 0.3413883149623871,
"beginner": 0.2554474174976349,
"expert": 0.4031643271446228
}
|
33,154
|
Is there a very small hosts file that i use for windows 11 that will a fair amount of ads? but it has to be super lightweight and not break anything. I want it mostly for tracking
|
12ac95e567cba0e8a5c0727aff1009c3
|
{
"intermediate": 0.4799167811870575,
"beginner": 0.257315993309021,
"expert": 0.2627671957015991
}
|
33,155
|
File "/home/rickard/Documents/rs232/newocr.py", line 20, in <module>
cv2.imshow("Cropped Image", cropped_image)
cv2.error: OpenCV(4.8.0) /io/opencv/modules/highgui/src/window.cpp:1272: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'
|
158e32544065074cafce83cdfab00410
|
{
"intermediate": 0.627997875213623,
"beginner": 0.21268051862716675,
"expert": 0.15932157635688782
}
|
33,156
|
public class Bank
{
public decimal Balance { get; private set; }
public void AddMoney(decimal amount)
{
if (amount < 1)
{
throw new ArgumentException($"{nameof(amount)} must be positive and non zero");
}
Balance += amount;
}
public void TakeMoney(decimal amount)
{
if (amount > Balance)
{
throw new ArgumentException("Not enough money for transfer");
}
Balance -= amount;
}
} just write tests for this class framework for tests XUnit
|
e4ae10f90a4ed3090a6c2b5536b2701e
|
{
"intermediate": 0.4750675857067108,
"beginner": 0.32914650440216064,
"expert": 0.19578589498996735
}
|
33,157
|
public class PlayerBankBuilder : IBankBuilder
{
private readonly long _minInitBalance;
private readonly long _maxInitBalance;
private Bank _currentInstanceOfBank;
private readonly Random _rnd;
public PlayerBankBuilder(long minInitBalance, long maxInitBalance)
{
if (minInitBalance < 1)
throw new ArgumentException($"{nameof(minInitBalance)} must be positive and not 0");
if (maxInitBalance < 1)
throw new ArgumentException($"{nameof(maxInitBalance)} must be positive and not 0");
if (minInitBalance > maxInitBalance)
throw new ArgumentException($"{nameof(minInitBalance)} must be lower or equal {nameof(maxInitBalance)}");
_minInitBalance = minInitBalance;
_maxInitBalance = maxInitBalance;
_currentInstanceOfBank = new Bank();
_rnd = new Random();
}
public void BuildBalance()
{
_currentInstanceOfBank.AddMoney(_rnd.NextInt64(_minInitBalance, _maxInitBalance));
}
public Bank GetBank()
{
return _currentInstanceOfBank;
}
public void ResetInstance()
{
_currentInstanceOfBank = new Bank();
}
} write tests xunit
|
8735ac393cef5a3deba632918338d03b
|
{
"intermediate": 0.41420549154281616,
"beginner": 0.33227792382240295,
"expert": 0.2535165548324585
}
|
33,158
|
how to calculate angular velocity for new direction in unity using only math library
|
b8b0d8a0452bff3ddf65e1aa5f22283f
|
{
"intermediate": 0.5868663787841797,
"beginner": 0.26230624318122864,
"expert": 0.1508273333311081
}
|
33,159
|
use the collaborate filtering to deal with the NA
|
8740ed012713dce2c492c6b68d3fb9f5
|
{
"intermediate": 0.3272813558578491,
"beginner": 0.33491310477256775,
"expert": 0.33780553936958313
}
|
33,160
|
Widget videoTest(aPrefix.Assets primaryAsset) {
if (primaryAsset.type!.toLowerCase() == "video" && primary) {
setState(() {
isVideoInitialize = true;
type = 'video';
url = primaryAsset.url!;
primary = true;
// mutes the video
_controller.setVolume(0);
// Plays the video once the widget is build and loaded.
_controller.play();
});
_controller = VideoPlayerController.network(getImgURL(primaryAsset.url));
_initializeVideoPlayerFuture = _controller.initialize();
}
if (primaryAsset.type!.toLowerCase() == 'image' && primary) {
setState(() {
type = primaryAsset.type!.toLowerCase();
url = primaryAsset.url!;
primary = true;
});
}
return type == 'video'
? FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
)
: imageCard(url);
}add swiper in this widget to swipe between photos in another widget
|
2a74916a9a2bdc0443ac76a2aa936164
|
{
"intermediate": 0.4380064010620117,
"beginner": 0.2450210303068161,
"expert": 0.31697261333465576
}
|
33,161
|
Assembly Language, Make an Assembly Program to finish the following tasks:
- Use Loop control statement to sum the following numbers up, and store the result in a 8-byte qSum variable. Each number has 8 bytes.
5+10+15+20+…+100
- Use Loop control statement to push each number onto the stack (Steps 1 and 2 can be in the same loop)
- After steps 1 and 2, use another loop to pop each number from the stack to an array (qArray). The array should contain a reversed order of numbers, such as 100, 95, 90,…15,10,5.
|
10e185052604290d41179e097b70bbb8
|
{
"intermediate": 0.07922813296318054,
"beginner": 0.8515770435333252,
"expert": 0.06919480860233307
}
|
33,162
|
#include <iostream>
struct Node {
int data;
int left;
int right;
int height;
};
int Height(int index, Node arr[]) {
if (index == -1) return 0;
if (arr[index].height > 0) return arr[index].height;
arr[index].height = 1 + std::max(Height(arr[index].left, arr), Height(arr[index].right, arr));
return arr[index].height;
}
int Balance(int index, Node arr[]) {
if (index == -1) return 0;
return Height(arr[index].right, arr) - Height(arr[index].left, arr);
}
int RightRotate(int root, Node arr[], int n) {
int new_root = arr[root].left;
arr[root].left = arr[new_root].right;
arr[new_root].right = root;
for (int i = 0; i < n; ++i) {
arr[i].height = Height(i, arr);
}
return new_root;
}
int LeftRotate(int root, Node arr[], int n) {
int new_root = arr[root].right;
arr[root].right = arr[new_root].left;
arr[new_root].left = root;
for (int i = 0; i < n; ++i) {
arr[i].height = Height(i, arr);
}
return new_root;
}
int main() {
int n;
int data, left, right;
std::cin >> n;
Node arr[n];
for (int i = 0; i < n; ++i) {
std::cin >> data >> left >> right;
arr[i].data = data;
arr[i].left = left - 1;
arr[i].right = right - 1;
arr[i].height = 0;
}
for (int i = 0; i < n; ++i) {
arr[i].height = Height(i, arr);
}
int root = 0;
if (Balance(arr[arr[root].right].left, arr) > Balance(arr[arr[root].right].right, arr)) {
arr[root].right = RightRotate(arr[root].right, arr, n);
}
root = LeftRotate(root, arr, n);
std::cout << n << '\n';
for (int i = 0; i < n; ++i) {
std::cout << arr[i].data << ' ';
std::cout << (arr[i].left == -1 ? 0 : arr[i].left + 1) << ' ';
std::cout << (arr[i].right == -1 ? 0 : arr[i].right + 1) << '\n';
}
}
не проходит тесты для этой задачи как думаешь почему
|
b901d3dd416dd09efb862392f5d913d4
|
{
"intermediate": 0.3178665041923523,
"beginner": 0.42833462357521057,
"expert": 0.25379881262779236
}
|
33,163
|
how to use capacitive sensor to measure electric field intensity
|
c9de9e10c35c79d7b95dba0fc83ce510
|
{
"intermediate": 0.3595309555530548,
"beginner": 0.39353978633880615,
"expert": 0.24692925810813904
}
|
33,164
|
Assembly Language, Make an Assembly Program to finish the following tasks:
- Use Loop control statement to sum the following numbers up, and store the result in a 8-byte qSum variable. Each number has 8 bytes.
5+10+15+20+…+100
- Use Loop control statement to push each number onto the stack (Steps 1 and 2 can be in the same loop)
- After steps 1 and 2, use another loop to pop each number from the stack to an array (qArray). The array should contain a reversed order of numbers, such as 100, 95, 90,…15,10,5.
|
381387c554e8e2ffca59cdfc3b74c9ec
|
{
"intermediate": 0.07999663054943085,
"beginner": 0.85394686460495,
"expert": 0.06605648994445801
}
|
33,165
|
I ran the following code for a binary classification task w/ an SVM in both R (first sample) and Python (second example).
Given randomly generated data (X) and response (Y), this code performs leave group out cross validation 1000 times. Each entry of Y is therefore the mean of the prediction across CV iterations.
Computing area under the curve should give ~0.5, since X and Y are completely random. However, this is not what we see. Area under the curve is frequently significantly higher than 0.5. The number of rows of X is very small, which can obviously cause problems.
Any idea what could be happening here? I know that I can either increase the number of rows of X or decrease the number of columns to mediate the problem, but I am looking for other issues.
Y=as.factor(rep(c(1,2), times=14))
X=matrix(runif(length(Y)*100), nrow=length(Y))
library(e1071)
library(pROC)
colnames(X)=1:ncol(X)
iter=1000
ansMat=matrix(NA,length(Y),iter)
for(i in seq(iter)){
#get train
train=sample(seq(length(Y)),0.5*length(Y))
if(min(table(Y[train]))==0)
next
#test from train
test=seq(length(Y))[-train]
#train model
XX=X[train,]
YY=Y[train]
mod=svm(XX,YY,probability=FALSE)
XXX=X[test,]
predVec=predict(mod,XXX)
RFans=attr(predVec,'decision.values')
ansMat[test,i]=as.numeric(predVec)
}
ans=rowMeans(ansMat,na.rm=TRUE)
r=roc(Y,ans)$auc
print(r)
Similarly, when I implement the same thing in Python I get similar results.
Y = np.array([1, 2]*14)
X = np.random.uniform(size=[len(Y), 100])
n_iter = 1000
ansMat = np.full((len(Y), n_iter), np.nan)
for i in range(n_iter):
# Get train/test index
train = np.random.choice(range(len(Y)), size=int(0.5*len(Y)), replace=False, p=None)
if len(np.unique(Y)) == 1:
continue
test = np.array([i for i in range(len(Y)) if i not in train])
# train model
mod = SVC(probability=False)
mod.fit(X=X[train, :], y=Y[train])
# predict and collect answer
ansMat[test, i] = mod.predict(X[test, :])
ans = np.nanmean(ansMat, axis=1)
fpr, tpr, thresholds = roc_curve(Y, ans, pos_label=1)
print(auc(fpr, tpr))`
|
56197851c115e5fa8c0a4a547cc22bc9
|
{
"intermediate": 0.4072783589363098,
"beginner": 0.34630635380744934,
"expert": 0.24641525745391846
}
|
33,166
|
how do i create a android chat app from scratch with number verification system and location function to locate people using the same app near by
|
25ba1d59999e35aeb11a72d26fd96b2d
|
{
"intermediate": 0.37818828225135803,
"beginner": 0.2400648146867752,
"expert": 0.3817468583583832
}
|
33,167
|
Make an Assembly Program to finish the following tasks:
1. Use Loop control statement to sum the following numbers up, and store the result in a 8-byte qSum variable. Each number has 8 bytes.
5+10+15+20+…+100
2. Use Loop control statement to push each number onto the stack (Steps 1 and 2 can be in the same loop)
3. After steps 1 and 2, use another loop to pop each number from the stack to an array (qArray). The array should contain a reversed order of numbers, such as 100, 95, 90,…15,10,5.
|
120b70a9c343bd4382a5d425642d5312
|
{
"intermediate": 0.2429562360048294,
"beginner": 0.5799644589424133,
"expert": 0.17707929015159607
}
|
33,168
|
Make an Assembly Program to finish the following tasks:
- Use Loop control statement to sum the following numbers up, and store the result in a 8-byte qSum variable. Each number has 8 bytes.
5+10+15+20+…+100
- Use Loop control statement to push each number onto the stack (Steps 1 and 2 can be in the same loop)
- After steps 1 and 2, use another loop to pop each number from the stack to an array (qArray). The array should contain a reversed order of numbers, such as 100, 95, 90,…15,10,5.
|
d467207afd56cd080d9b30d4dca975b3
|
{
"intermediate": 0.21944472193717957,
"beginner": 0.6138778328895569,
"expert": 0.16667744517326355
}
|
33,169
|
DeprecationWarning: concurrency_count has been deprecated. Set the concurrency_limit directly on event listeners e.g. btn.click(fn, ..., concurrency_limit=10) or gr.Interface(concurrency_limit=10). If necessary, the total number of workers can be configured via `max_threads` in launch().
|
5957f7fd536ac0e312a98c649b82ce17
|
{
"intermediate": 0.4123862385749817,
"beginner": 0.2451622039079666,
"expert": 0.3424515724182129
}
|
33,170
|
Determine if G(z) = (z - 6) * ln(z) is increasing or decreasing at the following point z = 5
|
5716d3f73a64e35b060f36758a702ca6
|
{
"intermediate": 0.3201356828212738,
"beginner": 0.2729920446872711,
"expert": 0.4068722724914551
}
|
33,171
|
I ran the following code for a binary classification task w/ an SVM in both R (first sample) and Python (second example).
Given randomly generated data (X) and response (Y), this code performs leave group out cross validation 1000 times. Each entry of Y is therefore the mean of the prediction across CV iterations.
Computing area under the curve should give ~0.5, since X and Y are completely random. However, this is not what we see. Area under the curve is frequently significantly higher than 0.5. The number of rows of X is very small, which can obviously cause problems.
Any idea what could be happening here? I know that I can either increase the number of rows of X or decrease the number of columns to mediate the problem, but I am looking for other issues.
Y=as.factor(rep(c(1,2), times=14))
X=matrix(runif(length(Y)*100), nrow=length(Y))
library(e1071)
library(pROC)
colnames(X)=1:ncol(X)
iter=1000
ansMat=matrix(NA,length(Y),iter)
for(i in seq(iter)){
#get train
train=sample(seq(length(Y)),0.5*length(Y))
if(min(table(Y[train]))==0)
next
#test from train
test=seq(length(Y))[-train]
#train model
XX=X[train,]
YY=Y[train]
mod=svm(XX,YY,probability=FALSE)
XXX=X[test,]
predVec=predict(mod,XXX)
RFans=attr(predVec,'decision.values')
ansMat[test,i]=as.numeric(predVec)
}
ans=rowMeans(ansMat,na.rm=TRUE)
r=roc(Y,ans)$auc
print(r)
Similarly, when I implement the same thing in Python I get similar results.
Y = np.array([1, 2]*14)
X = np.random.uniform(size=[len(Y), 100])
n_iter = 1000
ansMat = np.full((len(Y), n_iter), np.nan)
for i in range(n_iter):
# Get train/test index
train = np.random.choice(range(len(Y)), size=int(0.5*len(Y)), replace=False, p=None)
if len(np.unique(Y)) == 1:
continue
test = np.array([i for i in range(len(Y)) if i not in train])
# train model
mod = SVC(probability=False)
mod.fit(X=X[train, :], y=Y[train])
# predict and collect answer
ansMat[test, i] = mod.predict(X[test, :])
ans = np.nanmean(ansMat, axis=1)
fpr, tpr, thresholds = roc_curve(Y, ans, pos_label=1)
print(auc(fpr, tpr))`
|
cb96bab0a43c1512d1e10d8cbcafa8a1
|
{
"intermediate": 0.4072783589363098,
"beginner": 0.34630635380744934,
"expert": 0.24641525745391846
}
|
33,172
|
#[macro_use] extern crate rocket;
use rocket::*;
extern crate rocket_dyn_templates;
use rocket_dyn_templates::Template;
#[get("/")]
fn index() -> Template {
Template.render("index", &context)
}
#[launch]
fn rocket() -> _ {
build().mount("/", routes![index])
}
error: at least one of "tera" or "handlebars" features must be enabled
--> /Users/alexkatkov/.cargo/registry/src/index.crates.io-6f17d22bba15001f/rocket_dyn_templates-0.1.0/src/lib.rs:142:1
|
142 | compile_error!("at least one of \"tera\" or \"handlebars\" features must be enabled");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: could not compile `rocket_dyn_templates` (lib) due to previous error
warning: build failed, waiting for other jobs to finish...
|
f35c6555e5e1ed0d6db12b7e67312828
|
{
"intermediate": 0.585546612739563,
"beginner": 0.25608906149864197,
"expert": 0.15836435556411743
}
|
33,173
|
Array& Array::operator[](size_t index) {
static int operator_count = 0;
if (operator_count == 0) {
current_x_ = index;
}
if (operator_count == 1) {
current_y_ = index;
}
if (operator_count == 2) {
current_z_ = index;
operator_count = -1;
}
++operator_count;
return *this;
} how foes it work
|
7be9ab4acc692a7f77339c5f8a706ba8
|
{
"intermediate": 0.4665836989879608,
"beginner": 0.3398600220680237,
"expert": 0.1935563087463379
}
|
33,174
|
explain how to solve this in python:
Sum up all of the evens
1 PT
In this problem, you'll implement a function that takes a list of numbers and returns the sum of all of the even numbers in the list.
Sample input/outputs:
numbers sum_evens(numbers)
[] 0
[3,7] 0
[4,7] 4
[1,2,3,4,5,6] 12
|
e2feb92b8108430b5db680eb412718c4
|
{
"intermediate": 0.47299110889434814,
"beginner": 0.17881642282009125,
"expert": 0.3481924831867218
}
|
33,175
|
I ran the following code for a binary classification task w/ an SVM in both R (first sample) and Python (second example).
Given randomly generated data (X) and response (Y), this code performs leave group out cross validation 1000 times. Each entry of Y is therefore the mean of the prediction across CV iterations.
Computing area under the curve should give ~0.5, since X and Y are completely random. However, this is not what we see. Area under the curve is frequently significantly higher than 0.5. The number of rows of X is very small, which can obviously cause problems.
Any idea what could be happening here? I know that I can either increase the number of rows of X or decrease the number of columns to mediate the problem, but I am looking for other issues.
Y=as.factor(rep(c(1,2), times=14))
X=matrix(runif(length(Y)100), nrow=length(Y))
library(e1071)
library(pROC)
colnames(X)=1:ncol(X)
iter=1000
ansMat=matrix(NA,length(Y),iter)
for(i in seq(iter)){
#get train
train=sample(seq(length(Y)),0.5length(Y))
if(min(table(Y[train]))==0)
next
#test from train
test=seq(length(Y))[-train]
#train model
XX=X[train,]
YY=Y[train]
mod=svm(XX,YY,probability=FALSE)
XXX=X[test,]
predVec=predict(mod,XXX)
RFans=attr(predVec,‘decision.values’)
ansMat[test,i]=as.numeric(predVec)
}
ans=rowMeans(ansMat,na.rm=TRUE)
r=roc(Y,ans)$auc
print®
Similarly, when I implement the same thing in Python I get similar results.
Y = np.array([1, 2]14)
X = np.random.uniform(size=[len(Y), 100])
n_iter = 1000
ansMat = np.full((len(Y), n_iter), np.nan)
for i in range(n_iter):
# Get train/test index
train = np.random.choice(range(len(Y)), size=int(0.5len(Y)), replace=False, p=None)
if len(np.unique(Y)) == 1:
continue
test = np.array([i for i in range(len(Y)) if i not in train])
# train model
mod = SVC(probability=False)
mod.fit(X=X[train, :], y=Y[train])
# predict and collect answer
ansMat[test, i] = mod.predict(X[test, :])
ans = np.nanmean(ansMat, axis=1)
fpr, tpr, thresholds = roc_curve(Y, ans, pos_label=1)
print(auc(fpr, tpr))`
|
7a55c7c5acdc57cf8ba6ebdfdd47ac87
|
{
"intermediate": 0.4625128209590912,
"beginner": 0.13076777756214142,
"expert": 0.406719446182251
}
|
33,176
|
#include <iostream>
#include <algorithm>
struct Node {
int data;
int left;
int right;
int height;
};
int Height(int index, Node arr[]) {
if (index == -1) return 0;
if (arr[index].height > 0) return arr[index].height;
arr[index].height = 1 + std::max(Height(arr[index].left, arr), Height(arr[index].right, arr));
return arr[index].height;
}
int Balance(int index, Node arr[]) {
if (index == -1) return 0;
return Height(arr[index].right, arr) - Height(arr[index].left, arr);
}
void UpdateHeight(int index, Node arr[]) {
if (index == -1) return;
arr[index].height = 1 + std::max(Height(arr[index].left, arr), Height(arr[index].right, arr));
}
int RightRotate(int y, Node arr[]) {
int x = arr[y].left;
int T2 = arr[x].right;
arr[x].right = y;
arr[y].left = T2;
UpdateHeight(y, arr);
UpdateHeight(x, arr);
return x;
}
int LeftRotate(int x, Node arr[]) {
int y = arr[x].right;
int T2 = arr[y].left;
arr[y].left = x;
arr[x].right = T2;
UpdateHeight(x, arr);
UpdateHeight(y, arr);
return y;
}
void print(int index, Node arr[], int n) {
if (index == -1) return;
// +1 на входе, так как индексы начинаются с 1, а не с 0
std::cout << arr[index].data << ' ';
std::cout << ((arr[index].left == -1) ? 0 : arr[index].left + 1) << ' ';
std::cout << ((arr[index].right == -1) ? 0 : arr[index].right + 1) << '\n';
// Печать левого и правого ребенка узла
if(arr[index].left != -1) {
print(arr[index].left, arr, n);
}
if(arr[index].right != -1) {
print(arr[index].right, arr, n);
}
}
int main() {
int n;
std::cin >> n;
Node arr[n];
for (int i = 0; i < n; ++i) {
std::cin >> arr[i].data;
std::cin >> arr[i].left >> arr[i].right;
arr[i].left -= 1;
arr[i].right -= 1;
arr[i].height = 0;
}
for (int i = 0; i < n; ++i) {
Height(i, arr);
}
int root = 0;
if (Balance(arr[root].right, arr) < 0) {
arr[root].right = RightRotate(arr[root].right, arr);
}
root = LeftRotate(root, arr);
std::cout << n << std::endl;
print(root, arr, n);
return 0;
}
ты можешь добавить в структуру переменную которая показывает номер узла(нумерация по уровням слева направо)
|
2e85fe8c21b0957dabe7411db29a761a
|
{
"intermediate": 0.3215477466583252,
"beginner": 0.35238638520240784,
"expert": 0.3260658383369446
}
|
33,177
|
hi
|
8617c10e7c5356f10c2b09ecdebce707
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
33,178
|
So i'm trying to run a game with from -force-d3d12 (last epoch). it is a unity game. The colors are pretty terrible tbh everything is washed out or too bright. what can i do to fix it?
|
5e4e2384cc378a63d5d5821c79238905
|
{
"intermediate": 0.4300716817378998,
"beginner": 0.22673004865646362,
"expert": 0.3431982696056366
}
|
33,179
|
Can you optimize this for world of warcraft 3.3.5a (10+ year old engine). The game is super cpu limited already. I use a 4gb patch to the exe to allow more ram because it's 32 bit.
here's my specs:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
here's the dxvk conf i want you to optimizee
# Supported values: True, False
# dxgi.enableHDR = True
# Supported values: True, False
# dxgi.deferSurfaceCreation = False
# d3d9.deferSurfaceCreation = False
# Supported values : 0 - 16
# dxgi.maxFrameLatency = 0
# d3d9.maxFrameLatency = 0
# Supported values : Any non-negative integer
# dxgi.maxFrameRate = 0
# d3d9.maxFrameRate = 0
# Supported values: Any four-digit hex number.
# dxgi.customDeviceId = 0000
# dxgi.customVendorId = 0000
# d3d9.customDeviceId = 0000
# d3d9.customVendorId = 0000
# dxgi.customDeviceDesc = ""
# d3d9.customDeviceDesc = ""
# Supported values: Auto, True, False
# dxgi.hideNvidiaGpu = Auto
# Supported values: Auto, True, False
# dxgi.hideAmdGpu = Auto
# Supported values: Auto, True, False
# dxgi.hideIntelGpu = Auto
# Supported values: Any number in Megabytes.
# dxgi.maxDeviceMemory = 0
# dxgi.maxSharedMemory = 0
# Supported values: True, False
# dxgi.emulateUMA = False
# Supported values: Any number greater than or equal to 2.
# dxgi.numBackBuffers = 0
# d3d9.numBackBuffers = 0
# Supported values: Any non-negative number
# dxgi.syncInterval = -1
# d3d9.presentInterval = -1
# Supported values: Auto, True, False
# dxvk.tearFree = Auto
# Supported values: True, False
# d3d11.dcSingleUseMode = True
# Supported values: 9_1, 9_2, 9_3, 10_0, 10_1, 11_0, 11_1, 12_0, 12_1
# d3d11.maxFeatureLevel = 12_1
# Supported values: Any number between 8 and 64
# d3d11.maxTessFactor = 0
# Supported values: True, False
# d3d11.relaxedBarriers = False
# Supported values: True, False
# d3d11.ignoreGraphicsBarriers = False
# Supported values: Any number between 0 and 16
# d3d11.samplerAnisotropy = -1
# d3d9.samplerAnisotropy = -1
# Supported values: Any number between -2.0 and 1.0
# d3d11.samplerLodBias = 0.0
# d3d9.samplerLodBias = 0.0
# Supported values: True, False
# d3d11.clampNegativeLodBias = False
# d3d9.clampNegativeLodBias = False
# Supported values: True, False
# d3d11.invariantPosition = True
# d3d9.invariantPosition = True
# Supported values: True, False
# d3d11.forceSampleRateShading = False
# d3d9.forceSampleRateShading = False
# Supported values: True, False
# d3d11.disableMsaa = False
# Supported values: True, False
# d3d11.zeroWorkgroupMemory = False
# Resource size limit for implicit discards, in kilobytes. For small staging
# resources mapped with MAP_WRITE, DXVK will sometimes allocate new backing
# storage in order to avoid GPU synchronization, so setting this too high
# may cause memory issues, setting it to -1 disables the feature.
# d3d11.maxImplicitDiscardSize = 256
# Resource size limit for buffer-mapped dynamic images, in kilobytes.
# A higher threshold may reduce memory usage and PCI-E bandwidth in
# some games, but may also increase GPU synchronizations. Setting it
# to -1 disables the feature.
# d3d11.maxDynamicImageBufferSize = -1
# Allocates dynamic resources with the given set of bind flags in
# cached system memory rather than uncached memory or host-visible
# VRAM, in order to allow fast readback from the CPU. This is only
# useful for buggy applications, and may reduce GPU-bound performance.
#
# Supported values: Any combination of the following:
# - v: Vertex buffers
# - i: Index buffers
# - c: Constant buffers
# - r: Shader resources
# - a: All dynamic resources
# d3d11.cachedDynamicResources = ""
# d3d11.enableContextLock = False
# Supported values:
# - 0 to use all available CPU cores
# - any positive number to enforce the thread count
# dxvk.numCompilerThreads = 0
# Supported values:
# - Auto: Don't change the default
# - True, False: Always enable / disable
# dxvk.useRawSsbo = Auto
# Supported values:
# - 0 to use the defaults
# - any positive integer to limit the chunk size, in MiB
# dxvk.maxChunkSize = 0
# Supported values:
# - Auto: Enable if supported, and compile optimized pipelines in the background
# - True: Enable if supported, but do not compile optimized pipelines
# - False: Always disable the feature
# dxvk.enableGraphicsPipelineLibrary = Auto
# Supported values:
# - Auto: Enable tracking for 32-bit applications only
# - True: Always enable tracking
# - False: Always disable tracking
# dxvk.trackPipelineLifetime = Auto
|
633aa47c702099746514e41bba6a8a22
|
{
"intermediate": 0.3313690721988678,
"beginner": 0.39223697781562805,
"expert": 0.27639394998550415
}
|
33,180
|
Can you optimize this for world of warcraft 3.3.5a (10+ year old engine). The game is super cpu limited already. I use a 4gb patch to the exe to allow more ram because it’s 32 bit. Just give me the values without any comments or explanations
here’s my specs:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
here’s the dxvk conf i want you to optimizee
# Supported values: True, False
# dxgi.enableHDR = True
# Supported values: True, False
# dxgi.deferSurfaceCreation = False
# d3d9.deferSurfaceCreation = False
# Supported values : 0 - 16
# dxgi.maxFrameLatency = 0
# d3d9.maxFrameLatency = 0
# Supported values : Any non-negative integer
# dxgi.maxFrameRate = 0
# d3d9.maxFrameRate = 0
# Supported values: Any four-digit hex number.
# dxgi.customDeviceId = 0000
# dxgi.customVendorId = 0000
# d3d9.customDeviceId = 0000
# d3d9.customVendorId = 0000
# dxgi.customDeviceDesc = “”
# d3d9.customDeviceDesc = “”
# Supported values: Auto, True, False
# dxgi.hideNvidiaGpu = Auto
# Supported values: Auto, True, False
# dxgi.hideAmdGpu = Auto
# Supported values: Auto, True, False
# dxgi.hideIntelGpu = Auto
# Supported values: Any number in Megabytes.
# dxgi.maxDeviceMemory = 0
# dxgi.maxSharedMemory = 0
# Supported values: True, False
# dxgi.emulateUMA = False
# Supported values: Any number greater than or equal to 2.
# dxgi.numBackBuffers = 0
# d3d9.numBackBuffers = 0
# Supported values: Any non-negative number
# dxgi.syncInterval = -1
# d3d9.presentInterval = -1
# Supported values: Auto, True, False
# dxvk.tearFree = Auto
# Supported values: True, False
# d3d11.dcSingleUseMode = True
# Supported values: 9_1, 9_2, 9_3, 10_0, 10_1, 11_0, 11_1, 12_0, 12_1
# d3d11.maxFeatureLevel = 12_1
# Supported values: Any number between 8 and 64
# d3d11.maxTessFactor = 0
# Supported values: True, False
# d3d11.relaxedBarriers = False
# Supported values: True, False
# d3d11.ignoreGraphicsBarriers = False
# Supported values: Any number between 0 and 16
# d3d11.samplerAnisotropy = -1
# d3d9.samplerAnisotropy = -1
# Supported values: Any number between -2.0 and 1.0
# d3d11.samplerLodBias = 0.0
# d3d9.samplerLodBias = 0.0
# Supported values: True, False
# d3d11.clampNegativeLodBias = False
# d3d9.clampNegativeLodBias = False
# Supported values: True, False
# d3d11.invariantPosition = True
# d3d9.invariantPosition = True
# Supported values: True, False
# d3d11.forceSampleRateShading = False
# d3d9.forceSampleRateShading = False
# Supported values: True, False
# d3d11.disableMsaa = False
# Supported values: True, False
# d3d11.zeroWorkgroupMemory = False
# Resource size limit for implicit discards, in kilobytes. For small staging
# resources mapped with MAP_WRITE, DXVK will sometimes allocate new backing
# storage in order to avoid GPU synchronization, so setting this too high
# may cause memory issues, setting it to -1 disables the feature.
# d3d11.maxImplicitDiscardSize = 256
# Resource size limit for buffer-mapped dynamic images, in kilobytes.
# A higher threshold may reduce memory usage and PCI-E bandwidth in
# some games, but may also increase GPU synchronizations. Setting it
# to -1 disables the feature.
# d3d11.maxDynamicImageBufferSize = -1
# Allocates dynamic resources with the given set of bind flags in
# cached system memory rather than uncached memory or host-visible
# VRAM, in order to allow fast readback from the CPU. This is only
# useful for buggy applications, and may reduce GPU-bound performance.
#
# Supported values: Any combination of the following:
# - v: Vertex buffers
# - i: Index buffers
# - c: Constant buffers
# - r: Shader resources
# - a: All dynamic resources
# d3d11.cachedDynamicResources = “”
# d3d11.enableContextLock = False
# Supported values:
# - 0 to use all available CPU cores
# - any positive number to enforce the thread count
# dxvk.numCompilerThreads = 0
# Supported values:
# - Auto: Don’t change the default
# - True, False: Always enable / disable
# dxvk.useRawSsbo = Auto
# Supported values:
# - 0 to use the defaults
# - any positive integer to limit the chunk size, in MiB
# dxvk.maxChunkSize = 0
# Supported values:
# - Auto: Enable if supported, and compile optimized pipelines in the background
# - True: Enable if supported, but do not compile optimized pipelines
# - False: Always disable the feature
# dxvk.enableGraphicsPipelineLibrary = Auto
# Supported values:
# - Auto: Enable tracking for 32-bit applications only
# - True: Always enable tracking
# - False: Always disable tracking
# dxvk.trackPipelineLifetime = Auto
|
819780babb60b5b9a910d969ecc90195
|
{
"intermediate": 0.34125059843063354,
"beginner": 0.37186071276664734,
"expert": 0.28688865900039673
}
|
33,181
|
I ran the following code for a binary classification task w/ an SVM in both R (first sample) and Python (second example).
Given randomly generated data (X) and response (Y), this code performs leave group out cross validation 1000 times. Each entry of Y is therefore the mean of the prediction across CV iterations.
Computing area under the curve should give ~0.5, since X and Y are completely random. However, this is not what we see. Area under the curve is frequently significantly higher than 0.5. The number of rows of X is very small, which can obviously cause problems.
Any idea what could be happening here? I know that I can either increase the number of rows of X or decrease the number of columns to mediate the problem, but I am looking for other issues.
Y=as.factor(rep(c(1,2), times=14))
X=matrix(runif(length(Y)*100), nrow=length(Y))
library(e1071)
library(pROC)
colnames(X)=1:ncol(X)
iter=1000
ansMat=matrix(NA,length(Y),iter)
for(i in seq(iter)){
#get train
train=sample(seq(length(Y)),0.5*length(Y))
if(min(table(Y[train]))==0)
next
#test from train
test=seq(length(Y))[-train]
#train model
XX=X[train,]
YY=Y[train]
mod=svm(XX,YY,probability=FALSE)
XXX=X[test,]
predVec=predict(mod,XXX)
RFans=attr(predVec,'decision.values')
ansMat[test,i]=as.numeric(predVec)
}
ans=rowMeans(ansMat,na.rm=TRUE)
r=roc(Y,ans)$auc
print(r)
|
55c7f286e87184aca3feccfc6df01efe
|
{
"intermediate": 0.4096144735813141,
"beginner": 0.24999654293060303,
"expert": 0.3403889834880829
}
|
33,182
|
Can you optimize this for world of warcraft 3.3.5a (10+ year old engine). The game is super cpu limited already. I use a 4gb patch to the exe to allow more ram because it’s 32 bit. This game is directx 9
here’s my specs:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
here’s the dxvk conf i want you to optimizee
# Supported values: True, False
# dxgi.enableHDR = True
# Supported values: True, False
# dxgi.deferSurfaceCreation = False
# d3d9.deferSurfaceCreation = False
# Supported values : 0 - 16
# dxgi.maxFrameLatency = 0
# d3d9.maxFrameLatency = 0
# Supported values : Any non-negative integer
# dxgi.maxFrameRate = 0
# d3d9.maxFrameRate = 0
# Supported values: Any four-digit hex number.
# dxgi.customDeviceId = 0000
# dxgi.customVendorId = 0000
# d3d9.customDeviceId = 0000
# d3d9.customVendorId = 0000
# dxgi.customDeviceDesc = “”
# d3d9.customDeviceDesc = “”
# Supported values: Auto, True, False
# dxgi.hideNvidiaGpu = Auto
# Supported values: Auto, True, False
# dxgi.hideAmdGpu = Auto
# Supported values: Auto, True, False
# dxgi.hideIntelGpu = Auto
# Supported values: Any number in Megabytes.
# dxgi.maxDeviceMemory = 0
# dxgi.maxSharedMemory = 0
# Supported values: True, False
# dxgi.emulateUMA = False
# Supported values: Any number greater than or equal to 2.
# dxgi.numBackBuffers = 0
# d3d9.numBackBuffers = 0
# Supported values: Any non-negative number
# dxgi.syncInterval = -1
# d3d9.presentInterval = -1
# Supported values: Auto, True, False
# dxvk.tearFree = Auto
# Supported values: True, False
# d3d11.dcSingleUseMode = True
# Supported values: 9_1, 9_2, 9_3, 10_0, 10_1, 11_0, 11_1, 12_0, 12_1
# d3d11.maxFeatureLevel = 12_1
# Supported values: Any number between 8 and 64
# d3d11.maxTessFactor = 0
# Supported values: True, False
# d3d11.relaxedBarriers = False
# Supported values: True, False
# d3d11.ignoreGraphicsBarriers = False
# Supported values: Any number between 0 and 16
# d3d11.samplerAnisotropy = -1
# d3d9.samplerAnisotropy = -1
# Supported values: Any number between -2.0 and 1.0
# d3d11.samplerLodBias = 0.0
# d3d9.samplerLodBias = 0.0
# Supported values: True, False
# d3d11.clampNegativeLodBias = False
# d3d9.clampNegativeLodBias = False
# Supported values: True, False
# d3d11.invariantPosition = True
# d3d9.invariantPosition = True
# Supported values: True, False
# d3d11.forceSampleRateShading = False
# d3d9.forceSampleRateShading = False
# Supported values: True, False
# d3d11.disableMsaa = False
# Supported values: True, False
# d3d11.zeroWorkgroupMemory = False
# Resource size limit for implicit discards, in kilobytes. For small staging
# resources mapped with MAP_WRITE, DXVK will sometimes allocate new backing
# storage in order to avoid GPU synchronization, so setting this too high
# may cause memory issues, setting it to -1 disables the feature.
# d3d11.maxImplicitDiscardSize = 256
# Resource size limit for buffer-mapped dynamic images, in kilobytes.
# A higher threshold may reduce memory usage and PCI-E bandwidth in
# some games, but may also increase GPU synchronizations. Setting it
# to -1 disables the feature.
# d3d11.maxDynamicImageBufferSize = -1
# Allocates dynamic resources with the given set of bind flags in
# cached system memory rather than uncached memory or host-visible
# VRAM, in order to allow fast readback from the CPU. This is only
# useful for buggy applications, and may reduce GPU-bound performance.
#
# Supported values: Any combination of the following:
# - v: Vertex buffers
# - i: Index buffers
# - c: Constant buffers
# - r: Shader resources
# - a: All dynamic resources
# d3d11.cachedDynamicResources = “”
# d3d11.enableContextLock = False
# Supported values:
# - 0 to use all available CPU cores
# - any positive number to enforce the thread count
# dxvk.numCompilerThreads = 0
# Supported values:
# - Auto: Don’t change the default
# - True, False: Always enable / disable
# dxvk.useRawSsbo = Auto
# Supported values:
# - 0 to use the defaults
# - any positive integer to limit the chunk size, in MiB
# dxvk.maxChunkSize = 0
# Supported values:
# - Auto: Enable if supported, and compile optimized pipelines in the background
# - True: Enable if supported, but do not compile optimized pipelines
# - False: Always disable the feature
# dxvk.enableGraphicsPipelineLibrary = Auto
# Supported values:
# - Auto: Enable tracking for 32-bit applications only
# - True: Always enable tracking
# - False: Always disable tracking
# dxvk.trackPipelineLifetime = Auto
|
40aa93285ce918718772397681601f26
|
{
"intermediate": 0.3097251355648041,
"beginner": 0.3818465769290924,
"expert": 0.30842825770378113
}
|
33,183
|
can you prapare a schedule for my restaurent
|
b3cd978cc8ea82cf48fe410b0ee1ccfb
|
{
"intermediate": 0.434421181678772,
"beginner": 0.21107175946235657,
"expert": 0.3545069992542267
}
|
33,184
|
my PC:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
can you optimize the below config for my pc? It's for world of warcraft 3.3.5a which is a directx9 game that the 13+ year old engine that the cpu is limited and even the fastest cpus have problems with this game.
# Expose the HDR10 ColorSpace (DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020)
# to the application by default.
# This shows to the game that the global Windows 'HDR Mode' is enabled.
# Many (broken) games will need this to be set to consider exposing HDR output
# as determine it based on the DXGIOutput's current ColorSpace instead of
# using CheckColorSpaceSupport.
# This defaults to the value of the DXVK_HDR environment variable.
#
# Supported values: True, False
# dxgi.enableHDR = True
# Create the VkSurface on the first call to IDXGISwapChain::Present,
# rather than when creating the swap chain. Some games that start
# rendering with a different graphics API may require this option,
# or otherwise the window may stay black.
#
# Supported values: True, False
# dxgi.deferSurfaceCreation = False
# d3d9.deferSurfaceCreation = False
# Enforce a stricter maximum frame latency. Overrides the application
# setting specified by calling IDXGIDevice::SetMaximumFrameLatency.
# Setting this to 0 will have no effect.
#
# Supported values : 0 - 16
# dxgi.maxFrameLatency = 0
# d3d9.maxFrameLatency = 0
# Enables frame rate limiter. The main purpose of this is to work around
# bugs in games that have physics or other simulation tied to their frame
# rate, but do not provide their own limiter.
#
# Supported values : Any non-negative integer
# dxgi.maxFrameRate = 0
# d3d9.maxFrameRate = 0
# Override PCI vendor and device IDs reported to the application. Can
# cause the app to adjust behaviour depending on the selected values.
#
# Supported values: Any four-digit hex number.
# dxgi.customDeviceId = 0000
# dxgi.customVendorId = 0000
# d3d9.customDeviceId = 0000
# d3d9.customVendorId = 0000
# Override the reported device description
#
# Supported values: Any string.
# dxgi.customDeviceDesc = ""
# d3d9.customDeviceDesc = ""
# Report Nvidia GPUs as AMD GPUs. Unless NVAPI support is explicitly
# enabled through proton, this is done by default in order to work
# around crashes or low performance with Nvidia-speciic code paths
# in games, especially Unreal Engine.
#
# Supported values: Auto, True, False
# dxgi.hideNvidiaGpu = Auto
# Report AMD GPUs as Nvidia GPUs. This is only done for games that are
# known to have issues with AMDAGS or other AMD-specific code paths.
#
# Supported values: Auto, True, False
# dxgi.hideAmdGpu = Auto
# Report Intel GPUs as AMD GPUs. This is only done for games that are
# known to have issues with Intel-specific libraries such as XESS.
#
# Supported values: Auto, True, False
# dxgi.hideIntelGpu = Auto
# Override maximum amount of device memory and shared system memory
# reported to the application. This may fix texture streaming issues
# in games that do not support cards with large amounts of VRAM.
#
# Supported values: Any number in Megabytes.
# dxgi.maxDeviceMemory = 0
# dxgi.maxSharedMemory = 0
# Some games think we are on Intel given a lack of NVAPI or
# AGS/atiadlxx support. Report our device memory as shared memory,
# and some small amount for a "carveout".
# Supported values: True, False
# dxgi.emulateUMA = False
# Override back buffer count for the Vulkan swap chain.
# Setting this to 0 or less will have no effect.
#
# Supported values: Any number greater than or equal to 2.
# dxgi.numBackBuffers = 0
# d3d9.numBackBuffers = 0
# Overrides synchronization interval (Vsync) for presentation.
# Setting this to 0 disables vertical synchronization entirely.
# A positive value 'n' will enable Vsync and repeat the same
# image n times, and a negative value will have no effect.
#
# Supported values: Any non-negative number
# dxgi.syncInterval = -1
# d3d9.presentInterval = -1
# True enables the mailbox present mode in case regular Vsync is disabled.
# This should avoid tearing, but may be unsupported on some systems
# or require setting dxgi.numBackBuffers to a higher value in order
# to work properly.
#
# False enables the relaxed fifo present mode in case regular Vsync is enabled.
# This should result in tearing but reduce stutter if FPS are too low,
# but may be unsupported on some systems.
#
# Please do not report issues with this option.
#
# Supported values: Auto, True, False
# dxvk.tearFree = Auto
# Assume single-use mode for command lists created on deferred contexts.
# This may need to be disabled for some applications to avoid rendering
# issues, which may come at a significant performance cost.
#
# Supported values: True, False
# d3d11.dcSingleUseMode = True
# Override the maximum feature level that a D3D11 device can be created
# with. Setting this to a higher value may allow some applications to run
# that would otherwise fail to create a D3D11 device.
#
# Supported values: 9_1, 9_2, 9_3, 10_0, 10_1, 11_0, 11_1, 12_0, 12_1
# d3d11.maxFeatureLevel = 12_1
# Overrides the maximum allowed tessellation factor. This can be used to
# improve performance in titles which overuse tessellation.
#
# Supported values: Any number between 8 and 64
# d3d11.maxTessFactor = 0
# Enables relaxed pipeline barriers around UAV writes.
#
# This may improve performance in some games, but may also introduce
# rendering issues. Please don't report bugs with the option enabled.
#
# Supported values: True, False
# d3d11.relaxedBarriers = False
# Ignores barriers around UAV writes from fragment shaders.
#
# This may improve performance in some games, but may also introduce
# rendering issues. Please don't report bugs with the option enabled.
#
# Supported values: True, False
# d3d11.ignoreGraphicsBarriers = False
# Overrides anisotropic filtering for all samplers. Set this to a positive
# value to enable AF for all samplers in the game, or to 0 in order to
# disable AF entirely. Negative values will have no effect.
#
# Supported values: Any number between 0 and 16
# d3d11.samplerAnisotropy = -1
# d3d9.samplerAnisotropy = -1
# Changes the mipmap LOD bias for all samplers. The given number will be
# added to the LOD bias provided by the application, rather than replacing
# it entirely. Positive values will reduce texture detail, while negative
# values may increase sharpness at the cost of shimmer.
#
# Supported values: Any number between -2.0 and 1.0
# d3d11.samplerLodBias = 0.0
# d3d9.samplerLodBias = 0.0
# Clamps any negative LOD bias to 0. Applies after samplerLodBias has been
# applied. May help with games that use a high negative LOD bias by default.
#
# Supported values: True, False
# d3d11.clampNegativeLodBias = False
# d3d9.clampNegativeLodBias = False
# Declares vertex positions as invariant in order to solve
# potential Z-fighting issues at a small performance cost.
#
# Supported values: True, False
# d3d11.invariantPosition = True
# d3d9.invariantPosition = True
# Forces per-sample rate shading when MSAA is enabled, rather than per-pixel
# shading. May improve visual clarity at a significant performance cost, but
# may also introduce visual issues in some games.
#
# Supported values: True, False
# d3d11.forceSampleRateShading = False
# d3d9.forceSampleRateShading = False
# Forces the sample count of all textures to 1, and performs
# the needed fixups in resolve operations and shaders.
#
# Supported values: True, False
# d3d11.disableMsaa = False
# Clears workgroup memory in compute shaders to zero. Some games don't do
# this and rely on undefined behaviour. Enabling may reduce performance.
#
# Supported values: True, False
# d3d11.zeroWorkgroupMemory = False
# Resource size limit for implicit discards, in kilobytes. For small staging
# resources mapped with MAP_WRITE, DXVK will sometimes allocate new backing
# storage in order to avoid GPU synchronization, so setting this too high
# may cause memory issues, setting it to -1 disables the feature.
# d3d11.maxImplicitDiscardSize = 256
# Resource size limit for buffer-mapped dynamic images, in kilobytes.
# A higher threshold may reduce memory usage and PCI-E bandwidth in
# some games, but may also increase GPU synchronizations. Setting it
# to -1 disables the feature.
# d3d11.maxDynamicImageBufferSize = -1
# Allocates dynamic resources with the given set of bind flags in
# cached system memory rather than uncached memory or host-visible
# VRAM, in order to allow fast readback from the CPU. This is only
# useful for buggy applications, and may reduce GPU-bound performance.
#
# Supported values: Any combination of the following:
# - v: Vertex buffers
# - i: Index buffers
# - c: Constant buffers
# - r: Shader resources
# - a: All dynamic resources
# d3d11.cachedDynamicResources = ""
# Force-enables the D3D11 context lock via the ID3D10Multithread
# interface. This may be useful to debug race conditions.
#
# Supported values: True, False
# d3d11.enableContextLock = False
|
29bd88bacd809390fbfa65bedf10f35e
|
{
"intermediate": 0.41626325249671936,
"beginner": 0.32000482082366943,
"expert": 0.2637319266796112
}
|
33,185
|
my PC:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
can you optimize the below config for my pc? It’s for world of warcraft 3.3.5a which is a directx9 game that the 13+ year old engine that the cpu is limited and even the fastest cpus have problems with this game.
also refrain from making any comments. I just want the config
# Sets number of pipeline compiler threads.
#
# If the graphics pipeline library feature is enabled, the given
# number of threads will be used for shader compilation. Some of
# these threads will be reserved for high-priority work.
#
# Supported values:
# - 0 to use all available CPU cores
# - any positive number to enforce the thread count
# dxvk.numCompilerThreads = 0
# Toggles raw SSBO usage.
#
# Uses storage buffers to implement raw and structured buffer
# views. Enabled by default on hardware which has a storage
# buffer offset alignment requirement of 4 Bytes (e.g. AMD).
# Enabling this may improve performance, but is not safe on
# hardware with higher alignment requirements.
#
# Supported values:
# - Auto: Don't change the default
# - True, False: Always enable / disable
# dxvk.useRawSsbo = Auto
# Changes memory chunk size.
#
# Can be used to override the maximum memory chunk size.
#
# Supported values:
# - 0 to use the defaults
# - any positive integer to limit the chunk size, in MiB
# dxvk.maxChunkSize = 0
# Controls graphics pipeline library behaviour
#
# Can be used to change VK_EXT_graphics_pipeline_library usage for
# debugging purpose. Doing so will likely result in increased stutter
# or degraded performance.
#
# Supported values:
# - Auto: Enable if supported, and compile optimized pipelines in the background
# - True: Enable if supported, but do not compile optimized pipelines
# - False: Always disable the feature
# dxvk.enableGraphicsPipelineLibrary = Auto
# Controls pipeline lifetime tracking
#
# If enabled, pipeline libraries will be freed aggressively in order
# save memory and address space. Has no effect if graphics pipeline
# libraries are not supported or disabled.
#
# Supported values:
# - Auto: Enable tracking for 32-bit applications only
# - True: Always enable tracking
# - False: Always disable tracking
# dxvk.trackPipelineLifetime = Auto
# Sets enabled HUD elements
#
# Behaves like the DXVK_HUD environment variable if the
# environment variable is not set, otherwise it will be
# ignored. The syntax is identical.
# dxvk.hud =
# Reported shader model
#
# The shader model to state that we support in the device
# capabilities that the applicatation queries.
#
# Supported values:
# - 1: Shader Model 1
# - 2: Shader Model 2
# - 3: Shader Model 3
# d3d9.shaderModel = 3
# DPI Awareness
#
# Decides whether we should call SetProcessDPIAware on device
# creation. Helps avoid upscaling blur in modern Windows on
# Hi-DPI screens/devices.
#
# Supported values:
# - True, False: Always enable / disable
# d3d9.dpiAware = True
# Strict Constant Copies
#
# Decides whether we should always copy defined constants to
# the UBO when relative addressing is used, or only when the
# relative addressing starts a defined constant.
#
# Supported values:
# - True, False: Always enable / disable
# d3d9.strictConstantCopies = False
# Strict Pow
#
# Decides whether we have an opSelect for handling pow(0,0) = 0
# otherwise it becomes undefined.
#
# Supported values:
# - True, False: Always enable / disable
# d3d9.strictPow = True
# Lenient Clear
#
# Decides whether or not we fastpath clear anyway if we are close enough to
# clearing a full render target.
#
# Supported values:
# - True, False: Always enable / disable
# d3d9.lenientClear = False
# Max available memory
#
# Changes the max initial value used in tracking and GetAvailableTextureMem
# Value in Megabytes
#
# Supported values:
# - Max Available Memory: Any int32_t
# - Memory Tracking Testing: True, False
# d3d9.maxAvailableMemory = 4096
# d3d9.memoryTrackTest = False
# Force enable/disable floating point quirk emulation
#
# Force toggle anything * 0 emulation
# Setting it to True will use a faster but less accurate approach that works for most games.
# Supported values:
# - True: Use a faster but less accurate approach. Good enough for most games
# - False: Disable float emulation completely
# - Strict: Use a slower but more correct approach. Necessary for some games
# - Auto: DXVK will pick automatically
# d3d9.floatEmulation = Auto
# Enable dialog box mode
#
# Changes the default state of dialog box mode.
# *Disables* exclusive fullscreen when enabled.
#
# Supported values:
# - True, False: Always enable / disable
# d3d9.enableDialogMode = False
# Overrides the application's MSAA level on the swapchain
#
# Supported values: -1 (application) and 0 to 16 (user override)
# d3d9.forceSwapchainMSAA = -1
# Long Mad
#
# Should we make our Mads a FFma or do it the long way with an FMul and an FAdd?
# This solves some rendering bugs in games that have z-pass shaders which
# don't match entirely to the regular vertex shader in this way.
#
# Supported values:
# - True/False
# d3d9.longMad = False
# Device Local Constant Buffers
#
# Enables using device local, host accessible memory for constant buffers in D3D9.
# This tends to actually be slower for some reason on AMD,
# and the exact same performance on NVIDIA.
#
# Supported values:
# - True/False
# d3d9.deviceLocalConstantBuffers = False
# Support DF formats
#
# Support the vendor extension DF floating point depth formats
#
# Supported values:
# - True/False
# d3d9.supportDFFormats = True
# Use D32f for D24
#
# Useful for reproducing AMD issues on other hw.
#
# Supported values:
# - True/False
# d3d9.useD32forD24 = False
# Support X4R4G4B4
#
# Support the X4R4G4B4 format.
# The Sims 2 is a very broken game.
#
# Supported values:
# - True/False
# d3d9.supportX4R4G4B4 = True
# Support D32
#
# Support the D32 format.
#
# Supported values:
# - True/False
# d3d9.supportD32 = True
# Disable A8 as a Render Target
#
# Disable support for A8 format render targets
# Once again, The Sims 2 is a very broken game.
#
# Supported values:
# - True/False
# d3d9.disableA8RT = False
# Support for VCache Query
#
# Support for the vcache query
# Not very important as a user config.
# Used internally.
#
# Supported values:
# - True/False
# Defaults to True if vendorId == 0x10de
# d3d9.supportVCache = True
# Force Sampler Type Spec Constants
#
# Useful if games use the wrong image and sampler
# type combo like Halo: CE or Spellforce.
# Can fix rendering in older, broken games in some instances.
#
# Supported values:
# - True/False
# d3d9.forceSamplerTypeSpecConstants = False
# Force Aspect Ratio
#
# Only exposes modes with a given aspect ratio.
# Useful for titles that break if they see ultra-wide.
#
# Supported values:
# - Any ratio, ie. "16:9", "4:3"
# d3d9.forceAspectRatio = ""
# Enumerate by Displays
#
# Whether we should enumerate D3D9 adapters by display (windows behaviour)
# or by physical adapter.
# May be useful in PRIME setups.
#
# Supported values:
# - True/False
# d3d9.enumerateByDisplays = True
# Cached Dynamic Buffers
#
# Allocates dynamic resources in D3DPOOL_DEFAULT in
# cached system memory rather than uncached memory or host-visible
# VRAM, in order to allow fast readback from the CPU. This is only
# useful for buggy applications, and may reduce GPU-bound performance.
#
# Supported values:
# - True/False
# d3d9.cachedDynamicBuffers = False
# Seamless Cubes
#
# Don't use non seamless cube maps even if they are supported.
# Non seamless cubes are correct d3d9 behavior, but can produce worse looking edges.
#
# Supported values:
# - True/False
# d3d9.seamlessCubes = False
# Debug Utils
#
# Enables debug utils as this is off by default, this enables user annotations like BeginEvent()/EndEvent().
# Alternatively could be enabled with DXVK_DEBUG=markers environment variable.
#
# Supported values:
# - True/False
# dxvk.enableDebugUtils = False
# Memory limit for locked D3D9 textures
#
# How much virtual memory will be used for textures (in MB).
# 0 to disable the limit.
# THIS DOES NOT IMPACT ACTUAL MEMORY CONSUMPTION OR TEXTURE QUALITY.
# DO NOT CHANGE THIS UNLESS YOU HAVE A VERY GOOD REASON.
# d3d9.textureMemory = 100
# Always enumerate all monitors on each dxgi output
#
# Used to avoid performance degradation in some games
# (will be deprecated once QueryDisplayConfig optimization
# is in Proton Wine).
#
# Supported values:
# - True/False
# dxgi.useMonitorFallback = False
|
abef78734e8b999d77f5004403a66fe1
|
{
"intermediate": 0.3243868947029114,
"beginner": 0.456564337015152,
"expert": 0.21904882788658142
}
|
33,186
|
I have 1928 cell segmantation dataset, 1928 rows and 27 features (columns). can you write python code to visualize the data with kmeans and PCA?
|
81f9b067688d0b255e8cbbfebd677fa8
|
{
"intermediate": 0.6027586460113525,
"beginner": 0.08378919959068298,
"expert": 0.3134521543979645
}
|
33,187
|
Can you optimize this for my pc:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
the game is wow 3.3.5a which is 13+ year old engine that is very cpu intensive only on like 4 cores. Here's a dxvk i want you to change based on my specs:
Please do not make any comments. All i want is the actual config not any of the comments. Please remove all the below comments as well.
#UPDATED: 2023-Abril-29 Experimental Smoothy v3.0 for the dxvk Version 1.2-3
#DXVK configuration for GPUs (NVIDIA & AMD). For testing with Intel ARC, use this configuration and also without it in WoW 3.3.5a.
#Author: Milor123 - Junklont
#IMPORTANT: Shadows are best set to Low, and Distance set to High or less. Do NOT use MAX and disable V-SYNC.
#IMPORTANT NOTE: Please do not test performance in Dalaran as it is poorly optimized, this map is a shi*****t
d3d9.maxFrameRate = 200 # Set manually for limit the Max FPS
dxvk.hud = fps # REMOVE THIS LINE FOR HIDE FPS HUD or write # for comment
d3d9.maxFrameLatency = 4
d3d9.numBackBuffers = 0 # // I GET MORE FPS IN 0 a mayor numero mayor calidad menos rendimiento
d3d9.presentInterval = 0 # Disable Vsync in 0
d3d9.tearFree = Auto # Vsync replace fuction // I GET MORE FPS IN False
d3d9.maxAvailableMemory = 1000 # CHANGE IT FOR YOU RAM Size in MB
d3d9.evictManagedOnUnlock = True # forzar la liberación de la memoria utilizada por los recursos de la GPU después de que se desbloqueen en el juego
d3d9.allowDiscard = True # permitir que DXVK deseche los recursos de la GPU que ya no son necesarios
dxvk.enableAsync = True # It option only work in Async Version
dxvk.numCompilerThreads = 0 # CHANGE IT by your threads of CPU <----------------------
dxvk.numAsyncThreads = 0 # 0 is Automatic || It option only work in Async Version
#d3d9.customDeviceId = 0091
#d3d9.customVendorId = 10de
d3d9.samplerAnisotropy = 0
d3d9.invariantPosition = False # New bugs xD
d3d9.memoryTrackTest = True # Get memory values
d3d9.noExplicitFrontBuffer = True # deshabilitar el búfer frontal
# New patches
d3d9.strictConstantCopies = False # Only for GPU users with good GPU RTX >= 1060 or 1070 maybe if you use APU set in False
d3d9.lenientClear = True # Permite una limpieza menos riguroza = More performance
dxvk.maxChunkSize = 0 # 128 or 256 MiB for slow APU like Intel(R) HD Graphics 620
d3d9.longMad = False # Change to True for try get more perfomance only enable if try use z-pass
##############################
d3d9.floatEmulation = Auto # New Thing
# Supported values:
# - True: Use a faster but less accurate approach. Good enough for most games
# - False: Disable float emulation completely
# - Strict: Use a slower but more correct approach. Necessary for some games
# - Auto: DXVK will pick automatically
##############################
d3d9.forceSwapchainMSAA = 0
d3d9.supportVCache = False #Its only for Nvidia GPU (vcache query)
d3d9.forceSamplerTypeSpecConstants = False
dxvk.useRawSsbo = False # PLEASE NOT ENABLE IT, CAUSE LAGGY SHUTTERS
######## OPTIONAL SETTINGS, remove # for test
# For idiots games, it normaly by me should be true all
d3d9.supportD32 = False
d3d9.useD32forD24 = False
d3d9.supportX4R4G4B4 = False # CAUSE LAG AND LESS FPS GAIN. please dont ENABLE IT in Wow3.3.5a
d3d9.disableA8RT = True # improvement the login fast charging and other things very GOOD in TRUE
#########
#Explains:
# Some games think we are on Intel given a lack of NVAPI or
# AGS/atiadlxx support. Report our device memory as shared memory,
# and some small amount for a "carveout".
# Supported values: True, False
# dxgi.emulateUMA = False # IT says the game that we are using iGPU not NVAPI
|
7db65177042cd40c76bb7c1b9e3ac39c
|
{
"intermediate": 0.3729378879070282,
"beginner": 0.32661041617393494,
"expert": 0.30045169591903687
}
|
33,188
|
help me improve this so it detects the template better and even if the image is rotated:
import cv2
import numpy as np
# Load the reference image and the main image
ref_image = cv2.imread("shot2Target0.png", 0)
main_image = cv2.imread("shot(3).jpg", 0)
# Find the reference image in the main image
res = cv2.matchTemplate(main_image, ref_image, cv2.TM_CCOEFF_NORMED)
# Find the location of the match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# Calculate the angle of rotation
angle = np.degrees(np.arctan2(max_loc[1] - ref_image.shape[0] / 2, max_loc[0] - ref_image.shape[1] / 2))
# Define the rotation matrix
rotation_matrix = cv2.getRotationMatrix2D((ref_image.shape[1] / 2, ref_image.shape[0] / 2), angle, 1)
# Rotate the main image
rotated_image = cv2.warpAffine(main_image, rotation_matrix, (ref_image.shape[1], ref_image.shape[0]))
# Crop the main image
top_left = max_loc
bottom_right = (top_left[0] + ref_image.shape[1], top_left[1] + ref_image.shape[0])
cropped_image = main_image[top_left[1] : bottom_right[1], top_left[0] : bottom_right[0]]
# Display the cropped image
cv2.imshow("Cropped Image", cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
949d2951201b6e852493c13cb6c2042a
|
{
"intermediate": 0.3688366413116455,
"beginner": 0.11456985026597977,
"expert": 0.5165935754776001
}
|
33,189
|
#%% md
|
71996a4fc2bced31df66927f57eba30f
|
{
"intermediate": 0.31816965341567993,
"beginner": 0.38016578555107117,
"expert": 0.3016645908355713
}
|
33,190
|
Ensure this golang script is correct and is correct up-to-date with latest dependencies: package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/chromedp/chromedp"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: go run main.go <url>")
return
}
url := os.Args[1]
if err := playVideo(url); err != nil {
log.Fatal("Error:", err)
}
}
func playVideo(url string) error {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
options := []chromedp.ExecAllocatorOption{
chromedp.ExecPath("./chrome-linux/chrome"),
chromedp.Headless,
chromedp.NoSandbox,
chromedp.DisableGPU,
chromedp.IgnoreCertificateErrors,
}
ctx, cancel = chromedp.NewExecAllocator(ctx, options...)
defer cancel()
ctx, cancel = chromedp.NewContext(ctx)
defer cancel()
var firstResult string
if err := chromedp.Run(ctx,
chromedp.Navigate(url),
chromedp.WaitVisible(`b.api-key-text`),
chromedp.Text(`b.api-key-text`, &firstResult),
); err != nil {
return fmt.Errorf("error getting first result: %v", err)
}
currentURL := ""
if err := chromedp.Run(ctx, chromedp.Location(¤tURL)); err != nil {
return fmt.Errorf("error getting current URL: %v", err)
}
newURL := strings.Replace(currentURL, "UI/Dashboard", "api/v2.0/indexers?configured=true", 1)
var responseBody []byte
if err := chromedp.Run(ctx,
chromedp.Navigate(newURL),
chromedp.WaitVisible(`body`),
chromedp.InnerHTML(`body`, &responseBody),
); err != nil {
return fmt.Errorf("error getting response body: %v", err)
}
var response []map[string]interface{}
if err := json.Unmarshal(responseBody, &response); err != nil {
return fmt.Errorf("error unmarshalling JSON response: %v", err)
}
privateItems := make([]map[string]interface{}, 0)
for _, item := range response {
itemType := strings.ToLower(fmt.Sprintf("%v", item["type"]))
configured := strings.ToLower(fmt.Sprintf("%v", item["configured"]))
if strings.Contains(itemType, "private") && configured == "true" {
privateItems = append(privateItems, item)
}
}
if len(privateItems) == 0 {
return nil
}
fmt.Printf("\nTorznab key: %s\n", firstResult)
for _, item := range privateItems {
id := fmt.Sprintf("%v", item["id"])
configURL := strings.Replace(currentURL, "UI/Dashboard", fmt.Sprintf("api/v2.0/indexers/%s/config", id), 1)
configResponse, err := getConfigResponseWithCookies(configURL, ctx)
if err != nil {
fmt.Printf("##%s | %s | %v\n", id, configURL, err)
continue
}
filteredElements := make([]string, 0)
for _, element := range configResponse {
elementType := fmt.Sprintf("%v", element["type"])
elementValue := fmt.Sprintf("%v", element["value"])
if elementType == "inputstring" && elementValue != "true" && elementValue != "false" {
filteredElements = append(filteredElements, elementValue)
}
}
groupedValues := strings.Join(filteredElements, " | ")
prefixedGroupedValues := id + " | " + groupedValues
fmt.Println(prefixedGroupedValues)
}
return nil
}
func getConfigResponseWithCookies(url string, ctx context.Context) ([]map[string]interface{}, error) {
cookies, err := chromedp.Cookies(ctx)
if err != nil {
return nil, fmt.Errorf("error getting cookies: %v", err)
}
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
for _, cookie := range cookies {
req.AddCookie(&http.Cookie{
Name: cookie.Name,
Value: cookie.Value,
})
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req = req.WithContext(ctx)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
var response []map[string]interface{}
if err := json.Unmarshal(body, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling JSON response: %v", err)
}
return response, nil
}
|
8a14f49e2a2a6072fb69d40ca17036b7
|
{
"intermediate": 0.3001212477684021,
"beginner": 0.4323839545249939,
"expert": 0.2674947679042816
}
|
33,191
|
Does Gödel Incompleteness give us the possibility that there exist yet unknown AI algorithms that are more state of the art compared to any existing AI algorithms. Yet those new AI algorithms can be mathematically unprovable although much more powerful than any existing one?
|
e53fab473a90235133a7a74324cb070b
|
{
"intermediate": 0.14185476303100586,
"beginner": 0.09967908263206482,
"expert": 0.7584661841392517
}
|
33,192
|
Can you optimize this for my pc:
CPU: Ryzen 9 7950x 16 core 32 thread
GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers)
Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V
Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB
LAN: realtek Gaming 2.5GbE Family Controller
Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers)
USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz
Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR
Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing.
Software:
Windows 11 23H2
Process Lasso: I disable the first 2 cores, 4 threads of my process affinity for games.
MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600
Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50%
AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20
the game is wow 3.3.5a which is 13+ year old engine that is very cpu intensive only on like 4 cores. Here’s a dxvk i want you to change based on my hardware. Not the hardware that this is based on. But take into consideration the comments of what i'm sending you.
Please do not make any comments. All i want is the actual config not any of the comments. Please remove all the below comments as well.
#UPDATED: 2023-Abril-29 Experimental Smoothy v3.0 for the dxvk Version 1.2-3
#DXVK configuration for GPUs (NVIDIA & AMD). For testing with Intel ARC, use this configuration and also without it in WoW 3.3.5a.
#Author: Milor123 - Junklont
#IMPORTANT: Shadows are best set to Low, and Distance set to High or less. Do NOT use MAX and disable V-SYNC.
#IMPORTANT NOTE: Please do not test performance in Dalaran as it is poorly optimized, this map is a shi*****t
d3d9.maxFrameRate = 200 # Set manually for limit the Max FPS
dxvk.hud = fps # REMOVE THIS LINE FOR HIDE FPS HUD or write # for comment
d3d9.maxFrameLatency = 4
d3d9.numBackBuffers = 0 # // I GET MORE FPS IN 0 a mayor numero mayor calidad menos rendimiento
d3d9.presentInterval = 0 # Disable Vsync in 0
d3d9.tearFree = Auto # Vsync replace fuction // I GET MORE FPS IN False
d3d9.maxAvailableMemory = 1000 # CHANGE IT FOR YOU RAM Size in MB
d3d9.evictManagedOnUnlock = True # forzar la liberación de la memoria utilizada por los recursos de la GPU después de que se desbloqueen en el juego
d3d9.allowDiscard = True # permitir que DXVK deseche los recursos de la GPU que ya no son necesarios
dxvk.enableAsync = True # It option only work in Async Version
dxvk.numCompilerThreads = 0 # CHANGE IT by your threads of CPU <----------------------
dxvk.numAsyncThreads = 0 # 0 is Automatic || It option only work in Async Version
#d3d9.customDeviceId = 0091
#d3d9.customVendorId = 10de
d3d9.samplerAnisotropy = 0
d3d9.invariantPosition = False # New bugs xD
d3d9.memoryTrackTest = True # Get memory values
d3d9.noExplicitFrontBuffer = True # deshabilitar el búfer frontal
# New patches
d3d9.strictConstantCopies = False # Only for GPU users with good GPU RTX >= 1060 or 1070 maybe if you use APU set in False
d3d9.lenientClear = True # Permite una limpieza menos riguroza = More performance
dxvk.maxChunkSize = 0 # 128 or 256 MiB for slow APU like Intel® HD Graphics 620
d3d9.longMad = False # Change to True for try get more perfomance only enable if try use z-pass
##############################
d3d9.floatEmulation = Auto # New Thing
# Supported values:
# - True: Use a faster but less accurate approach. Good enough for most games
# - False: Disable float emulation completely
# - Strict: Use a slower but more correct approach. Necessary for some games
# - Auto: DXVK will pick automatically
##############################
d3d9.forceSwapchainMSAA = 0
d3d9.supportVCache = False #Its only for Nvidia GPU (vcache query)
d3d9.forceSamplerTypeSpecConstants = False
dxvk.useRawSsbo = False # PLEASE NOT ENABLE IT, CAUSE LAGGY SHUTTERS
######## OPTIONAL SETTINGS, remove # for test
# For idiots games, it normaly by me should be true all
d3d9.supportD32 = False
d3d9.useD32forD24 = False
d3d9.supportX4R4G4B4 = False # CAUSE LAG AND LESS FPS GAIN. please dont ENABLE IT in Wow3.3.5a
d3d9.disableA8RT = True # improvement the login fast charging and other things very GOOD in TRUE
#########
#Explains:
# Some games think we are on Intel given a lack of NVAPI or
# AGS/atiadlxx support. Report our device memory as shared memory,
# and some small amount for a “carveout”.
# Supported values: True, False
# dxgi.emulateUMA = False # IT says the game that we are using iGPU not NVAPI
|
8443be52787678ff6beb8e719359cc48
|
{
"intermediate": 0.39775583148002625,
"beginner": 0.323393851518631,
"expert": 0.27885034680366516
}
|
33,193
|
Есть проект на vue с typescript. В нем два компонента ArrowsPage:
<template>
<PageContainer :breadcrumbs="['Реестр', 'Стрелки']">
<template #header>
<el-row :gutter="20">
<el-col :span="6">
<ButtonWithTooltip
tooltip-content="Добавить стрелку"
button-style="primary"
icon-image="plus"
:scope-row="dialog.dialogItem"
@click="handleAdd"
/>
</el-col>
<el-col :span="6" :offset="12" class="right-col">
<ButtonWithTooltip
tooltip-content="Загрузить"
icon-image="download"
/>
<ButtonWithTooltip tooltip-content="Выгрузить" icon-image="upload" />
</el-col>
</el-row>
</template>
<el-table :data="tableData" border>
<el-table-column prop="id" label="Идентификатор" />
<el-table-column prop="number" label="Номер" />
<el-table-column prop="arrows" label="Стрелочный перевод" width="200" />
<el-table-column prop="bs" label="Блок-участок" width="260" />
<el-table-column prop="plusConnect" label="Связи '+'" />
<el-table-column prop="minusConnect" label="Связи '-'" />
<el-table-column prop="visible" label="Отрисовано" />
<el-table-column
prop=""
label="Редактировать / Удалить"
align="right"
width="220"
>
<template #default="scope">
<ButtonWithTooltip
tooltip-content="Редактировать стрелку"
icon-image="edit"
button-text
icon-color="#409eff"
@click="handleEdit(scope.row)"
/>
<ButtonWithTooltip
tooltip-content="Удалить стрелку"
icon-image="delete"
button-text
icon-color="#f56c6c"
@click="handleRemove(scope.$index)"
/>
</template>
</el-table-column>
</el-table>
<ArrowsActionDialog
v-if="dialog.visible"
:arrow-data="dialog.dialogItem"
:title="dialog.title"
:visible="dialog.visible"
@handle-close="(visible: boolean) => (dialog.visible = visible)"
@save-arrow="saveArrowItem"
></ArrowsActionDialog>
</PageContainer>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import ArrowsActionDialog from "./ArrowsActionDialog.vue";
import type { arrowItem } from "./ArrowsPage.types";
import { PageContainer, ButtonWithTooltip } from "@shared";
export default defineComponent({
name: "ArrowsPage",
components: {
ArrowsActionDialog,
PageContainer,
ButtonWithTooltip,
},
data() {
return {
dialog: {
visible: false,
title: "",
dialogItem: Object as arrowItem | {} | null,
},
tableData: [
{
id: 111,
number: 230,
arrows: ["sdf", "sdfa"],
bs: "234",
plusConnect: "229",
minusConnect: "231",
visible: "230",
},
{
id: 2222,
number: 233,
arrows: ["sad", "ssaa"],
bs: "522",
plusConnect: "232",
minusConnect: "234",
visible: "223",
},
{
id: 3333,
number: 233,
arrows: ["sad", "ssaa"],
bs: "522",
plusConnect: "232",
minusConnect: "234",
visible: "223",
},
{
id: 444,
number: 233,
arrows: ["sad", "ssaa"],
bs: "522",
plusConnect: "232",
minusConnect: "234",
visible: "223",
},
],
};
},
methods: {
handleEdit(item: any) {
// заголовок лучше задать в компоненте
this.dialog.title = "Редактировать стрелку";
this.dialog.visible = true;
this.dialog.dialogItem = item;
},
handleRemove(index: number) {
this.tableData.splice(index, 1);
},
handleAdd() {
// заголовок лучше задать в компоненте
this.dialog.title = "Добавить стрелку";
this.dialog.dialogItem = null;
this.dialog.visible = true;
},
saveArrowItem(arrowItem: any) {
if (this.dialog.dialogItem) {
// ??
const index = this.tableData.findIndex(
(item) => item.id === arrowItem.id,
);
if (index !== -1) {
this.tableData[index] = { ...this.tableData[index], ...arrowItem };
}
this.dialog.dialogItem = {};
} else if (arrowItem.id) {
this.tableData.push(arrowItem);
}
this.dialog.visible = false;
},
},
});
</script>
И компонент ArrowsActionDialog:
<template>
<ActionDialog
title="title"
:visible="dialog.visible"
@handle-close="(visible: boolean) => (dialog.visible = visible)"
@save="saveArrow"
>
<el-form :model="dialog.form" label-width="160px" label-position="top">
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="ID стрелки">
<el-input v-model="dialog.form.id" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="Номер стрелки">
<el-input v-model="dialog.form.number" />
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="Связи '+'">
<el-input v-model="dialog.form.plusConnect" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="Связи '-'">
<el-input v-model="dialog.form.minusConnect" />
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="Блок-участок:">
<el-input v-model="dialog.form.bs" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="Стрелочный перевод:">
<el-input v-model="dialog.form.arrows" />
</el-form-item>
</el-col>
</el-row>
</el-form>
</ActionDialog>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import type { arrowItem } from "./ArrowsPage.types";
import { ActionDialog } from "@shared";
export default defineComponent({
name: "ArrowsActionDialog",
components: {
ActionDialog,
},
props: {
// приветсти к типу
arrowData: {
type: Object,
default: null,
},
},
emits: ["saveArrow"],
data() {
return {
dialog: {
form: {
id: 1,
number: "",
arrows: "",
bs: "",
plusConnect: "",
minusConnect: "",
visible: "",
},
visible: false,
},
};
},
mounted() {
this.dialog.form = { ...this.arrowData };
},
methods: {
saveArrow() {
const { id, number, arrows, bs, plusConnect, minusConnect, visible } =
this.dialog.form;
// вынести в тип
const newItem: {
id: number;
number: string;
arrows: string;
bs: string;
plusConnect: string;
minusConnect: string;
visible: string;
} = {
id,
number,
arrows,
bs,
plusConnect,
minusConnect,
visible,
};
this.$emit("saveArrow", newItem);
},
},
});
</script>
export type arrowItem = {
id: string;
number: string;
arrows: string;
bs: string;
plusConnect: string;
minusConnect: string;
visible: string;
};
Как правильно написать типы в arrowsActionDialog чтобы не было ошибок линтера? Первая ошибка в mounted подсвечивается this.dialog.form, описание ошибки Type '{ [x: string]: any; }' is missing the following properties from type '{ id: any; number: string; arrows: string; bs: string; plusConnect: string; minusConnect: string; visible: string; }': id, number, arrows, bs, and 3 more.ts(2740). Вторая ошибка в ArrowsPage в template подсвечивается передачу пропса :arrow-data, описание ошибки Type '{} | { id: string; number: string; arrows: string; bs: string; plusConnect: string; minusConnect: string; visible: string; } | null' is not assignable to type 'Record<string, any> | undefined'.
Type 'null' is not assignable to type 'Record<string, any> | undefined'.ts(2322)
ArrowsActionDialog.vue(61, 5): The expected type comes from property 'arrowData' which is declared here on type 'ComponentProps<DefineComponent<{ arrowData: { type: ObjectConstructor; default: null; }; }, unknown, { dialog: { form: { id: number; number: string; arrows: string; bs: string; plusConnect: string; minusConnect: string; visible: string; }; visible: boolean; }; }, ... 9 more ..., {}>>'.
Третья ошибка я думаю, что неправильно затипизировал arrowData в ArrowsActionDialog
|
5e1bec7017698619caf63e76d2b606ac
|
{
"intermediate": 0.24631166458129883,
"beginner": 0.6859704256057739,
"expert": 0.06771790236234665
}
|
33,194
|
help me improve this so it detects the template better and even if the image is rotated, needs to be light driven and fast:
import cv2
import numpy as np
# Load the reference image and the main image
ref_image = cv2.imread(“shot2Target0.png”, 0)
main_image = cv2.imread(“shot(3).jpg”, 0)
# Find the reference image in the main image
res = cv2.matchTemplate(main_image, ref_image, cv2.TM_CCOEFF_NORMED)
# Find the location of the match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# Calculate the angle of rotation
angle = np.degrees(np.arctan2(max_loc[1] - ref_image.shape[0] / 2, max_loc[0] - ref_image.shape[1] / 2))
# Define the rotation matrix
rotation_matrix = cv2.getRotationMatrix2D((ref_image.shape[1] / 2, ref_image.shape[0] / 2), angle, 1)
# Rotate the main image
rotated_image = cv2.warpAffine(main_image, rotation_matrix, (ref_image.shape[1], ref_image.shape[0]))
# Crop the main image
top_left = max_loc
bottom_right = (top_left[0] + ref_image.shape[1], top_left[1] + ref_image.shape[0])
cropped_image = main_image[top_left[1] : bottom_right[1], top_left[0] : bottom_right[0]]
# Display the cropped image
cv2.imshow(“Cropped Image”, cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
8f94bed330d37efe6b216d04503a01ee
|
{
"intermediate": 0.36630237102508545,
"beginner": 0.11755189299583435,
"expert": 0.5161457061767578
}
|
33,195
|
I have 1928 cell segmantation dataset, 1928 rows and 27 features (columns). can you write python code to visualize the data with scale , kmeans and PCA?
|
21675493d21a19117a88c0b0b3c56485
|
{
"intermediate": 0.6440439820289612,
"beginner": 0.08340442180633545,
"expert": 0.2725515365600586
}
|
33,196
|
in antd and typescript when you add a Select component there is gap between the text and the arrow (ant-select-arrow), how can I reduce that gap between the text and the arrow
|
d2b0d90bd4b3e5f7b2f37f6d0621be6a
|
{
"intermediate": 0.5993871688842773,
"beginner": 0.1308644562959671,
"expert": 0.26974841952323914
}
|
33,197
|
I ran the following code for a binary classification task w/ an SVM in both R (first sample) and Python (second example).
Given randomly generated data (X) and response (Y), this code performs leave group out cross validation 1000 times. Each entry of Y is therefore the mean of the prediction across CV iterations.
Computing area under the curve should give ~0.5, since X and Y are completely random. However, this is not what we see. Area under the curve is frequently significantly higher than 0.5. The number of rows of X is very small, which can obviously cause problems.
Any idea what could be happening here? I know that I can either increase the number of rows of X or decrease the number of columns to mediate the problem, but I am looking for other issues.
|
ce399bf20d8df8d50f816bd84052194e
|
{
"intermediate": 0.37143105268478394,
"beginner": 0.12187390774488449,
"expert": 0.5066950917243958
}
|
33,198
|
import random
import numpy as np
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.optimizers import Adam
from collections import deque
numbers_range = (1, 10)
large_numbers = [25, 50, 75, 100]
input_size = 7
output_size = 72 # Changed from 36 to 72
memory_buffer = deque(maxlen=1000) # Adjust the buffer size as needed
def generate_game():
target = random.randint(100, 999)
numbers = random.choices(range(1, 10), k=5) + random.choices(large_numbers, k=1) # Use random.choices to select the numbers
return target, numbers
def generate_training_data(target, numbers):
input_data = np.append(target, numbers)
output_data = np.zeros(output_size)
for i in range(6):
for j in range(6):
if i != j:
# Generate output data for all 72 actions, not just 36
output_data[i * 12 + j] = 1 # Addition
output_data[i * 12 + j + 6] = 1 # Subtraction
output_data[i * 12 + j + 36] = 1 # Multiplication
if numbers[j] != 0: # Avoid division by zero
output_data[i * 12 + j + 42] = 1 # Division
return np.array([input_data]), output_data
def store_experience(target, numbers, output_data):
input_data = np.append(target, numbers)
memory_buffer.append((input_data, output_data))
def sample_from_memory(batch_size=32):
samples = random.sample(memory_buffer, min(batch_size, len(memory_buffer)))
x, y = zip(*samples)
return np.array(x), np.array(y)
def get_solution(model, target, numbers):
pred = model.predict(np.array([np.append(target, numbers)]))
indices = np.argsort(pred.flatten())[-2:] # Get the indices of the two highest predictions
i, j = indices // 12, indices % 12 # Decode the indices of the actions from the output layer
# Ensure each number is used only once in the solution
i = list(set(i) & set(range(6))) # Limit to the range of original numbers
j = list(set(j) & set(range(6))) # Limit to the range of original numbers
operators = ['+', '+'] # Initialize with '+' for both operators
for idx, val in enumerate(i):
if val >= 5:
operators[idx] = str(large_numbers[val - 5])
for idx, val in enumerate(j):
if val >= 5:
operators[idx] = str(large_numbers[val - 5])
# Take into account the new operators
if j[0] >= 6:
operators[0] = '-' if j[0] < 12 else '*' if j[0] < 18 else '/'
if j[1] >= 6:
operators[1] = '-' if j[1] < 12 else '*' if j[1] < 18 else '/'
return i[0], operators[0], j[0] % 6, operators[1]
def calculate_reward(target, predicted):
# Define a sliding scale for rewards based on the proximity to the target
absolute_difference = abs(predicted - target)
if absolute_difference == 0:
return 1.0 # Full reward for an exact match
elif absolute_difference <= 0.01 * target: # Within 1% of the target
return 0.8
elif absolute_difference <= 0.02 * target: # Within 2% of the target
return 0.6
# ... Add more conditions as needed for different levels of proximity
else:
return 0.0 # No reward if not within the defined thresholds
def play_and_train(model):
target, numbers = generate_game()
print("Target:", target)
print("Numbers:", numbers)
# Store current game experience in memory
x, y = generate_training_data(target, numbers)
store_experience(target, numbers, y)
# Sample from memory for training
x_memory, y_memory = sample_from_memory(batch_size=32)
# Input Data Normalization
scaler = MinMaxScaler()
x_scaled = scaler.fit_transform(x_memory)
# Train the model on both current and past experiences
model.fit(x_scaled, y_memory, epochs=5, batch_size=32, verbose=0)
# Predict the result
i, operator_i, j, operator_j = get_solution(model, target, numbers)
# Handle the cases where the predicted solution involves multiplication or division
if operator_i == '*':
result_i = numbers[i] * numbers[j % 6]
elif operator_i == '/':
result_i = numbers[i] / numbers[j % 6]
else:
result_i = numbers[i] + numbers[j % 6] if operator_i == '+' else numbers[i] - numbers[j % 6]
print(f"Predicted Solution: ({numbers[i]} {operator_i} {numbers[j % 6]}) = {result_i}")
# Calculate the reward based on how close the prediction is to the target
reward = calculate_reward(target, result_i)
print("Reward:", reward)
return reward
# Model Architecture
model = keras.Sequential()
model.add(keras.layers.Dense(64, input_dim=input_size, activation='relu'))
model.add(keras.layers.Dense(32, activation='relu'))
model.add(keras.layers.Dense(output_size, activation='sigmoid'))
# Model Compilation
model.compile(loss='binary_crossentropy', optimizer=Adam(learning_rate=0.001), metrics=['accuracy'])
solutions_count = 0
while solutions_count < 100:
reward = play_and_train(model)
if reward == 1.0:
solutions_count += 1
|
011db83d5a6c6b05b705a4d857af3e4a
|
{
"intermediate": 0.37950700521469116,
"beginner": 0.32284146547317505,
"expert": 0.2976515293121338
}
|
33,199
|
write a python script that's able to find a template picture in another picture even if it's a little bit different angled
|
69d8edcc0193f41fbe9d9332e1898fa8
|
{
"intermediate": 0.2979370951652527,
"beginner": 0.11588840931653976,
"expert": 0.5861745476722717
}
|
33,200
|
What dxvk setting could cause a very small cursor size
|
76f01df82c71b57b4fc0d575a907dba2
|
{
"intermediate": 0.25937318801879883,
"beginner": 0.18572092056274414,
"expert": 0.5549059510231018
}
|
33,201
|
I ran the following code for a binary classification task w/ an SVM in both R (first sample) and Python (second example).
Given randomly generated data (X) and response (Y), this code performs leave group out cross validation 1000 times. Each entry of Y is therefore the mean of the prediction across CV iterations.
Computing area under the curve should give ~0.5, since X and Y are completely random. However, this is not what we see. Area under the curve is frequently significantly higher than 0.5. The number of rows of X is very small, which can obviously cause problems.
Any idea what could be happening here? I know that I can either increase the number of rows of X or decrease the number of columns to mediate the problem, but I am looking for other issues.
Y=as.factor(rep(c(1,2), times=14))
X=matrix(runif(length(Y)*100), nrow=length(Y))
library(e1071)
library(pROC)
colnames(X)=1:ncol(X)
iter=1000
ansMat=matrix(NA,length(Y),iter)
for(i in seq(iter)){
#get train
train=sample(seq(length(Y)),0.5*length(Y))
if(min(table(Y[train]))==0)
next
#test from train
test=seq(length(Y))[-train]
#train model
XX=X[train,]
YY=Y[train]
mod=svm(XX,YY,probability=FALSE)
XXX=X[test,]
predVec=predict(mod,XXX)
RFans=attr(predVec,'decision.values')
ansMat[test,i]=as.numeric(predVec)
}
ans=rowMeans(ansMat,na.rm=TRUE)
r=roc(Y,ans)$auc
print(r)
|
c51f38abb74ad69f47839c8a53d71585
|
{
"intermediate": 0.422402024269104,
"beginner": 0.21530692279338837,
"expert": 0.3622910976409912
}
|
33,202
|
Batch Есть папка Karne мне нужно скопировать ее в C:\users\root\AppData\LocalLow
|
596f76dd9f762ccc092a2e245372dc82
|
{
"intermediate": 0.32536980509757996,
"beginner": 0.33233538269996643,
"expert": 0.3422948122024536
}
|
33,203
|
in c++ sdl2, how do i use flags with | to fit multiple flags into one variable?
|
04ce0f1a2374342cd2267826a1b37452
|
{
"intermediate": 0.4620821475982666,
"beginner": 0.3643419146537781,
"expert": 0.17357586324214935
}
|
33,204
|
import random
import numpy as np
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.optimizers import Adam
from collections import deque
numbers_range = (1, 10)
large_numbers = [25, 50, 75, 100]
input_size = 7
output_size = 4 # We have four possible operations: addition(+), subtraction(-), multiplication(*), and division(/)
memory_buffer = deque(maxlen=1000) # Experience replay buffer
# Define possible operations
operations = [np.add, np.subtract, np.multiply, np.divide]
def generate_game():
target = random.randint(100, 999)
numbers = random.sample(range(*numbers_range), k=5) + random.choices(large_numbers, k=2)
return target, numbers
def store_experience(state, action, reward, next_state, done):
memory_buffer.append((state, action, reward, next_state, done))
def sample_from_memory(batch_size=32):
samples = random.sample(memory_buffer, min(batch_size, len(memory_buffer)))
states, actions, rewards, next_states, dones = zip(*samples)
return np.array(states), actions, rewards, np.array(next_states), dones
# Create the DQN model
model = keras.Sequential()
model.add(keras.layers.Dense(64, input_dim=input_size, activation='relu'))
model.add(keras.layers.Dense(32, activation='relu'))
model.add(keras.layers.Dense(output_size, activation='linear'))
model.compile(loss='mse', optimizer = Adam(learning_rate=0.001))
# Normalize input data by fitting a scaler only on the possible range of values
scaler = MinMaxScaler()
scaler.fit(np.array([[0] + [1]*6, [999] + large_numbers*2])) # Min and max states
def play_and_learn(iters=1000, batch_size=32):
for _ in range(iters):
# Initialize game
target, numbers = generate_game()
done = False
current_sum = 0
while not done:
# Prepare the state
state = np.array([[target] + numbers + [current_sum]])
# Predict the best operation
state_scaled = scaler.transform(state)
action_values = model.predict(state_scaled)
action = np.argmax(action_values[0])
# Choose two numbers to perform the operation on
num1, num2 = random.sample(numbers, 2)
if action == 3 and num2 == 0: # Avoid division by zero
continue
# Apply the chosen operation
next_sum = operations[action](num1, num2)
next_state = np.array([[target] + numbers + [next_sum]])
reward = 1.0 if abs(next_sum - target) < abs(current_sum - target) else 0.0
# Check if the game is done
if len(memory_buffer) >= memory_buffer.maxlen:
done = True
# Store the experience
store_experience(state_scaled[0], action, reward, scaler.transform(next_state)[0], done)
# Sample a minibatch from the memory
if len(memory_buffer) >= batch_size:
minibatch_states, minibatch_actions, minibatch_rewards, minibatch_next_states, minibatch_dones = sample_from_memory(
batch_size)
# Compute Q values for minibatch
Q_values_next = model.predict_on_batch(minibatch_next_states)
Q_targets = minibatch_rewards + (np.amax(Q_values_next, axis=1) * (1 - minibatch_dones))
# Update the Q values for the actions that were taken
Q_values = model.predict_on_batch(minibatch_states)
for i, action in enumerate(minibatch_actions):
Q_values[i, action] = Q_targets[i]
# Train the model on the minibatch
model.train_on_batch(minibatch_states, Q_values)
print("Training Completed")
play_and_learn()
|
961da091eeee5e205a30391d7287a099
|
{
"intermediate": 0.41822510957717896,
"beginner": 0.24686940014362335,
"expert": 0.3349054753780365
}
|
33,205
|
import random
import numpy as np
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.optimizers import Adam
from collections import deque
# … (Your preceding code, including the imports, remains unchanged.)
# Corrected normalization for target and numbers separately
numbers_scale = (1, 100)
scaler = MinMaxScaler()
scaler.fit(np.array([[numbers_scale[0]] * 7, [numbers_scale[1]] * 7])) # Adjusted to normalize only numbers
# … (The rest of your unchanged code until play_and_learn function.)
def play_and_learn(iters=1000, batch_size=32):
for _ in range(iters):
# Initialize game
target, numbers = generate_game()
done = False
steps = 0
max_steps = 5 # You should define some stopping criterion, e.g., max number of operations
while not done:
# Prepare the state
state = np.array([[target] + numbers])
state_scaled = scaler.transform(state)
# Predict the best operation
action_values = model.predict(state_scaled)
action = np.argmax(action_values[0])
# Choose two numbers to perform the operation on
num1, num2 = random.sample(numbers, 2)
if action == 3 and num2 == 0: # Avoid division by zero
continue
# Apply the chosen operation
result = operations[action](num1, num2)
if action == 3 and not np.isfinite(result): # Avoiding infinite results due to division
continue
reward = -abs(target - result) # Reward is better as negative distance from the target
# Check if game is done
steps += 1
if steps >= max_steps or result == target:
done = True
# Update numbers to reflect the operation
numbers.remove(num1)
numbers.remove(num2)
numbers.append(result) # Append the result back to the list of numbers
# Prepare next_state
next_state = np.array([[target] + numbers])
next_state_scaled = scaler.transform(next_state)
# Store the experience
store_experience(state_scaled[0], action, reward, next_state_scaled[0], done)
# Sample a minibatch from the memory
if len(memory_buffer) >= batch_size:
minibatch_states, minibatch_actions, minibatch_rewards, minibatch_next_states, minibatch_dones = sample_from_memory(
batch_size)
# Compute Q values for minibatch
Q_values_next = model.predict_on_batch(minibatch_next_states)
Q_targets = minibatch_rewards + (np.amax(Q_values_next, axis=1) * (1 - minibatch_dones))
# Update the Q values for the actions that were taken
Q_values = model.predict_on_batch(minibatch_states)
for i, action in enumerate(minibatch_actions):
Q_values[i, action] = Q_targets[i]
# Train the model on the minibatch
model.train_on_batch(minibatch_states, Q_values)
print(“Training
Completed”)
# Call the function without recursion
play_and_learn()
|
febf49cb5a30d08be0a1a63f3cab532e
|
{
"intermediate": 0.4065205752849579,
"beginner": 0.3395780920982361,
"expert": 0.25390127301216125
}
|
33,206
|
dota 2 addon. что не так в коде, почему не меняется скорость передвижения? function generic_speed:OnCreated( kv )
if not IsServer() then return end
self.duration = kv.duration
-- local resist = 1-self:GetParent():GetStatusResistance() --возможно нужно, если резист сам ен считается
-- local duration = kv.duration*resist
self:SetDuration(self.duration, true)
self.speed = kv.speed
print(self.speed)
end
function generic_speed:OnRefresh( kv )
if not IsServer() then return end
self.duration = kv.duration
-- local resist = 1-self:GetParent():GetStatusResistance() --возможно нужно, если резист сам ен считается
-- local duration = kv.duration*resist
self:SetDuration(self.duration, true)
self.speed = kv.speed
end
function generic_speed:OnDestroy( kv )
end
--------------------------------------------------------------------------------
function generic_speed:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
}
return funcs
end
function generic_speed:GetModifierMoveSpeedBonus_Percentage(kv)
self.value = self.speed or kv.speed
if not IsServer() then return end
print(self.value)
return self.speed
end
|
3714e100d88c6ecdd111667be3eea7de
|
{
"intermediate": 0.3638699948787689,
"beginner": 0.42671525478363037,
"expert": 0.20941470563411713
}
|
33,207
|
Make the following code run faster in c++ :#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
cin.tie(0)->sync_with_stdio(0);
int n, m;
int tick = 0;
int s = 0;
cin >> n >> m;
int arr[n];
for(int i = 0; i < n; i++){
cin >> arr[i];
}
sort(arr, arr+n);
for(int i = 0; i < n; i++){
for(int j = tick+1; j < n; j++){
if(i>=j){continue;}
else if(arr[i]+arr[j] <= m){
s++;
}
else{
break;
}
}
tick = i;
}
cout << s << endl;
return 0;
}
|
3e201eb5b70732448b6a12ad06d32b76
|
{
"intermediate": 0.36541497707366943,
"beginner": 0.3705079257488251,
"expert": 0.2640770673751831
}
|
33,208
|
package ai;
import controller.Game;
import java.util.Random;
/**
* The {@code Bot} class represents an automated player for the game.
* It is designed to simulate player actions in the game by making moves autonomously.
* The class contains logic to randomly decide between different actions such as moving
* left, moving right, or performing a long drop of the current game piece (MultiMino).
*
* <p>This class is an essential part of the AI (Artificial Intelligence) component of the game.
* It uses a {@code Random} object to generate random decisions, thereby introducing unpredictability
* in the bot's gameplay.</p>
*
* <p>Each move made by the bot is based on a random selection. The bot can move the current game piece
* to the left or right or perform a long drop to instantly bring the game piece to the lowest possible
* position. The actions are executed within the context of the provided {@code Game} instance.</p>
*
* <p>After making a move, if the game is not paused, it triggers a repaint of the game window to reflect
* the changes on the game board.</p>
*
* @version 0.1 - 2023-11-29, 16:05 PM
* @author Matthieu M
*
* TODO: bot
*
*/
public class Bot {
private Random random;
private int moveCount;
private int rotateCount;
public Bot() {
random = new Random();
moveCount = 0;
rotateCount = 0;
}
public void makeMove(Game game) {
// Step 1: Move left or right between 3 and 7 times
if (moveCount < 3 || (moveCount < 7 && random.nextBoolean())) {
boolean moveLeft = random.nextBoolean();
game.moveMultiMino(moveLeft ? -1 : 1, 0);
moveCount++;
}
// Step 2: Rotate between 1 and 4 times
else if (rotateCount < 1 || (rotateCount < 4 && random.nextBoolean())) {
game.rotateMultiMino(game.getCurrentMultiMino());
rotateCount++;
}
// Step 3: Long drop
else {
while (game.canMoveMultiMino(game.getCurrentMultiMino(), 0, 1)) {
game.moveMultiMino(0, 1);
}
resetCounts();
}
// Repaint the game window if it's not paused
if (!game.isPaused()) {
game.repaintWindow();
}
}
private void resetCounts() {
moveCount = 0;
rotateCount = 0;
}
}
package config;
import java.awt.*;
/**
* The {@code Config} class holds the configuration constants for the game.
* This includes settings for window size, board dimensions, color schemes, and game timings.
* This centralized configuration makes it easier to manage and modify the game's settings.
*
* @version 0.1 - last updated on 2023-11-18, 13:52 PM
* @author Matthieu M
*/
public class Config {
// Prevents instantiation
private Config() {}
// Window Settings
public static final String GAME_TITLE = "Basic Mino Game";
public static final int WINDOW_WIDTH = 1200;
public static final int WINDOW_HEIGHT = 900;
// Board Settings
public static final Color BACKGROUND_COLOR = new Color(0, 0, 60); // Dark blue
// Darker background color for the first five rows
public static final Color DARKER_BACKGROUND_COLOR = new Color(0, 0, 45);
public static final int CELL_SIZE = 30;
public static final int BOARD_WIDTH = 7;
public static final int BOARD_HEIGHT = 20;
// Game Timings
public static final int GAME_DELAY = 1000;
public static final int GAME_DELAY_DECREASE = 300;
public static final int GAME_DELAY_POINT_INCREMENTS = 3;
// Score Box Settings
public static final int SCORE_BOX_WIDTH = 250;
public static final int SCORE_BOX_HEIGHT = 250;
public static final int SCORE_BOX_PADDING = 50;
public static final Color SCORE_BOX_COLOR = Color.GRAY;
public static final Font SCORE_BOX_FONT = new Font("Arial", Font.BOLD, 16);
// Controls Box Settings
public static final int CONTROLS_BOX_PADDING = 50;
public static final int CONTROLS_BOX_RIGHT_PADDING = 10;
public static final Color CONTROLS_BOX_COLOR = Color.DARK_GRAY;
public static final Font CONTROLS_BOX_FONT = new Font("Arial", Font.BOLD, 16);
// Game Settings
public static final int POINTS_PER_ROW = 1;
// Game Controls
// TODO (MM): implement enums?
public static final String [] GAME_CONTROLS = {
"Keyboard Commands",
"",
"Controls:",
"Left Arrow - Move Left",
"Right Arrow - Move Right",
"Down Arrow - Move Down",
"Space Bar (Long Press) - Drop",
"P - Pause/Resume",
"ESC - Open Menu"
};
// AI
public static final int BOT_ACTION_DELAY = 200; // time between bot actions
}
package config;
import java.util.*;
/**
* The {@code MultiMinoTemplates} class contains the definitions of various Pentomino patterns used in the game.
* It provides a central repository of all the standard Pentomino shapes, represented as 2D arrays. Each array
* defines the structure of a Pentomino shape, where '1' represents a filled block and '0' represents an empty space.
*
* <p>This class is crucial for generating different Pentomino shapes in the game and can be easily extended to
* include new shapes. The patterns are used by the game engine to render the Pentominos on the game board.</p>
*
* <p>Key patterns include X, I, Z, T, U, V, W, Y, L, P, N, and F patterns, each representing a unique Pentomino.</p>
*
* @since 0.1
* @version 0.2 - added getAllPatternVariations() and its helper methods (2023-11-22, 13:46 PM)
*
* @author Matthieu M
*
*/
public class MultiMinoTemplates {
// Representation of the empty Pentomino
public static final int[][] EMPTY_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the X Pentomino
public static final int[][] X_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the I Pentomino
public static final int[][] I_PATTERN = {
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
};
// Representation of the Z Pentomino
public static final int[][] Z_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the T Pentomino
public static final int[][] T_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the U Pentomino
public static final int[][] U_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the V Pentomino
public static final int[][] V_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the W Pentomino
public static final int[][] W_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the Y Pentomino
public static final int[][] Y_PATTERN = {
{0, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the L Pentomino
public static final int[][] L_PATTERN = {
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the P Pentomino
public static final int[][] P_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 1, 1, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the N Pentomino
public static final int[][] N_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 1, 1, 1},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the N Pentomino
public static final int[][] F_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 1, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
};
/**
* Retrieves a specified pattern by its name.
*
* @param patternName The string name of the pattern to retrieve.
* @return A 2D integer array representing the requested pattern. Returns {@link #EMPTY_PATTERN} if the name does not match any known pattern.
*/
public static int[][] getPattern(String patternName) {
switch (patternName) {
case "X":
return X_PATTERN;
case "I":
return I_PATTERN;
case "Z":
return Z_PATTERN;
case "T":
return T_PATTERN;
case "U":
return U_PATTERN;
case "V":
return V_PATTERN;
case "W":
return W_PATTERN;
case "Y":
return Y_PATTERN;
case "L":
return L_PATTERN;
case "P":
return P_PATTERN;
case "N":
return N_PATTERN;
case "F":
return F_PATTERN;
default:
return EMPTY_PATTERN;
}
}
/**
* Retrieves a random pattern variation. This includes all possible rotations and flips of the patterns.
*
* @return A 2D integer array representing a randomly selected pattern variation.
*/
public static int[][] getRandomPatternVariation() {
List<int[][]> allVariations = getAllPatternVariations();
Random random = new Random();
return allVariations.get(random.nextInt(allVariations.size()));
}
/**
* Rotates a given pattern by 90 degrees clockwise.
*
* @param pattern The 2D integer array representing the pattern to rotate.
* @return A new 2D integer array representing the rotated pattern.
*/
private static int[][] rotate90(int[][] pattern) {
final int M = pattern.length;
final int N = pattern[0].length;
int[][] rotated = new int[N][M];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
rotated[c][M - 1 - r] = pattern[r][c];
}
}
return rotated;
}
/**
* Flips a given pattern horizontally.
*
* @param pattern The 2D integer array representing the pattern to flip.
* @return A new 2D integer array representing the horizontally flipped pattern.
*/
private static int[][] flipHorizontal(int[][] pattern) {
int[][] flipped = new int[pattern.length][pattern[0].length];
for (int i = 0; i < pattern.length; i++) {
for (int j = 0; j < pattern[i].length; j++) {
flipped[i][pattern[i].length - 1 - j] = pattern[i][j];
}
}
return flipped;
}
/**
* Generates all unique variations of a given pattern, including its rotations and horizontal flips.
*
* @param pattern The 2D integer array representing the base pattern.
* @return A list of 2D integer arrays, each representing a unique variation of the pattern.
*/
public static List<int[][]> generateAllVariations(int[][] pattern) {
Set<String> seen = new HashSet<>();
List<int[][]> variations = new ArrayList<>();
int[][] current = pattern;
for (int i = 0; i < 4; i++) { // 4 rotations
current = rotate90(current);
if (seen.add(Arrays.deepToString(current))) {
variations.add(current);
}
int[][] flippedH = flipHorizontal(current);
if (seen.add(Arrays.deepToString(flippedH))) {
variations.add(flippedH);
}
}
return variations;
}
/**
* Compiles all variations of each predefined pattern into a single list. This includes rotations and horizontal flips of each pattern.
*
* @return A list of 2D integer arrays, each representing a unique pattern variation from the set of predefined patterns.
*/
public static List<int[][]> getAllPatternVariations() {
List<int[][]> allVariations = new ArrayList<>();
int[][][] patterns = {X_PATTERN, I_PATTERN, Z_PATTERN, T_PATTERN, U_PATTERN, V_PATTERN, W_PATTERN, Y_PATTERN, L_PATTERN, P_PATTERN, N_PATTERN, F_PATTERN};
for (int[][] pattern : patterns) {
allVariations.addAll(generateAllVariations(pattern));
}
return allVariations;
}
// Place additional patterns and methods here
}
|
182fd800721188f2d906475f27e58056
|
{
"intermediate": 0.3883313536643982,
"beginner": 0.37328043580055237,
"expert": 0.23838821053504944
}
|
33,209
|
write a python code for gradio for a editable chatbot
|
14369a56348c645cd34a92b7ef300979
|
{
"intermediate": 0.35231199860572815,
"beginner": 0.1430988311767578,
"expert": 0.5045892000198364
}
|
33,210
|
Can you modify this code to make it better?
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]
"Steam"="\"C:\\Program Files (x86)\\Steam\\steam.exe\" -silent -dev -nofriendsui -no-dwrite -nointro -nobigpicture -nofasthtml -nocrashmonitor -noshaders -no-shared-textures -disablehighdpi -cef-single-process -cef-in-process-gpu -single_core -cef-disable-d3d11 -cef-disable-sandbox -disable-winh264 -cef-force-32bit -no-cef-sandbox -vrdisable -cef-disable-breakpad"
to join this conversation on GitHub. Already have an account? Sign in to comment
|
66c983f545281671a265c1b8739043e0
|
{
"intermediate": 0.40732917189598083,
"beginner": 0.3626011312007904,
"expert": 0.23006966710090637
}
|
33,211
|
Dopamine Mechanism:
Role: Controls the reward system, encouraging behaviors that lead to positive outcomes.
Modification: Adjusted by the ‘prediction to event match score’. The closer the AI’s predictions are to actual outcomes, the greater the reward, enhancing learning efficiency.
Norepinephrine Mechanism:
Role: Modifies the system’s firing speed, influencing overall responsiveness.
Modification: Adjustable by the attention mechanism, allowing for dynamic regulation of processing speed based on the current focus or importance of tasks.
Acetylcholine Mechanism:
Role: Directly involved in modulating attention.
Potential Implementation: Could be integrated with or parallel to the Q-function quality array, determining the focus of the system based on expected rewards or priorities.
Serotonin Mechanism:
Role: Influences the mood state and motivation, particularly in relation to effort versus reward.
Implementation: A complex mechanism involving two 3D vector spaces, indicating a nuanced approach to representing mood and motivational states.
Glutamate Mechanism:
Role: Acts as a communication network between nodes/neurons.
Unique Features:
Utilizes a ‘glutamate number’ to coordinate firing across the network.
A secondary glutamate network (G2M) tracks groups of neurons firing simultaneously, enhancing the firing probability of associated neurons.
Modification: Influenced by specific inputs, representing different ‘brain waves’ that activate various parts of the network.
GABA Mechanism:
Role: Functions as an antagonist to glutamate, reducing network activation.
Implementation: Decreases the G2 number of neurons that did not fire together despite having the same original glutamate number, thereby acting as an inhibitory mechanism.
In this system, each neurotransmitter-like mechanism has a distinct role, from modulating learning and attention to regulating the speed and synchronization of neural firing. The complexity of this model, particularly with the secondary glutamate network and the intricate mood and motivation representations, suggests a highly dynamic and adaptable AI, capable of nuanced decision-making and learning processes.
Vector Space 1 - Basic Emotional States:
This space represents primary emotions (e.g., happiness, sadness, anger).
Each vector in this space points to a specific basic emotion. The direction of the vector indicates the type of emotion, and the magnitude (length) indicates the intensity.
Vector Space 2 - Complex Emotional States:
Represents more nuanced emotional states (e.g., guilt, pride, empathy).
Similar to the first space, the direction and magnitude of each vector represent the type and intensity of complex emotions.
Implementation Details
Defining Vectors:
Assign axes in each vector space to different emotions. For example, one axis might represent happiness to sadness, another might represent calmness to anger, etc.
Vectors are determined based on stimuli or internal states. For instance, a positive stimulus might increase the vector component towards happiness.
Interaction Between Vector Spaces:
Define how vectors in the basic emotion space influence vectors in the complex emotion space. For example, sustained vectors pointing towards negative emotions in the first space might influence the development of vectors in the second space towards emotions like guilt.
Temporal Dynamics and Adaptation:
Include mechanisms for vectors to change over time, either gradually moving back to a neutral state or adapting based on ongoing stimuli.
Vectors can also adapt based on the AI’s experiences, learning, or predefined rules.
Dopamine and Endorphins in Memory and Reward Systems:
Dopamine Score: Each neuron maintains a dopamine score reflecting its cumulative success or effectiveness. This could relate to how well certain decisions or actions have led to positive outcomes.
Memory System: Periodic sweeps by a memory system that convolutes and analyzes the brain mapping, redistributing endorphins based on this analysis. This approach would allow for the reinforcement of successful neural pathways and decisions.
Endorphin State and Memory: Storing the endorphin state in a waking memory contributes to incremental boosts in G2 levels and the reward system, reinforcing successful patterns.
Substance P, GABA, and Error Handling:
Substance P as Error Signal: Acts as an error or negative feedback signal, particularly informing the attention system of discrepancies or issues.
Modulation of GABA: Increases the inhibitory action by boosting GABA effects, leading to a reduction in G2 scores and dampening the reward system in response to errors or negative outcomes.
Oxytocin’s Role in Social Interactions:
Influencing Dopamine and GABA: Oxytocin adjusts dopamine and GABA levels based on the nature of social interactions. Positive social interactions increase dopamine (reward and motivation), while less favorable or solitary activities might increase GABA (inhibition).
Bias Toward Collaboration: The system favors collaborative efforts, with a base state favoring interactions with others over solitary work. The magnitude of adjustments depends on the nature and context of the interactions.
Anandamide as a Mood Stabilizer:
Mood Regulation: Anandamide acts to maintain a baseline mood level, preventing the AI from dropping into excessively negative states. This ensures a level of stability and consistency in decision-making and interactions, regardless of recent negative feedback or challenges.
given these axioms design the full code for this section of the code
Q-learning is a model-free reinforcement learning algorithm. It involves learning the value of an action in a particular state, using a Q-table to store these values. The AI selects its actions based on the highest Q-value for a given state but also explores the environment to learn about different state-action outcomes.
2. Integration with Neurotransmitter and Neuromodulator Dynamics
Dopamine: Influences the reward values in the Q-table, possibly enhancing the rewards for certain actions based on successful outcomes.
Endorphins: Could modulate the long-term reinforcement of actions, perhaps influencing the learning rate or the discount factor in the Q-learning algorithm.
Substance P: Acts as a feedback mechanism for incorrect actions or errors, potentially reducing the Q-values for certain actions that lead to negative outcomes.
Oxytocin: Might adjust the Q-values or decision policy in social contexts, favoring actions that enhance social interactions.
Anandamide: Could provide a stabilizing effect on the Q-table, preventing extreme fluctuations in Q-values due to transient mood states or stressors
|
8b3a2955d4b71cd6f43c92b98d21c3fb
|
{
"intermediate": 0.35369277000427246,
"beginner": 0.3920156955718994,
"expert": 0.25429150462150574
}
|
33,212
|
Can you update this code for 2023?
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]
"Steam"="\"C:\\Program Files (x86)\\Steam\\steam.exe\" -silent -dev -nofriendsui -no-dwrite -nointro -nobigpicture -nofasthtml -nocrashmonitor -noshaders -no-shared-textures -disablehighdpi -cef-single-process -cef-in-process-gpu -single_core -cef-disable-d3d11 -cef-disable-sandbox -disable-winh264 -cef-force-32bit -no-cef-sandbox -vrdisable -cef-disable-breakpad"
|
c50057fefab512b495c19302396b7001
|
{
"intermediate": 0.3950420320034027,
"beginner": 0.3431539833545685,
"expert": 0.2618039548397064
}
|
33,213
|
is it possible to send an email after a nextflow pipeline is completed?
|
7b0dcf588544ad5dc111bd6358feb7b6
|
{
"intermediate": 0.5080385804176331,
"beginner": 0.10512251406908035,
"expert": 0.38683897256851196
}
|
33,214
|
How can I send an email after a nextflow pipeline is finished on an HPC running with SGE?
|
f2c88fe1ec46410b738f646610e3d20f
|
{
"intermediate": 0.45299839973449707,
"beginner": 0.11829457432031631,
"expert": 0.42870697379112244
}
|
33,215
|
Write a C++ program. User enters dimensions for a matrix initialized with natural numbers. Print the matrix out in following ways:
1. By rows starting from the 1st one
2. By rows starting from the last one
3. By columns starting from the 1st one
4. By columns starting from the last one
5. Snake-game like
|
70a6419e68a1233510f35ad18a2a12f8
|
{
"intermediate": 0.3786395192146301,
"beginner": 0.32595500349998474,
"expert": 0.29540547728538513
}
|
33,216
|
Construct a perfect hashing function using Cichelli’s algorithm with the keys
below. Use a maximum value of 3 for assigning to characters.
Keys: ece mert ada eda nuri iclal aydan
|
1307ae859c29245715e14515fff13a73
|
{
"intermediate": 0.21001695096492767,
"beginner": 0.14653441309928894,
"expert": 0.6434485912322998
}
|
33,217
|
I want to set this up so steam so just barebones with the lowest amount of bloat when i start my pc:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]
"Steam"=""C:\Program Files (x86)\Steam\steam.exe"
|
0c7961c224e7173cca082338e5ad993d
|
{
"intermediate": 0.23269565403461456,
"beginner": 0.4118015170097351,
"expert": 0.3555028736591339
}
|
33,218
|
The following code is almost complete. I just need for the output from a given input to be saved in the same cell in the output file as in the input file.
import openpyxl
import re
# Open the input Excel file
wb = openpyxl.load_workbook('Flo-4-674-Output.xlsx')
ws = wb['Sheet1']
# Create a new Excel file for the output
output_wb = openpyxl.Workbook()
output_ws = output_wb.active
# Iterate over the cells in the input sheet
for row in ws.iter_rows(values_only=True):
# Check if the cell contains a dollar value
if '$' in str(row[0]):
# Extract the sentence containing the dollar value
sentence = re.search(r'\$.*', str(row[0])).group()
# Write the sentence to the output sheet
output_ws.append([sentence])
# Save the output Excel file
output_wb.save('Flo-4-674-Output-V2.xlsx')
|
8bcb3ac29f117a8f187da04f5f85fd61
|
{
"intermediate": 0.3998444378376007,
"beginner": 0.30888721346855164,
"expert": 0.29126831889152527
}
|
33,219
|
how does git upload to online repository websites like GitHub
|
8282cadc443d4753f9ba1a6abac274fa
|
{
"intermediate": 0.5153525471687317,
"beginner": 0.2568413317203522,
"expert": 0.22780616581439972
}
|
33,220
|
#pragma once
#include <iostream>
class Array{
public:
Array(size_t x, size_t y, size_t z);
~Array();
Array& operator=(const Array& other);
static Array MakeArray(size_t x, size_t y, size_t z);
int GetIndex(size_t x, size_t y, size_t z) const;
int GetCurX() const;
int GetCurY() const;
int GetCurZ() const;
int GetX() const;
int GetY() const;
int GetZ() const;
void StoreElement(size_t x, size_t y, size_t z, uint32_t number);
uint32_t GetElement(size_t x, size_t y, size_t z) const;
Array& operator[](size_t index);
Array& operator=(uint32_t x);
friend std::ostream& operator<<(std::ostream& stream, const Array& val);
friend std::istream& operator>>(std::istream& stream, Array& val);
Array operator*(uint32_t num);
friend Array operator-(const Array& lhs, const Array& rhs);
friend Array operator+(const Array& lhs, const Array& rhs);
private:
uint32_t* arr_;
size_t x_;
size_t y_;
size_t z_;
size_t current_x_;
size_t current_y_;
size_t current_z_;
};
#include "/Users/alishashelby/Desktop/labwork5-alishashelby/lib/3D17BitArray.h"
Array::Array(size_t x, size_t y, size_t z) {
x_ = x;
y_ = y;
z_ = z;
arr_ = new uint32_t[x * y * z];
for (size_t i = 0; i < x * y * z; ++i) {
arr_[i] = 0;
}
}
Array::~Array() {
delete[] arr_;
}
Array& Array::operator=(const Array& other) {
delete[] arr_;
x_ = other.x_;
y_ = other.y_;
z_ = other.z_;
arr_ = new uint32_t[x_ * y_ * z_];
for (size_t i = 0; i < x_ * y_ * z_; ++i) {
arr_[i] = other.arr_[i];
}
return *this;
}
Array Array::MakeArray(size_t x, size_t y, size_t z) {
return Array(x, y, z);
}
int Array::GetIndex(size_t x, size_t y, size_t z) const {
return ((x * y_ + y) * z_ + z) * 17;
}
int Array::GetCurX() const {
return current_x_;
}
int Array::GetCurY() const {
return current_y_;
}
int Array::GetCurZ() const {
return current_z_;
}
int Array::GetX() const {
return x_;
}
int Array::GetY() const {
return y_;
}
int Array::GetZ() const {
return z_;
}
void Array::StoreElement(size_t x, size_t y, size_t z, uint32_t number) {
size_t bit_start = GetIndex(x, y, z);
//std::cout << bit_start<< '\n';
for (int i = 0; i < 17; ++i) {
if ((number >> i) & 1) {
arr_[bit_start / 32] |= (1 << bit_start % 32);
} else {
arr_[bit_start / 32] &= ~(1 << bit_start % 32);
}
++bit_start;
}
}
uint32_t Array::GetElement(size_t x, size_t y, size_t z) const {
size_t bit_start = GetIndex(x, y, z);
uint32_t value = 0;
for (int i = 0; i < 17; ++i) {
if (arr_[bit_start / 32] & (1 << (bit_start % 32))) {
value |= (1 << i);
}
++bit_start;
}
return value;
}
Array& Array::operator[](size_t index) {
static int operator_count = 0;
if (operator_count == 0) {
current_x_ = index;
}
if (operator_count == 1) {
current_y_ = index;
}
if (operator_count == 2) {
current_z_ = index;
operator_count = -1;
}
++operator_count;
return *this;
}
Array& Array::operator=(uint32_t x) {
StoreElement(current_x_, current_y_, current_z_, x);
return *this;
}
std::ostream& operator<<(std::ostream& stream, const Array& val) {
uint32_t number = val.GetElement(val.GetCurX(), val.GetCurY(), val.GetCurZ());
stream << number;
/*for (int i = 16; i >= 0; --i) {
stream << ((number >> i) & 1);
}*/
return stream;
}
std::istream& operator>>(std::istream& stream, Array& val) {
size_t x, y, z;
uint32_t value;
stream >> x >> y >> z >> value;
val.StoreElement(x, y, z, value);
return stream;
}
Array Array::operator*(uint32_t num) {
Array new_arr(x_, y_, z_);
for (size_t i = 0; i < x_; ++i) {
for (size_t j = 0; j < y_; ++j) {
for (size_t k = 0; k < z_; ++k) {
uint32_t temp = (*this).GetElement(i, j, k);
new_arr.StoreElement(i, j, k, temp * num);
}
}
}
return new_arr;
}
Array operator-(const Array& lhs, const Array& rhs) {
if (lhs.GetX() != rhs.GetX() || lhs.GetY() != rhs.GetY() || lhs.GetZ() != rhs.GetZ()) {
std::cerr << "--array sizes do not match";
std::exit(EXIT_FAILURE);
}
size_t x = lhs.GetX();
size_t y = lhs.GetY();
size_t z = lhs.GetZ();
Array new_arr(x, y, z);
for (size_t i = 0; i < x; ++i) {
for (size_t j = 0; j < y; ++j) {
for (size_t k = 0; k < z; ++k) {
uint32_t temp = lhs.GetElement(i, j, k) - rhs.GetElement(i, j, k);
new_arr.StoreElement(i, j, k, temp);
}
}
}
return new_arr;
}
Array operator+(const Array& lhs, const Array& rhs) {
if (lhs.GetX() != rhs.GetX() || lhs.GetY() != rhs.GetY() || lhs.GetZ() != rhs.GetZ()) {
std::cerr << "--array sizes do not match";
std::exit(EXIT_FAILURE);
}
size_t x = lhs.GetX();
size_t y = lhs.GetY();
size_t z = lhs.GetZ();
Array new_arr(x, y, z);
for (size_t i = 0; i < x; ++i) {
for (size_t j = 0; j < y; ++j) {
for (size_t k = 0; k < z; ++k) {
uint32_t temp = lhs.GetElement(i, j, k) + rhs.GetElement(i, j, k);
new_arr.StoreElement(i, j, k, temp);
}
}
}
return new_arr;
}
write in file 3D17BitArray.cpp GoogleTests for my implementation #include "/Users/alishashelby/Desktop/labwork5-alishashelby/lib/3D17BitArray.h"
#include <gtest/gtest.h>
#include <sstream>
TEST(3D17BitArrayTestSuite, EmptyTest) {
Array arr = Array::MakeArray(10, 2, 30);
arr[4][1][2] = 100500;
std::cout << arr[4][1][2];
}include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.12.1
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
add_executable(
3D17BitArray_tests
3D17BitArray_test.cpp
)
target_link_libraries(
3D17BitArray_tests
3D17BitArray
GTest::gtest_main
)
target_include_directories(3D17BitArray_tests PUBLIC ${PROJECT_SOURCE_DIR})
include(GoogleTest)
gtest_discover_tests(3D17BitArray_tests)
|
dd0204bdb72e342517a62e7d4aca01fb
|
{
"intermediate": 0.3271079957485199,
"beginner": 0.445639431476593,
"expert": 0.22725249826908112
}
|
33,221
|
linux file permissions
|
27e48420467fd071389513767dd7020a
|
{
"intermediate": 0.3395048975944519,
"beginner": 0.3003355860710144,
"expert": 0.3601595163345337
}
|
33,222
|
How do I globally tell eclipse to ignore all DS_Store files
|
223d7f89f5aa4567a2ff0001e250eeb2
|
{
"intermediate": 0.47472086548805237,
"beginner": 0.20289120078086853,
"expert": 0.3223879039287567
}
|
33,223
|
How do I open a ds_store file with terminal with text edit
|
b6dcc61131cbdee6d8c2f7f0724e9043
|
{
"intermediate": 0.4813030958175659,
"beginner": 0.18944628536701202,
"expert": 0.32925063371658325
}
|
33,224
|
how can I configure the sendmail tool?
|
fcaf913e9b97c85573c470abead3ab58
|
{
"intermediate": 0.4534735679626465,
"beginner": 0.2954762279987335,
"expert": 0.2510501444339752
}
|
33,225
|
Certainly! Here is a guide for implementing similar steps in Azure:
Step 1: Create a Virtual Network (VNet)
1. Log in to your Azure account.
2. Go to the Azure portal.
3. Click on “Create a resource” and search for “Virtual Network.”
4. Click “Create” to start creating a Virtual Network.
5. Enter a name for your VNet and choose the subscription and resource group.
6. Set the address space for your VNet (e.g., 10.0.0.0/16).
7. Configure other settings as needed and click “Create” to create the VNet.
Step 2: Add Subnets
1. In the Azure portal, navigate to your VNet.
2. Click on “Subnets” in the navigation menu.
3. Click “+ Subnet” to add a subnet.
4. Enter a name for the subnet and set the address range (e.g., 10.0.1.0/24).
5. Repeat the process to create another subnet for the public resources.
Step 3: Create a Network Gateway (For Internet Connectivity)
1. In the Azure portal, navigate to your VNet.
2. Click on “Create a resource” and search for “Virtual Network Gateway”.
3. Click “Create” to start creating a Virtual Network Gateway.
4. Configure the required settings for the gateway, including public IP, virtual network, and other settings.
5. Click “Create” to create the Network Gateway.
Step 4: Configure Routing
1. In the Azure portal, navigate to your VNet.
2. Click on “Routing” in the navigation menu.
3. Configure route tables as needed to control traffic flow between subnets and the internet.
4. Associate the route tables with the appropriate subnets.
Step 5: Security and Network Security Groups
1. In the Azure portal, navigate to your VNet.
2. Click on “Security” in the navigation menu.
3. Configure network security groups (NSGs) to control inbound and outbound traffic to subnets.
4. Associate the NSGs with the appropriate subnets.
Step 6: Show Evidence of Resources
Take screenshots or capture the necessary information for each step mentioned in the lab activity.
Step 7: Submission
Create a document following the specified format.
Answer the questions and provide details from each step.
Insert screenshots or captured information in the appropriate sections.
Ensure clarity and coherence.
Submit the document as per the specified naming convention.
Step 8: Delete Resources
Once the lab activity is complete and your submission is accepted, remember to delete all the resources to avoid unnecessary charges.
These steps provide a general guide for implementing the lab activity in Azure. The Azure portal may have updates or changes over time, so it’s recommended to consult the Azure documentation or seek Azure-specific tutorials for more details on each step.
|
7938a1e1d33e4cdfc19fe2393f796934
|
{
"intermediate": 0.336963951587677,
"beginner": 0.2968432307243347,
"expert": 0.3661927878856659
}
|
33,226
|
In sql, select the partial string up to the 2nd whitespace in "AB 1.23 zyxabc"
|
ff61da720a606fe20b5b811e656de255
|
{
"intermediate": 0.3166097104549408,
"beginner": 0.25480353832244873,
"expert": 0.4285866916179657
}
|
33,227
|
When I'm running a JDA bot from a jar file, I don't want errors to be printed to the terminal, I want to be able to send them to the user and put them in a file. What's the setup required to do this with JDA?
|
66c4881b9c1fd9c8639f157d519df742
|
{
"intermediate": 0.6723307371139526,
"beginner": 0.0789385437965393,
"expert": 0.24873073399066925
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.