row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
1,103
|
add a text view of the latest data from a node of a firebase database
|
42ce11c479353585c9737594f6665e6a
|
{
"intermediate": 0.4443676471710205,
"beginner": 0.22819462418556213,
"expert": 0.32743778824806213
}
|
1,104
|
Fix the error java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 .
private void cannyImage() {
if (image != null) {
String inputMask = JOptionPane.showInputDialog(this, "Enter a mask size (odd number >= 3):");
int kernelSize = Integer.parseInt(inputMask);
if (kernelSize % 2 == 0 || kernelSize < 3) {
JOptionPane.showMessageDialog(this, "Invalid mask size. Please enter an odd number >= 3.");
return;
}
float[][] mask = new float[kernelSize][kernelSize];
for (int i = 0; i < mask.length; i++) {
for (int j = 0; j < mask[i].length; j++) {
mask[i][j] = 1.0f / (mask.length * mask[i].length);
}
}
// Use a custom input dialog with a slider for the threshold values
JPanel panel = new JPanel(new GridLayout(0, 1));
JSlider lowThresholdSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 50);
JSlider highThresholdSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 100);
panel.add(new JLabel("Low Threshold:"));
panel.add(lowThresholdSlider);
panel.add(new JLabel("High Threshold:"));
panel.add(highThresholdSlider);
int result = JOptionPane.showOptionDialog(this, panel, "Enter Threshold Values", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
int lowThreshold = lowThresholdSlider.getValue();
int highThreshold = highThresholdSlider.getValue();
applyCannyEdgeDetector(image, mask, lowThreshold, highThreshold, kernelSize);
}
}
}
private BufferedImage applyCannyEdgeDetector(BufferedImage image, float[][] mask, int lowThreshold, int highThreshold, int kernelSize) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = new int[width * height];
int[] edges = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
int[][] sobelX = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
int[][] sobelY = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
int[] grayPixels = convertToGrayscale(pixels);
int[] gradientX = getConvolution(grayPixels, sobelX, width, height, kernelSize);
int[] gradientY = getConvolution(grayPixels, sobelY, width, height, kernelSize);
for (int i = 0; i < pixels.length; i++) {
int gx = gradientX[i];
int gy = gradientY[i];
edges[i] = (int) Math.sqrt(gx * gx + gy * gy);
}
int[] thresholdEdges = applyHysteresis(edges, lowThreshold, highThreshold, width, height);
for (int i = 0; i < pixels.length; i++) {
if (thresholdEdges[i] != 0) {
resultImage.setRGB(i % width, i / width, 0);
} else {
resultImage.setRGB(i % width, i / width, 0xFFFFFF);
}
}
return resultImage;
}
private int[] applyHysteresis(int[] edges, int low, int high, int width, int height) {
int[] result = new int[edges.length];
Arrays.fill(result, 0);
for (int i = 0; i < edges.length; i++) {
if (edges[i] >= high && result[i] == 0) {
trace(result, edges, low, high, i, width, height);
}
}
return result;
}
private void trace(int[] result, int[] edges, int low, int high, int i, int width, int height) {
result[i] = 255;
LinkedList<Integer> queue = new LinkedList<>();
queue.offer(i);
while (!queue.isEmpty()) {
int currIndex = queue.poll();
int currX = currIndex % width;
int currY = currIndex / width;
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
int neighborX = currX + k;
int neighborY = currY + j;
int neighborIndex = neighborY * width + neighborX;
if (neighborX >= 0 && neighborX < width &&
neighborY >= 0 && neighborY < height &&
neighborIndex >= 0 && neighborIndex < edges.length &&
result[neighborIndex] == 0 && edges[neighborIndex] >= low &&
edges[neighborIndex] <= high) {
result[neighborIndex] = 255;
queue.offer(neighborIndex);
}
}
}
}
}
private int[] getConvolution(int[] pixels, int[][] filter, int width, int height, int kernelSize) {
int[] result = new int[pixels.length];
int radius = kernelSize / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double sum = 0.0;
for (int ky = -radius; ky <= radius; ky++) {
for (int kx = -radius; kx <= radius; kx++) {
int px = x + kx;
int py = y + ky;
if (px >= 0 && px < width && py >= 0 && py < height) {
int i = py * width + px;
double value = (double) pixels[i];
sum += value * filter[ky + radius][kx + radius];
}
}
}
int i = y * width + x;
result[i] = (int) sum;
}
}
return result;
}
private int[] convertToGrayscale(int[] pixels) {
int[] grayPixels = new int[pixels.length];
for (int i = 0; i < pixels.length; i++) {
int r = (pixels[i] >> 16) & 0xFF;
int g = (pixels[i] >> 8) & 0xFF;
int b = pixels[i] & 0xFF;
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b);
grayPixels[i] = (gray << 16) + (gray << 8) + gray;
}
return grayPixels;
}
|
46176350d06834b176fe166c3e9d5b3c
|
{
"intermediate": 0.32795289158821106,
"beginner": 0.39407870173454285,
"expert": 0.2779684364795685
}
|
1,105
|
Fix the error Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 3. In this code.
private void cannyImage() {
if (image != null) {
String inputMask = JOptionPane.showInputDialog(this, "Enter a mask size (odd number >= 3):");
int kernelSize = Integer.parseInt(inputMask);
if (kernelSize % 2 == 0 || kernelSize < 3) {
JOptionPane.showMessageDialog(this, "Invalid mask size. Please enter an odd number >= 3.");
return;
}
float[][] mask = new float[kernelSize][kernelSize];
for (int i = 0; i < mask.length; i++) {
for (int j = 0; j < mask[i].length; j++) {
mask[i][j] = 1.0f / (mask.length * mask[i].length);
}
}
// Use a custom input dialog with a slider for the threshold values
JPanel panel = new JPanel(new GridLayout(0, 1));
JSlider lowThresholdSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 50);
JSlider highThresholdSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 100);
panel.add(new JLabel("Low Threshold:"));
panel.add(lowThresholdSlider);
panel.add(new JLabel("High Threshold:"));
panel.add(highThresholdSlider);
int result = JOptionPane.showOptionDialog(this, panel, "Enter Threshold Values", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
int lowThreshold = lowThresholdSlider.getValue();
int highThreshold = highThresholdSlider.getValue();
applyCannyEdgeDetector(image, mask, lowThreshold, highThreshold, kernelSize);
}
}
}
private BufferedImage applyCannyEdgeDetector(BufferedImage image, float[][] mask, int lowThreshold, int highThreshold, int kernelSize) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = new int[width * height];
int[] edges = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
int[][] sobelX = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
int[][] sobelY = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
int[] grayPixels = convertToGrayscale(pixels);
int[] gradientX = getConvolution(grayPixels, sobelX, width, height, kernelSize);
int[] gradientY = getConvolution(grayPixels, sobelY, width, height, kernelSize);
for (int i = 0; i < pixels.length; i++) {
int gx = gradientX[i];
int gy = gradientY[i];
edges[i] = (int) Math.sqrt(gx * gx + gy * gy);
}
int[] thresholdEdges = applyHysteresis(edges, lowThreshold, highThreshold, width, height);
for (int i = 0; i < pixels.length; i++) {
if (thresholdEdges[i] != 0) {
resultImage.setRGB(i % width, i / width, 0);
} else {
resultImage.setRGB(i % width, i / width, 0xFFFFFF);
}
}
return resultImage;
}
private int[] applyHysteresis(int[] edges, int low, int high, int width, int height) {
int[] result = new int[edges.length];
Arrays.fill(result, 0);
for (int i = 0; i < edges.length; i++) {
if (edges[i] >= high && result[i] == 0) {
trace(result, edges, low, high, i, width, height);
}
}
return result;
}
private void trace(int[] result, int[] edges, int low, int high, int i, int width, int height) {
result[i] = 255;
LinkedList<Integer> queue = new LinkedList<>();
queue.offer(i);
while (!queue.isEmpty()) {
int currIndex = queue.poll();
int currX = currIndex % width;
int currY = currIndex / width;
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
int neighborX = currX + k;
int neighborY = currY + j;
int neighborIndex = neighborY * width + neighborX;
if (neighborX >= 0 && neighborX < width &&
neighborY >= 0 && neighborY < height &&
neighborIndex >= 0 && neighborIndex < edges.length &&
result[neighborIndex] == 0 && edges[neighborIndex] >= low &&
edges[neighborIndex] <= high) {
result[neighborIndex] = 255;
queue.offer(neighborIndex);
}
}
}
}
}
private int[] getConvolution(int[] pixels, int[][] filter, int width, int height, int kernelSize) {
int[] result = new int[pixels.length];
int radius = kernelSize / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double sum = 0.0;
for (int ky = -radius; ky <= radius && ky < kernelSize; ky++) {
for (int kx = -radius; kx <= radius && kx < kernelSize; kx++) {
int px = x + kx;
int py = y + ky;
if (px >= 0 && px < width && py >= 0 && py < height) {
int i = py * width + px;
double value = (double) pixels[i];
sum += value * filter[ky + radius][kx + radius];
}
}
}
int i = y * width + x;
result[i] = (int) sum;
}
}
return result;
}
private int[] convertToGrayscale(int[] pixels) {
int[] grayPixels = new int[pixels.length];
for (int i = 0; i < pixels.length; i++) {
int r = (pixels[i] >> 16) & 0xFF;
int g = (pixels[i] >> 8) & 0xFF;
int b = pixels[i] & 0xFF;
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b);
grayPixels[i] = (gray << 16) + (gray << 8) + gray;
}
return grayPixels;
}
|
c9ea8b1e8f88db78ceb03e775d36d197
|
{
"intermediate": 0.3604711890220642,
"beginner": 0.3814069330692291,
"expert": 0.2581218481063843
}
|
1,106
|
Write an open processing sketch in java mode that will accept pasted javascript and html code and return all the div elements that are user inputs such as buttons, radios, and text areas
|
96c92a4560b659198e907dad203be48b
|
{
"intermediate": 0.6059431433677673,
"beginner": 0.09505467116832733,
"expert": 0.29900217056274414
}
|
1,107
|
Fix the code.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cannyButton) {
cannyImage();
}
}
private void cannyImage() {
if (image != null) {
String inputMask = JOptionPane.showInputDialog(this,"Enter a mask size (odd number >= 3)");
int kernelSize = Integer.parseInt(inputMask);
if (kernelSize % 2 == 0 || kernelSize < 3) {
JOptionPane.showMessageDialog(this,"INlid mask size. Please enter an odd number >= 3.");
return;
}
float[][] mask = new float[kernelSize][kernelSize];
for (int i = 0; i < mask.length; i++) {
for (int j = 0; j < mask[i].length; j++) {
mask[i][j] = 1.0f / (mask.length * mask[i].length);
}
}
// Use a custom input dialog with a slider for the threshold values
JPanel panel = new JPanel(new GridLayout(0, 1));
JSlider lowThresholdSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 50);
JSlider highThresholdSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 100);
panel.add(new JLabel("Low Threshold:"));
panel.add(lowThresholdSlider);
panel.add(new JLabel("High Threshold:"));
panel.add(highThresholdSlider);
int result = JOptionPane.showOptionDialog(this, panel,
"Enter Threshold Values",JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
int lowThreshold = lowThresholdSlider.getValue();
int highThreshold = highThresholdSlider.getValue();
applyCannyEdgeDetector(image, mask, lowThreshold, highThreshold,
kernelSize);
}
}
}
private BufferedImage applyCannyEdgeDetector(BufferedImage image,
float[][] mask, int lowThreshold, int highThreshold, int kernelSize) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
int[] pixels = new int[width * height];
int[] edges = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
int[] grayPixels = convertToGrayscale(pixels);
int[] gradientX = getConvolution(grayPixels, sobelX, width, height, kernelSize);
int[] gradientY = getConvolution(grayPixels, sobelY, width, height, kernelSize);
for (int i = 0; i < pixels.length; i++) {
int gx = gradientX[i];
int gy = gradientY[i];
edges[i] = (int) Math.sqrt(gx * gx + gy * gy);
}
int[] thresholdEdges = applyHysteresis(edges, lowThreshold, highThreshold, width, height);
for (int i = 0; i < pixels.length; i++) {
if (thresholdEdges[i] != 0) {
resultImage.setRGB(i % width, i / width, Color.BLACK.getRGB());
} else {
resultImage.setRGB(i % width, i / width, 0xFFFFFF);
}
}
return resultImage;
}
private int[] applyHysteresis(int[] edges, int low, int high, int width, int height) {
int[] result = new int[edges.length];
Arrays.fill(result, 0);
for (int i = 0; i < edges.length; i++) {
if (edges[i] >= high && result[i] == 0) {
trace(result, edges, low, high, i, width, height);
}
}
return result;
}
private void trace(int[] result, int[] edges, int low, int high, int i, int width, int height) {
result[i] = 255;
LinkedList<Integer> queue = new LinkedList<>();
queue.offer(i);
while (!queue.isEmpty()) {
int currIndex = queue.poll();
int currX = currIndex % width;
int currY = currIndex / width;
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
int neighborX = currX + k;
int neighborY = currY + j;
int neighborIndex = neighborY * width + neighborX;
if (neighborX >= 0 && neighborX < width &&
neighborY >= 0 && neighborY < height &&
neighborIndex >= 0 && neighborIndex < edges.length &&
result[neighborIndex] == 0 && edges[neighborIndex] >= low &&
edges[neighborIndex] <= high) {
result[neighborIndex] = 255;
queue.offer(neighborIndex);
}
}
}
}
}
private int[] getConvolution(int[] pixels, int[][] filter, int width, int height, int kernelSize) {
int[] result = new int[pixels.length];
int radius = kernelSize / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double sum = 0.0;
for (int ky = -radius; ky <= radius && ky < kernelSize; ky++) {
for (int kx = -radius; kx <= radius && kx < kernelSize; kx++) {
int px = x + kx;
int py = y + ky;
if (px >= 0 && px < width && py >= 0 && py < height) {
int i = py * width + px;
double value = (double) pixels[i];
sum += value * filter[ky + radius][kx + radius];
}
}
}
int i = y * width + x;
result[i] = (int) sum;
}
}
return result;
}
private int[] convertToGrayscale(int[] pixels) {
int[] grayPixels = new int[pixels.length];
for (int i = 0; i < pixels.length; i++) {
int r = (pixels[i] >> 16) & 0xFF;
int g = (pixels[i] >> 8) & 0xFF;
int b = pixels[i] & 0xFF;
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b);
grayPixels[i] = (gray << 16) + (gray << 8) + gray;
}
return grayPixels;
}
|
f0d7f1fa007e9347544322a3ff6c3d2d
|
{
"intermediate": 0.34108686447143555,
"beginner": 0.4821556806564331,
"expert": 0.17675743997097015
}
|
1,108
|
有一个类结构如下,现在用C# newtonsoft.json把一个json转为该对象
public class Menu
{
public int id { get; set; }
public string createTime { get; set; }
public string updateTime { get; set; }
public object parentId { get; set; }
public string name { get; set; }
public string router { get; set; }
public int type { get; set; }
public string icon { get; set; }
public int orderNum { get; set; }
public string viewPath { get; set; }
public int keepAlive { get; set; }
public int isShow { get; set; }
public int createType { get; set; }
public string firmId { get; set; }
public object perms { get; set; }
}
|
8e69f040556335101d1a39d32d5d5949
|
{
"intermediate": 0.3622492551803589,
"beginner": 0.46040135622024536,
"expert": 0.17734943330287933
}
|
1,109
|
In python, make a machine learning model to predict a 5x5 minesweeper game. You can’t make it random or make it predict 2 same results in a row if a new game is started. You have data for the past 30 games [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9] and you need to predict 5 safe spots 3 possible bomb locations that amount is the giving mines amount.the total lenght of the list is 90. You also need to make it say the accuracy in % and make sure it wont get the same results everytime
|
bde859e151658abe021fdaa658e033eb
|
{
"intermediate": 0.14971747994422913,
"beginner": 0.07476743310689926,
"expert": 0.775515079498291
}
|
1,110
|
write a javascript code that will return all the js paths of user interactive elements from a webpage
|
3a0cdd1b2fe4ba7d9e5131b1ab5e9a1a
|
{
"intermediate": 0.4872904419898987,
"beginner": 0.2188446968793869,
"expert": 0.2938648462295532
}
|
1,111
|
I want you to write a trading bot for a crypto exchange. I will give you the strategy and you will transform it into the code. Can you do this?
|
2b86823754baeeed8166d756c569de0c
|
{
"intermediate": 0.2449059635400772,
"beginner": 0.21780917048454285,
"expert": 0.537284791469574
}
|
1,112
|
tracking face,hands and shoulder shrugging through out the video
|
82fbbae715849192764fea6943a33031
|
{
"intermediate": 0.326013445854187,
"beginner": 0.29102474451065063,
"expert": 0.38296183943748474
}
|
1,113
|
Create a C program where it does the following: Expect three points from stdin, one per line.
Verify each point is EXACTLY "(fx, fy)" (where fx and fy are floating point numbers)
Output the area of the triangle defined by those, to two places.
|
8e136658eef38c2e7c62d2ef65603c3f
|
{
"intermediate": 0.434052973985672,
"beginner": 0.2773147225379944,
"expert": 0.2886323630809784
}
|
1,114
|
I am trying to use a textview to display the latest data from the database
textresult.java
package com.example.profile;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class textresult extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("predict");
Query query = myRef.orderByChild("timestamp").limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d("FirebaseDebug", "onDataChange: Data received"); // Add this line
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
// Get the "soreness_label", "gsr_data" and "emg_data" from the latest entry
String latestSorenessLabel = snapshot.child("soreness_label").getValue(String.class);
// Combine values to be displayed
String combinedValues = "Soreness Label: " + latestSorenessLabel ;
// Display combined values in the TextView
TextView textViewData = findViewById(R.id.textViewData);
textViewData.setText(combinedValues);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("FirebaseDebug", "onCancelled: Error encountered"); // Add this line
Log.w("Error", "Failed to read value.", databaseError.toException());
}
});
}
}
activity_main.java
<?xml version='1.0' encoding='utf-8'?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android='http://schemas.android.com/apk/res/android'
xmlns:app='http://schemas.android.com/apk/res-auto'
xmlns:tools='http://schemas.android.com/tools'
android:layout_width='match_parent'
android:layout_height='match_parent'
android:id='@+id/drawer'
tools:context='.MainActivity'>
<LinearLayout
android:layout_width='match_parent'
android:layout_height='match_parent'
android:background='@drawable/bg'
android:orientation='vertical'>
<include
layout='@layout/main_toolbar'
/>
<TextView
android:layout_width='match_parent'
android:layout_height='match_parent'
android:text=''
android:textSize='52sp'
android:textStyle='bold'
android:textColor='@color/black'
android:gravity='center'
android:id='@+id/textViewData'
/>
</LinearLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_gravity="start">
<include
layout = "@layout/main_navigation_drawer"
/>
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
|
2d80baa6c523afb1a7ccced939dcefa3
|
{
"intermediate": 0.38961705565452576,
"beginner": 0.37159377336502075,
"expert": 0.23878921568393707
}
|
1,115
|
en python:10 KEY OFF
20 CLS
30 PRINT " ######################################"
40 PRINT " # #"
50 PRINT " # Probit analysis program #"
60 PRINT " # #"
70 PRINT " ######################################"
80 PRINT " Michel Raymond, Laboratoire de Gntique"
90 PRINT " Institut des Sciences de L'Evolution"
100 PRINT " U.S.T.L. Place E. Bataillon"
110 PRINT " 34060 Montpellier Cedex"
120 PRINT " France"
130 PRINT " ----------------------------------------------"
140 PRINT "References:": PRINT : PRINT "Finney, D.J., 1971. Probit analysis, Cambridge University Press, 3rd Edition."
150 PRINT "Finney, D.J., 1949. Ann., Appl., Biol., 36, 187-195."
160 PRINT : PRINT : PRINT "Feel free to contact me for any information or advice. This program is described in a publication: RAYMOND M., 1985. Prsentation d'un programme"
170 PRINT " d'analyse log-probit pour micro-ordinnateur."
180 PRINT " Cah. ORSTOM, Sr. Ent. med et Parasitol.,"
190 PRINT " vol 22(2), 117-121."
200 PRINT "(Copyright April 1993 version)"
|
fa69474ebd1de90d977272ab39d211ce
|
{
"intermediate": 0.20770958065986633,
"beginner": 0.4401218295097351,
"expert": 0.35216856002807617
}
|
1,116
|
persistentMarkers: Map<Float, Marker>? = null,
please give an example on how to create a persistent marker
|
e6037264caa4ed12cb449ce8fb1a9830
|
{
"intermediate": 0.4373495876789093,
"beginner": 0.15803484618663788,
"expert": 0.4046155512332916
}
|
1,117
|
добавить в код построения гистограмм изображений (исходных и преобразованных).
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
openImage();
} else if (e.getSource() == processButton) {
processImage();
} else if (e.getSource() == brightnessButton) {
brightnessImage();
}
else if (e.getSource() == contrastButton) {
contrastImage();
}
else if (e.getSource() == sawtoothButton) {
sawtoottImage();
}
else if (e.getSource() == gaussButton) {
gaussImage();
}
else if (e.getSource() == cannyButton) {
cannyImage();
}
else if (e.getSource() == histogramButton) {
histogramImage();
}
}
|
1ca2a04db2b9216a680de5f7336df70d
|
{
"intermediate": 0.4218127131462097,
"beginner": 0.3409804105758667,
"expert": 0.23720687627792358
}
|
1,118
|
convert this to var: let monthlyInsurance = 0;
|
47798d703e2223d439608d1dc6459f0d
|
{
"intermediate": 0.2023191750049591,
"beginner": 0.6382609605789185,
"expert": 0.15941983461380005
}
|
1,119
|
I have an excel sheet
|
82ba5588865f3dc34c33874fc48a3f32
|
{
"intermediate": 0.2836819887161255,
"beginner": 0.30706000328063965,
"expert": 0.40925803780555725
}
|
1,120
|
where from download haarcascade_shoulder.xml
|
d1c4e9cad95f09307f02e04c3da06b51
|
{
"intermediate": 0.39911481738090515,
"beginner": 0.23114852607250214,
"expert": 0.3697367012500763
}
|
1,121
|
почему не строится гистограмма преобразованного изображения. public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
openImage();
} else if (e.getSource() == processButton) {
processImage();
} else if (e.getSource() == brightnessButton) {
brightnessImage();
}
else if (e.getSource() == contrastButton) {
contrastImage();
}
else if (e.getSource() == sawtoothButton) {
sawtoottImage();
}
else if (e.getSource() == gaussButton) {
gaussImage();
}
else if (e.getSource() == cannyButton) {
cannyImage();
}
else if (e.getSource() == histogramButton) {
histogramImage();
}
}
private void histogramImage() {
// Создаем гистограмму исходного изображения
int[] histogram = new int[256];
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int pixel = image.getRGB(i, j);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = pixel & 0xff;
// Вычисляем яркость пикселя
int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue);
histogram[brightness]++;
}
}
// Создаем гистограмму преобразованного изображения
int[] transformedHistogram = new int[256];
BufferedImage transformedImage = null;
if (image != null) {
transformedImage = copyImage(image);
// Ваш код преобразования изображения должен быть здесь
int[][] imageMatrix = convertToMatrix(transformedImage);
//максимальная и минимальная яркости
int maxValue = getMaxValue(imageMatrix);
int minValue = getMinValue(imageMatrix);
//разница между максимальной и минимальной яркостями
float range = (float)(maxValue - minValue);
for (int i = 0; i < transformedImage.getWidth(); i++) {
for (int j = 0; j < transformedImage.getHeight(); j++) {
int pixel = image.getRGB(i, j);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = pixel & 0xff;
// Вычисляем яркость пикселя
int brightness = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue);
// Вычисляем преобразованную яркость пикселя
float newBrightness = ((brightness - minValue) / range) * 255.0f;
transformedImage.setRGB(i, j, new Color((int)newBrightness, (int)newBrightness, (int)newBrightness).getRGB());
transformedHistogram[(int)newBrightness]++;
}
}
}
// Создаем окно для отображения гистограмм
JFrame histogramFrame = new JFrame("Гистограмма");
histogramFrame.setLayout(new GridLayout(1, 2, 5, 5));
// Создаем панель для первой гистограммы (исходного изображения)
JPanel histogramPanel1 = new JPanel();
histogramPanel1.setLayout(new BorderLayout());
histogramPanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Исходное изображение"));
// Создаем компонент для рисования гистограммы исходного изображения
JPanel histogramComponent1 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int max = Arrays.stream(histogram).max().getAsInt();
for (int i = 0; i < 256; i++) {
int height = (int) (300.0 * histogram[i] / max);
g.fillRect(i, 300 - height, 1, height);
}
}
};
histogramComponent1.setPreferredSize(new Dimension(256, 300));
histogramPanel1.add(histogramComponent1, BorderLayout.CENTER);
// Создаем панель для второй гистограммы (преобразованного изображения)
JPanel histogramPanel2 = new JPanel();
histogramPanel2.setLayout(new BorderLayout());
histogramPanel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Преобразованное изображение"));
// Создаем компонент для рисования гистограммы преобразованного изображения
JPanel histogramComponent2 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int max = Arrays.stream(transformedHistogram).max().getAsInt();
for (int i = 0; i < 256; i++) {
int height = (int) (300.0 * transformedHistogram[i] / max);
g.fillRect(i, 300 - height, 1, height);
}
}
};
histogramComponent2.setPreferredSize(new Dimension(256, 300));
histogramPanel2.add(histogramComponent2, BorderLayout.CENTER);
histogramFrame.add(histogramPanel1);
histogramFrame.add(histogramPanel2);
histogramFrame.pack();
histogramFrame.setLocationRelativeTo(null);
histogramFrame.setVisible(true);
}
private BufferedImage copyImage(BufferedImage image) {
ColorModel cm = image.getColorModel();
WritableRaster raster = image.copyData(null);
return new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);
}
private int[][] convertToMatrix(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] matrix = new int[height][width];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
matrix[j][i] = image.getRGB(i, j);
}
}
return matrix;
}
private int getMaxValue(int[][] matrix) {
int maxValue = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > maxValue) {
maxValue = matrix[i][j];
}
}
}
return maxValue;
}
private int getMinValue(int[][] matrix) {
int minValue = Integer.MAX_VALUE;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < minValue) {
minValue = matrix[i][j];
}
}
}
return minValue;
}
private void openImage() {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
image = ImageIO.read(file);
setImageIcon(image); // set the opened image to the imageLabel
imageWidth = new BigDecimal(image.getWidth()); // set the width of the image
imageHeight = new BigDecimal(image.getHeight()); // set the height of the image
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error opening image", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
|
d03680b64db41b7fe4a7766201d0a346
|
{
"intermediate": 0.21162033081054688,
"beginner": 0.5383402705192566,
"expert": 0.2500394880771637
}
|
1,122
|
replace let with var "use strict";
var readlineSync = require('readline-sync');
/*
Author: Liam Butler
Date: 3/6/23
Title: PROG1700 Assignment 3- Q1 Timesheet
*/
// DO NOT EDIT: The main function to house our program code
function main()
{
//input, allows the user to input the days they have worked
let hours = [];
for (let i = 0; i < 5; i++) {
hours[i] = readlineSync.question(`Enter the number of hours worked on day ${i + 1}: `);
}
//sorts the work days based on how many hours worked (5 and under being useless, 7-6 being slacked off)
let totalHours = 0;
for (let i = 0; i < 5; i++) {
totalHours += parseFloat(hours[i]);
}
//calculating the average amount of hours worked
let averageHours = totalHours / 5;
//figures out days that were slacking off on days (7 hours or less)
let slackedoff = [];
for (let i = 0; i < 5; i++) {
if (parseFloat(hours[i]) < 7) {
slackedoff.push(`day ${i + 1}`);
}
}
//calculates the days that were useless (4 hours or less worked)
let uselessdays = 0;
for (let i = 0; i < 5; i++) {
if (parseFloat(hours[i]) < 4) {
uselessdays++;
}
}
//puts out the results
console.log("-----------RESULTS-----------")
console.log(`you've worked: ${totalHours}` + " total hours");
console.log(`average hours worked: ${averageHours.toFixed(2)}`);
console.log(`days with less then 7 hours worked: ${slackedoff}`);
console.log(`useless days with less then 4 hours worked: ${uselessdays}`);
}
// Trigger our main function to launch the program
if (require.main === module)
{
main();
}
// DO NOT EDIT: Trigger our main function to launch the program
if (require.main === module)
{
main();
}
|
830695d2fd5feb477c151640b54c3d55
|
{
"intermediate": 0.35627281665802,
"beginner": 0.3474205434322357,
"expert": 0.2963065803050995
}
|
1,123
|
you need to predict a minesweper game. a 5x5 field. You've data for the past 3 games, but the data changes. The user inputs the amount of mines and the amount of spots he wants
predicted. If the user inputs 3 mines and 5 safe spots, you have to predict 5 safe spots, but the predictions cannot be the same as last game, IF, the data is unchanged.
Another thing, you also need to predict the possible mine locations. The amount of mines you need to predict, is the amount the user inputs. So if 3 mines, you predict 3 possible locations.
Data. The dats you got is from the last 30 games, but it depends. If the user inputs 3 mines, you of course have to predict for a 3 mines game, but the data will be 30x3. If the user inputs 2 mines, the data is 2x30 = all mine locations from the past games. The data I'm gonna give you is for 30 past games played. The data will automatic be updated and you don't have to worry about it.
The data (3 mine game, 30 past games): [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9]
Each number presents a mine location on the 5x5 board.
method. You need to use machine learning to predict the game, and it can be anything, expect Deep Learning. No deep learning. Make it really accuracy, as much as possible.
Accuracy. The model needs an accuracy of at least 70%, and also needs to spit out the accuracy in %
Good luck.
|
3235e8c89528c7cf2e1809a218bbf04e
|
{
"intermediate": 0.2201409637928009,
"beginner": 0.14790937304496765,
"expert": 0.6319496631622314
}
|
1,124
|
fix the code
package com.example.profile;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("predict");
Query query = myRef.orderByChild("timestamp").limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d("FirebaseDebug", "onDataChange: Data received"); // Add this line
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
// Get the "soreness_label", "gsr_data" and "emg_data" from the latest entry
String latestSorenessLabel = snapshot.child("soreness_label").getValue(String.class);
Integer latestGsrData = snapshot.child("gsr_data").getValue(Integer.class);
Integer latestEmgData = snapshot.child("emg_data").getValue(Integer.class);
// Combine values to be displayed
String combinedValues = "Soreness Label: " + latestSorenessLabel +
"\nGSR Data: " + latestGsrData +
"\nEMG Data: " + latestEmgData;
// Display combined values in the TextView
TextView textViewData = findViewById(R.id.textViewData);
textViewData.setText(combinedValues);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("FirebaseDebug", "onCancelled: Error encountered"); // Add this line
Log.w("Error", "Failed to read value.", databaseError.toException());
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout=findViewById(R.id.drawer);
}
public void ClickMenu(View view){
openDrawer(drawerLayout);
}
static void openDrawer(DrawerLayout drawerLayout) {
drawerLayout.openDrawer(GravityCompat.START);
}
public void ClickLogo(View view){
closeDrawer(drawerLayout);
}
public static void closeDrawer(DrawerLayout drawerLayout) {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
public void ClickHome(View view){
recreate();
}
public void ClickProfile(View view){
redirectActivity(this,Profile.class);
}
public void ClickResult(View view){
redirectActivity(this,Result.class);
}
public void ClickAction(View view){
redirectActivity(this,Action.class);
}
public void ClickLogout(View view){
logout(this);
}
static void logout(Activity activity) {
AlertDialog.Builder builder=new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure you want to logout?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.show();
}
public static void redirectActivity(Activity activity, Class Class) {
Intent intent=new Intent(activity,Class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
@Override
protected void onPause() {
super.onPause();
closeDrawer(drawerLayout);
}
}
Activity_main.xml for context
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">
<include
layout = "@layout/main_toolbar"
/>
<TextView
android:layout_width='match_parent'
android:layout_height='match_parent'
android:text=''
android:textSize='52sp'
android:textStyle='bold'
android:textColor='@color/black'
android:gravity='center'
android:id='@+id/textViewData'
/>
</LinearLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_gravity="start">
<include
layout = "@layout/main_navigation_drawer"
/>
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
|
b6a9c4de3d1c3be44348b92a2501b7a2
|
{
"intermediate": 0.32118138670921326,
"beginner": 0.3539513945579529,
"expert": 0.32486721873283386
}
|
1,125
|
fs.writeFile(outputFile, modifiedText, function(err) {
^
ReferenceError: modifiedText is not defined
at main (C:\Users\Liam Butler\Documents\PROG1700\prog-1700--assignment-4-liamb0469148\q1.js:53:27)
at Object.<anonymous> (C:\Users\Liam Butler\Documents\PROG1700\prog-1700--assignment-4-liamb0469148\q1.js:64:5)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
|
9497e4821fd83134dd6b0ff5da3a60f3
|
{
"intermediate": 0.3185476064682007,
"beginner": 0.4680107533931732,
"expert": 0.2134416252374649
}
|
1,126
|
Задание: Дописать код C++ (ВАЖНО пиши код используя markdown cpp
|
5bea33540204a18eab3c3378b5ba68eb
|
{
"intermediate": 0.3292464017868042,
"beginner": 0.4144262969493866,
"expert": 0.2563273310661316
}
|
1,127
|
import os
input_path = input("请输入需要拆分的合并后图片的路径:") # 输入合并后图片的路径
output_dir = input("请输入拆分后图片序列的保存路径:") # 输出拆分后图片序列的文件夹路径
grid_size = input("请输入拆分网格的行数和列数,用'x'连接:") # 用户输入拆分网格的行数和列数,比如 2x2、3x3
row_num, column_num = map(int, grid_size.strip().split('x'))
index = 0
# 创建输出文件夹
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 遍历输入路径下所有图片文件,执行图片拆分操作
for file in os.listdir(input_path):
if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg"):
img_path = os.path.join(input_path, file)
# 获取输入图片的宽和高
iw, ih, _ = os.popen('ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 {}'.format(img_path)).read().split('x')
iw, ih = int(iw.strip()), int(ih.strip())
# 使用ffmpeg命令行工具进行图片拆分
for y in range(row_num):
for x in range(column_num):
# 构建输出文件路径
index += 1
output_path = os.path.join(output_dir, f"{str(index).zfill(3)}.jpeg")
# 拆分图片
crop_w = iw / column_num
crop_h = ih / row_num
os.system('ffmpeg -i {} -vf "crop={}:{}:{}:{}" {}'.format(img_path, crop_w, crop_h, crop_w * x, crop_h * y, output_path))
# 输出拆分后的图片序列路径
print("图片 {} 拆分后的图片序列路径为:{}".format(file, output_path)) 错误信息:C:\Users\96394\Videos\test>python split.py
请输入需要拆分的合并后图片的路径:./16/merged
请输入拆分后图片序列的保存路径:./16/split
请输入拆分网格的行数和列数,用'x'连接:3x3
Traceback (most recent call last):
File "C:\Users\96394\Videos\test\split.py", line 82, in <module>
iw, ih, _ = os.popen('ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 {}'.format(img_path)).read().split('x')
ValueError: not enough values to unpack (expected 3, got 2)
|
5d34443565113eb8924a545a1a316ce5
|
{
"intermediate": 0.28548291325569153,
"beginner": 0.43017178773880005,
"expert": 0.2843453586101532
}
|
1,128
|
in python I have a string with this format and I want to extract the number and assign it to the other variable, like this:
xp_skill_key = "f3"
xp_f_key = 3 # number extracted
How can I do this?
|
b0b6d081fb5287d86fe7b3426793d03e
|
{
"intermediate": 0.4036824107170105,
"beginner": 0.298383504152298,
"expert": 0.29793408513069153
}
|
1,129
|
PS C:\Users\Liam Butler\Documents\PROG1700\prog-1700--assignment-4-liamb0469148> node q2
node:internal/fs/utils:673
throw new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL'], path);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
at Object.openSync (node:fs:586:10)
at Object.readFileSync (node:fs:462:35)
at main (C:\Users\Liam Butler\Documents\PROG1700\prog-1700--assignment-4-liamb0469148\q2.js:12:23)
at Object.<anonymous> (C:\Users\Liam Butler\Documents\PROG1700\prog-1700--assignment-4-liamb0469148\q2.js:58:5)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
|
8cd0ffdaee97d6e41138012c17703804
|
{
"intermediate": 0.48928335309028625,
"beginner": 0.3642755448818207,
"expert": 0.14644113183021545
}
|
1,130
|
Добавь setImageIcon(transformedImage); в этот код.
private void histogramImage() {
// Создаем гистограмму исходного изображения
int[] histogram = new int[256];
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int pixel = image.getRGB(i, j);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = pixel & 0xff;
// Вычисляем яркость пикселя
int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue);
histogram[brightness]++;
}
}
// Создаем гистограмму преобразованного изображения
int[] transformedHistogram = new int[256];
BufferedImage transformedImage = null;
if (image != null) {
transformedImage = copyImage(image);
// Ваш код преобразования изображения должен быть здесь
int[][] imageMatrix = convertToMatrix(transformedImage);
//максимальная и минимальная яркости
int maxValue = getMaxValue(imageMatrix);
int minValue = getMinValue(imageMatrix);
//разница между максимальной и минимальной яркостями
float range = (float)(maxValue - minValue);
for (int i = 0; i < transformedImage.getWidth(); i++) {
for (int j = 0; j < transformedImage.getHeight(); j++) {
int pixel = image.getRGB(i, j);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = pixel & 0xff;
// Вычисляем яркость пикселя
int brightness = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue);
// Вычисляем преобразованную яркость пикселя
float newBrightness = ((brightness - minValue) / range) * 255.0f;
transformedImage.setRGB(i, j, new Color((int)newBrightness, (int)newBrightness, (int)newBrightness).getRGB());
transformedHistogram[(int)newBrightness]++;
}
}
}
// Создаем окно для отображения гистограмм
JFrame histogramFrame = new JFrame("Гистограмма");
histogramFrame.setLayout(new GridLayout(1, 2, 5, 5));
// Создаем панель для первой гистограммы (исходного изображения)
JPanel histogramPanel1 = new JPanel();
histogramPanel1.setLayout(new BorderLayout());
histogramPanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Исходное изображение"));
// Создаем компонент для рисования гистограммы исходного изображения
JPanel histogramComponent1 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int max = Arrays.stream(histogram).max().getAsInt();
for (int i = 0; i < 256; i++) {
int height = (int) (300.0 * histogram[i] / max);
g.fillRect(i, 300 - height, 1, height);
}
}
};
histogramComponent1.setPreferredSize(new Dimension(256, 300));
histogramPanel1.add(histogramComponent1, BorderLayout.CENTER);
// Создаем панель для второй гистограммы (преобразованного изображения)
JPanel histogramPanel2 = new JPanel();
histogramPanel2.setLayout(new BorderLayout());
histogramPanel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Преобразованное изображение"));
// Создаем компонент для рисования гистограммы преобразованного изображения
JPanel histogramComponent2 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int max = Arrays.stream(transformedHistogram).max().getAsInt();
for (int i = 0; i < 256; i++) {
int height = (int) (300.0 * transformedHistogram[i] / max);
g.fillRect(i, 300 - height, 1, height);
}
}
};
histogramComponent2.setPreferredSize(new Dimension(256, 300));
histogramPanel2.add(histogramComponent2, BorderLayout.CENTER);
histogramFrame.add(histogramPanel1);
histogramFrame.add(histogramPanel2);
histogramFrame.pack();
histogramFrame.setLocationRelativeTo(null);
histogramFrame.setVisible(true);
}
private BufferedImage copyImage(BufferedImage image) {
ColorModel cm = image.getColorModel();
WritableRaster raster = image.copyData(null);
return new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);
}
private int[][] convertToMatrix(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] matrix = new int[height][width];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
matrix[j][i] = image.getRGB(i, j);
}
}
return matrix;
}
private int getMaxValue(int[][] matrix) {
int maxValue = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > maxValue) {
maxValue = matrix[i][j];
}
}
}
return maxValue;
}
private int getMinValue(int[][] matrix) {
int minValue = Integer.MAX_VALUE;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < minValue) {
minValue = matrix[i][j];
}
}
}
return minValue;
}
|
0e244a6594169986d43fb984f497ec76
|
{
"intermediate": 0.2925761938095093,
"beginner": 0.4736320674419403,
"expert": 0.2337917536497116
}
|
1,131
|
Write a python implementation of insertion sort with example array.
|
65852634a740a459ce26741a5361653d
|
{
"intermediate": 0.4859830141067505,
"beginner": 0.090789794921875,
"expert": 0.4232272505760193
}
|
1,132
|
I want to Dial a code like (*858*45212323654#) on my android phone with C#.
|
5d5202cd71182cecf4620edc89c743c6
|
{
"intermediate": 0.4177435338497162,
"beginner": 0.336880087852478,
"expert": 0.2453763633966446
}
|
1,133
|
Assignment:
Create a website for the Retail Camping Company (RCC), a camping equipment retailer moving to online sales.
Requirements:
1. HTML (25 Marks)
- Develop a website using HTML 5 with at least SIX (6) interlinked pages.
- Content should include images of camping equipment, minimal text with visuals, and use of headers, sections, footers.
- Make the website usable on at least TWO (2) different web browsers, optimized for mobile devices and responsive design.
- Home Page: features navigation bar, responsive design, at least one plugin, sections, and footer with social media links.
- Reviews Page: responsive contact section including first name, last name, and submit button (through email).
- Camping Equipment, Furniture Page, and Offers and Package Page: responsive resize design, TWO (2) different plugins, catalogue style and animated text search for products.
- Basket Page: allows customers to add products to their basket.
2. CSS (25 Marks)
- Create an external CSS file that each of the HTML pages link to.
- Home Page: include relevant elements like border radius, box-shadow, hover, etc.
- Implement an animated text search for customers to seek different products.
3. Testing and Evaluation (15 Marks)
- Test the website using W3C validation service for HTML and CSS code.
- Test the website for accessibility using a screen reader and consider disabled users.
- Test the website on TWO (2) different browsers, describe differences between the browsers and their reasons.
- Write a report assessing the suitability of testing (max 500 words), evaluate any outstanding problems, provide recommendations for fixing issues, and explain the role of the W3C.
|
0cf484ecfea4ee71139aed35777525e1
|
{
"intermediate": 0.2922143042087555,
"beginner": 0.4275197386741638,
"expert": 0.2802659571170807
}
|
1,134
|
Hello. I have a numpy array in python. This array has values from 0 to 35 in integer representing tiles of a map. I also have a tile map. What I need is to make a solution so I can convert integer array to an image with tiles from tile map and be able to show it in .ipynb file.
|
c235d12d50e5bd813624f9353a6ad4a3
|
{
"intermediate": 0.5909736752510071,
"beginner": 0.13513199985027313,
"expert": 0.2738943099975586
}
|
1,135
|
I want to remove the EditText
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("predict");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
// Load data based on the current EditText input
handleEditTextInput();
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
handleEditTextInput();
}
};
// Create a new method to handle EditText input
private void handleEditTextInput() {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef;
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Node Name", idSnapshot.getKey())); // Add this line
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged(); // Add this line
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
public void ClickMenu(View view) {
MainActivity.openDrawer(drawerLayout);
}
public void ClickLogo(View view) {
MainActivity.closeDrawer(drawerLayout);
}
public void ClickHome(View view) {
MainActivity.redirectActivity(this, MainActivity.class);
}
public void ClickProfile(View view) {
MainActivity.redirectActivity(this, Profile.class);
}
public void ClickResult(View view) {
recreate();
}
public void ClickAction(View view) {
MainActivity.redirectActivity(this, Action.class);
}
public void ClickLogout(View view) {
MainActivity.logout(this);
}
@Override
protected void onPause() {
super.onPause();
MainActivity.closeDrawer(drawerLayout);
}
}
UserItem.java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, Object data) {
this.name = name;
this.data = data.toString(); // Just convert the object directly to a string
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public int emg_data; // Changed to Object
public int gsr_data; // Changed to Object
public String timestamp;
public UserData() {
}
}
RecyclerViewAdapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg">
<include
android:id="@+id/include"
layout="@layout/main_toolbar" />
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
android:textColorHint="@color/black"
app:layout_constraintTop_toBottomOf="@+id/include"
tools:layout_editor_absoluteX="8dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text"
app:layout_constraintVertical_bias="0.0"
tools:layout_editor_absoluteX="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
|
276448e44a29566c14bda4976bbc3a80
|
{
"intermediate": 0.30750343203544617,
"beginner": 0.44310319423675537,
"expert": 0.24939341843128204
}
|
1,136
|
is there is a way to dial a code on an Android device from a C# Windows application that doesn’t require ADB?
|
a3bcb68083b6586ad53d5bfc43ff3123
|
{
"intermediate": 0.6937079429626465,
"beginner": 0.1302439123392105,
"expert": 0.1760481297969818
}
|
1,137
|
"use strict";
/*
Author: Liam Butler
Assignment #: 4
Description: Q3 (BONUS): Battleship
*/
var fs = require("fs");
var gamemap = [];
var targetmap = [];
var missles = 30;
var hitCount = 0;
var shipssunk = [false, false, false, false, false];
function main() // <-- Don't change this line!
{
//load the map.txt file
function loadShipMap(targetmap) {
var targetmap = fs.readFileSync(targetmap, "utf8");
//split them into rows
var rows = targetmap.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = rows[i].split(",");
gamemap.push(row);
}
}
}
//initiate the targeting map
function initTargetingMap() {
for (var i = 0; i < 10; i++) {
var row = [];
for (var j = 0; j < 10; j++) {
row.push(" ");
}
targetmap.push(row);
}
}
//updates the map with the amount of missles
function updateTargetingMap(row, col, hit) {
if (hit) {
targetmap[row][col] = "X";
} else {
targetmap[row][col] = "-";
}
}
//makes sure the coords you hit are valid
function isValidCoordinates(row, col) {
if (row < 0 || row >= 10 || col < 0 || col >= 10) {
return false;
}
return true;
}
//checks to see if theres a ship in the square you hit
function checkShipSunk(row, col) {
if (gamemap[row][col] === 1) {
gamemap[row][col] = "X"; //mark the ship as hit on the map
for (var r = 0; r < gamemap.length; r++) {
for (var c = 0; c < gamemap[r].length; c++) {
if (gamemap[r][c] === 1) {
return false; //at least one ship cell is still not hit, so the ship is not sunk yet
}
}
}
return true; //all ship cells are hit, so the ship sank
}
return false; //there is no ship at the given location
}
//checks to see if a square has been hit already
function checkSquareHit(row, col) {
if (targetmap[row][col] === "X") {
return true;
}
return false;
}
loadShipMap(gamemap);
initTargetingMap();
//game loop
while (missles > 0) {
console.log("your missiles remaining are " + missles);
console.log("current game board:\n");
console.log(gamemap);
console.log(targetmap);
//input for playing
var row = parseInt(prompt("row to attack (0-9):"));
var col = parseInt(prompt("column to attack (0-9):"));
//tells you when you sunk a ship
if (isValidCoordinates(row, col)) {
if (checkShipSunk(row, col)) {
console.log("You sunk a ship!");
hitCount++;
//if you sink 17 ships, you win
if (hitCount == 17) {
console.log("Congratulations, you've sunk all the ships and won the game!");
return;
}
}
}
}
// Do not change any of the code below!
if (require.main === module)
{
main();
}
"use strict";
/*
Author: Liam Butler
Assignment #: 4
Description: Q3 (BONUS): Battleship
*/
var fs = require("fs");
var gamemap = [];
var targetmap = [];
var missles = 30;
var hitCount = 0;
var shipssunk = [false, false, false, false, false];
function main() // <-- Don't change this line!
{
//load the map.txt file
function loadShipMap(targetmap) {
var targetmap = fs.readFileSync(targetmap, "utf8");
//split them into rows
var rows = targetmap.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = rows[i].split(",");
gamemap.push(row);
}
}
}
//initiate the targeting map
function initTargetingMap() {
for (var i = 0; i < 10; i++) {
var row = [];
for (var j = 0; j < 10; j++) {
row.push(" ");
}
targetmap.push(row);
}
}
//updates the map with the amount of missles
function updateTargetingMap(row, col, hit) {
if (hit) {
targetmap[row][col] = "X";
} else {
targetmap[row][col] = "-";
}
}
//makes sure the coords you hit are valid
function isValidCoordinates(row, col) {
if (row < 0 || row >= 10 || col < 0 || col >= 10) {
return false;
}
return true;
}
//checks to see if theres a ship in the square you hit
function checkShipSunk(row, col) {
if (gamemap[row][col] === 1) {
gamemap[row][col] = "X"; //mark the ship as hit on the map
for (var r = 0; r < gamemap.length; r++) {
for (var c = 0; c < gamemap[r].length; c++) {
if (gamemap[r][c] === 1) {
return false; //at least one ship cell is still not hit, so the ship is not sunk yet
}
}
}
return true; //all ship cells are hit, so the ship sank
}
return false; //there is no ship at the given location
}
//checks to see if a square has been hit already
function checkSquareHit(row, col) {
if (targetmap[row][col] === "X") {
return true;
}
return false;
}
loadShipMap(gamemap);
initTargetingMap();
//game loop
while (missles > 0) {
console.log("your missiles remaining are " + missles);
console.log("current game board:\n");
console.log(gamemap);
console.log(targetmap);
//input for playing
var row = parseInt(prompt("row to attack (0-9):"));
var col = parseInt(prompt("column to attack (0-9):"));
//tells you when you sunk a ship
if (isValidCoordinates(row, col)) {
if (checkShipSunk(row, col)) {
console.log("You sunk a ship!");
hitCount++;
//if you sink 17 ships, you win
if (hitCount == 17) {
console.log("Congratulations, you've sunk all the ships and won the game!");
return;
}
}
}
}
// Do not change any of the code below!
if (require.main === module)
{
main();
}
"use strict";
/*
Author: Liam Butler
Assignment #: 4
Description: Q3 (BONUS): Battleship
*/
var fs = require("fs");
var gamemap = [];
var targetmap = [];
var missles = 30;
var hitCount = 0;
var shipssunk = [false, false, false, false, false];
function main() // <-- Don't change this line!
{
//load the map.txt file
function loadShipMap(targetmap) {
var targetmap = fs.readFileSync(targetmap, "utf8");
//split them into rows
var rows = targetmap.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = rows[i].split(",");
gamemap.push(row);
}
}
}
//initiate the targeting map
function initTargetingMap() {
for (var i = 0; i < 10; i++) {
var row = [];
for (var j = 0; j < 10; j++) {
row.push(" ");
}
targetmap.push(row);
}
}
//updates the map with the amount of missles
function updateTargetingMap(row, col, hit) {
if (hit) {
targetmap[row][col] = "X";
} else {
targetmap[row][col] = "-";
}
}
//makes sure the coords you hit are valid
function isValidCoordinates(row, col) {
if (row < 0 || row >= 10 || col < 0 || col >= 10) {
return false;
}
return true;
}
//checks to see if theres a ship in the square you hit
function checkShipSunk(row, col) {
if (gamemap[row][col] === 1) {
gamemap[row][col] = "X"; //mark the ship as hit on the map
for (var r = 0; r < gamemap.length; r++) {
for (var c = 0; c < gamemap[r].length; c++) {
if (gamemap[r][c] === 1) {
return false; //at least one ship cell is still not hit, so the ship is not sunk yet
}
}
}
return true; //all ship cells are hit, so the ship sank
}
return false; //there is no ship at the given location
}
//checks to see if a square has been hit already
function checkSquareHit(row, col) {
if (targetmap[row][col] === "X") {
return true;
}
return false;
}
loadShipMap(gamemap);
initTargetingMap();
//game loop
while (missles > 0) {
console.log("your missiles remaining are " + missles);
console.log("current game board:\n");
console.log(gamemap);
console.log(targetmap);
//input for playing
var row = parseInt(prompt("row to attack (0-9):"));
var col = parseInt(prompt("column to attack (0-9):"));
//tells you when you sunk a ship
if (isValidCoordinates(row, col)) {
if (checkShipSunk(row, col)) {
console.log("You sunk a ship!");
hitCount++;
//if you sink 17 ships, you win
if (hitCount == 17) {
console.log("Congratulations, you've sunk all the ships and won the game!");
return;
}
}
}
}
// Do not change any of the code below!
if (require.main === module)
{
main();
}
"use strict";
/*
Author: Liam Butler
Assignment #: 4
Description: Q3 (BONUS): Battleship
*/
var fs = require("fs");
var gamemap = [];
var targetmap = [];
var missles = 30;
var hitCount = 0;
var shipssunk = [false, false, false, false, false];
function main() // <-- Don't change this line!
{
//load the map.txt file
function loadShipMap(targetmap) {
var targetmap = fs.readFileSync(targetmap, "utf8");
//split them into rows
var rows = targetmap.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = rows[i].split(",");
gamemap.push(row);
}
}
}
//initiate the targeting map
function initTargetingMap() {
for (var i = 0; i < 10; i++) {
var row = [];
for (var j = 0; j < 10; j++) {
row.push(" ");
}
targetmap.push(row);
}
}
//updates the map with the amount of missles
function updateTargetingMap(row, col, hit) {
if (hit) {
targetmap[row][col] = "X";
} else {
targetmap[row][col] = "-";
}
}
//makes sure the coords you hit are valid
function isValidCoordinates(row, col) {
if (row < 0 || row >= 10 || col < 0 || col >= 10) {
return false;
}
return true;
}
//checks to see if theres a ship in the square you hit
function checkShipSunk(row, col) {
if (gamemap[row][col] === 1) {
gamemap[row][col] = "X"; //mark the ship as hit on the map
for (var r = 0; r < gamemap.length; r++) {
for (var c = 0; c < gamemap[r].length; c++) {
if (gamemap[r][c] === 1) {
return false; //at least one ship cell is still not hit, so the ship is not sunk yet
}
}
}
return true; //all ship cells are hit, so the ship sank
}
return false; //there is no ship at the given location
}
//checks to see if a square has been hit already
function checkSquareHit(row, col) {
if (targetmap[row][col] === "X") {
return true;
}
return false;
}
loadShipMap(gamemap);
initTargetingMap();
//game loop
while (missles > 0) {
console.log("your missiles remaining are " + missles);
console.log("current game board:\n");
console.log(gamemap);
console.log(targetmap);
//input for playing
var row = parseInt(prompt("row to attack (0-9):"));
var col = parseInt(prompt("column to attack (0-9):"));
//tells you when you sunk a ship
if (isValidCoordinates(row, col)) {
if (checkShipSunk(row, col)) {
console.log("You sunk a ship!");
hitCount++;
//if you sink 17 ships, you win
if (hitCount == 17) {
console.log("Congratulations, you've sunk all the ships and won the game!");
return;
}
}
}
}
// Do not change any of the code below!
if (require.main === module)
{
main();
} remember this code for later
|
bb2aebbc5a445e644ebfd55a8f43699a
|
{
"intermediate": 0.3086564540863037,
"beginner": 0.47921761870384216,
"expert": 0.21212589740753174
}
|
1,138
|
Here's my code:
_______________________
library(rvest)
# create data frames for each section of data
data_A <- data.frame(
protocol_url_segment = character(),
A.1 = character(), A.2 = character(), A.3 = character(), A.3.1 = character(), A.3.2 = character(), A.4.1 = character(), A.5.1 = character(), A.5.2 = character(), A.5.3 = character(), A.5.4 = character(), A.7 = character(), A.8 = character(),
stringsAsFactors = FALSE
)
[TRUNCATED]
data_P <- data.frame(
protocol_url_segment = character(),
P.A = character(), P.B = character(),
stringsAsFactors = FALSE
)
# specify the base URL of the protocol page
protocol_url_segment <- "2015-003589-10/GR"
base_url <- "https://www.clinicaltrialsregister.eu/ctr-search/trial/"
url <- paste0(base_url, protocol_url_segment)
# read in the HTML content of the page
page <- read_html(url)
# extract the tricell rows as a list of nodes
tricell_rows <- page %>% html_nodes("tr.tricell")
# function to extract the text from row td elements and create a row vector
extract_td_text <- function(row) {
td_elements <- html_children(row)
td_texts <- sapply(td_elements, html_text)
td_texts <- trimws(td_texts)
return(as.vector(td_texts))
}
# extract the text from the td elements in each row and store them in rows_list
rows_list <- lapply(tricell_rows, extract_td_text)
# create a data frame from the rows_list
tricell_df <- do.call(rbind.data.frame, c(rows_list, stringsAsFactors = FALSE))
colnames(tricell_df) <- c("Column1", "Column2", "Column3")
# Create a data frame with the codes and their corresponding replacements
lookup_df <- data.frame(
code = c("E.8.9.1", "E.8.9.1", "E.8.9.1", "E.8.9.2", "E.8.9.2", "E.8.9.2",
[TRUNCATED]
)
)
# Loop through each row in the target data frame and check if the code and value match
for (i in 1:nrow(tricell_df)) {
code <- tricell_df[i, 1]
value <- tricell_df[i, 2]
replacement <- lookup_df[lookup_df$code == code & lookup_df$value == value, "replacement"]
# If a match is found, replace the code with the corresponding replacement
if (length(replacement) > 0) {
tricell_df[i, 1] <- replacement
}
}
# Function that filters dataframe by the first letter in ‘Column1’ and returns the filtered dataframe
filter_by_first_letter <- function(df, letter) {
index <- grep(paste0("^", letter), df$Column1)
filtered_df <- df[index,]
return(filtered_df)
}
# Filter the dataframe for each letter, then create separate dataframes
df_A <- filter_by_first_letter(tricell_df, "A")
[TRUNCATED]
df_P <- filter_by_first_letter(tricell_df, "P")
data_list <- list(data_A, data_B, data_D, data_E, data_F, data_G, data_H, data_N, data_P)
df_list <- list(df_A, df_B, df_D, df_E, df_F, df_G, df_H, df_N, df_P)
# Loop through each pair of data_ and df_ dataframes
for (k in 1:length(data_list)) {
data_df <- data_list[[k]]
merge_df <- df_list[[k]]
if (nrow(merge_df) == 0) {
next
}
new_row <- data_df[1,] # Create a new row based on the structure of the data_ dataframe
# Set all values in the new row to NA except the protocol_url_segment column
new_row[,-1] <- NA
new_row$protocol_url_segment <- protocol_url_segment
# Loop through each row in the df_ dataframe
for (i in 1:nrow(merge_df)) {
code <- merge_df[i, 1]
value <- merge_df[i, 3]
# Check if the code exists in the data_ dataframe
if (code %in% colnames(data_df)) {
# Insert the value at the corresponding column in the new row
new_row[, code] <- value
}
}
# Add the new row to the data_ dataframe
data_list[[k]] <- rbind(data_list[[k]], new_row)
}
# Update the data_ dataframes with the merged values
data_A <- data_list[[1]]
[TRUNCATED]
data_N <- data_list[[8]]
_________________________
We need to change a thing... Handling of multiple entries is not working.
The problem is with the data from B, D and G.
While for the others, there's only one entry per df_, for B, D and G, each protocol_url may have multiple entries. If there are multiple entries I want them saved with a row each in the data_ dataframes.
Multiple entries in those dataframes will appear sequentially, and not in multiple columns. You can detect it's a new entry if the codes start repeating.
It may help to know that each entry will always start with the same code: "B.1.1", "D.1.2andD.1.3" or "G.4.1", respectively.
If there are multiple, they will be sequentially in the df dataframe, per example:
"D.1.2andD.1.3" "D.2.1" "D.2.5" "D.2.5.1" "D.3.1" "D.3.2" "D.3.4" "D.3.4.1"
"D.3.7" "D.3.8" "D.3.9.1" "D.3.9.2" "D.3.10.1" "D.3.10.2" "D.3.10.3" "D.3.11.1"
"D.3.11.2" "D.3.11.3" "D.3.11.3.1" "D.3.11.3.2" "D.3.11.3.3" "D.3.11.3.4" "D.3.11.3.5" "D.3.11.4"
"D.3.11.5" "D.3.11.6" "D.3.11.7" "D.3.11.8" "D.3.11.9" "D.3.11.10" "D.3.11.11" "D.3.11.12"
"D.3.11.13" "D.1.2andD.1.3" "D.2.1" "D.2.5"
|
69f1fee12ace872fbe349b5fba592e2a
|
{
"intermediate": 0.527786910533905,
"beginner": 0.3039166331291199,
"expert": 0.16829648613929749
}
|
1,139
|
kotlin txt file process to database room entity
|
c258cd267629925f01913775a1418a84
|
{
"intermediate": 0.45159074664115906,
"beginner": 0.2229928821325302,
"expert": 0.3254163861274719
}
|
1,140
|
переделай код, чтобы строилась гистограмма преобразованного изображения.
// Создаем гистограмму преобразованного изображения
int[] transformedHistogram = new int[256];
BufferedImage transformedImage = null;
if (image != null) {
transformedImage = copyImage(image);
// Ваш код преобразования изображения должен быть здесь
int[][] imageMatrix = convertToMatrix(transformedImage);
//максимальная и минимальная яркости
int maxValue = getMaxValue(imageMatrix);
int minValue = getMinValue(imageMatrix);
//разница между максимальной и минимальной яркостями
float range = (float)(maxValue - minValue);
for (int i = 0; i < transformedImage.getWidth(); i++) {
for (int j = 0; j < transformedImage.getHeight(); j++) {
int pixel = image.getRGB(i, j);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = pixel & 0xff;
// Вычисляем яркость пикселя
int brightness = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue);
// Вычисляем преобразованную яркость пикселя
float newBrightness = ((brightness - minValue) / range) * 255.0f;
transformedImage.setRGB(i, j, new Color((int)newBrightness, (int)newBrightness, (int)newBrightness).getRGB());
transformedHistogram[(int)newBrightness]++;
}
}
}
// Создаем окно для отображения гистограмм
JFrame histogramFrame = new JFrame("Гистограмма");
histogramFrame.setLayout(new GridLayout(1, 2, 5, 5));
// Создаем панель для первой гистограммы (исходного изображения)
JPanel histogramPanel1 = new JPanel();
histogramPanel1.setLayout(new BorderLayout());
histogramPanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Исходное изображение"));
// Создаем компонент для рисования гистограммы исходного изображения
JPanel histogramComponent1 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int max = Arrays.stream(histogram).max().getAsInt();
for (int i = 0; i < 256; i++) {
int height = (int) (300.0 * histogram[i] / max);
g.fillRect(i, 300 - height, 1, height);
}
}
};
histogramComponent1.setPreferredSize(new Dimension(256, 300));
histogramPanel1.add(histogramComponent1, BorderLayout.CENTER);
// Создаем панель для второй гистограммы (преобразованного изображения)
JPanel histogramPanel2 = new JPanel();
histogramPanel2.setLayout(new BorderLayout());
histogramPanel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Преобразованное изображение"));
// Создаем компонент для рисования гистограммы преобразованного изображения
JPanel histogramComponent2 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int max = Arrays.stream(transformedHistogram).max().getAsInt();
for (int i = 0; i < 256; i++) {
int height = (int) (300.0 * transformedHistogram[i] / max);
g.fillRect(i, 300 - height, 1, height);
}
}
};
histogramComponent2.setPreferredSize(new Dimension(256, 300));
histogramPanel2.add(histogramComponent2, BorderLayout.CENTER);
histogramFrame.add(histogramPanel1);
histogramFrame.add(histogramPanel2);
histogramFrame.pack();
histogramFrame.setLocationRelativeTo(null);
histogramFrame.setVisible(true);
}
private BufferedImage copyImage(BufferedImage image) {
ColorModel cm = image.getColorModel();
WritableRaster raster = image.copyData(null);
return new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);
}
private int[][] convertToMatrix(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] matrix = new int[height][width];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
matrix[j][i] = image.getRGB(i, j);
}
}
return matrix;
}
private int getMaxValue(int[][] matrix) {
int maxValue = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > maxValue) {
maxValue = matrix[i][j];
}
}
}
return maxValue;
}
private int getMinValue(int[][] matrix) {
int minValue = Integer.MAX_VALUE;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < minValue) {
minValue = matrix[i][j];
}
}
}
return minValue;
}
|
edce33389ad4c58f68966616dd0bfeb3
|
{
"intermediate": 0.27017104625701904,
"beginner": 0.4182847738265991,
"expert": 0.3115442097187042
}
|
1,141
|
hello
|
8b9f2aa671cdfedf9049acf2ed55afbe
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
1,142
|
pipes make me 3 tasks with solution
|
37819b9add07d691a3d5b5071a8efee2
|
{
"intermediate": 0.3112431466579437,
"beginner": 0.3890542984008789,
"expert": 0.29970258474349976
}
|
1,143
|
Hi, i’ve implemented the following ImageDataset Class and I want you to go through the code and check for any potential issues or loopholes. You are free to come up with any better ideas and modifications as well. So, Here is the code:# Implement ImageDataset class
class ImageDataset(Dataset):
def init(self, folder_names, transform=None):
self.folder_names = folder_names
self.transform = transform
self.y = self.get_labels()
def get_labels(self):
labels = []
for i, folder in enumerate(self.folder_names):
labels.extend([i] * len(os.listdir(folder)))
return labels
def len(self):
return sum(len(os.listdir(folder)) for folder in self.folder_names)
def getitem(self, idx):
for i, folder_name in enumerate(self.folder_names):
if idx < len(os.listdir(folder_name)):
file = os.listdir(folder_name)[idx]
img = Image.open(os.path.join(folder_name, file))
if self.transform:
img = self.transform(img)
label = i
return img, label
idx -= len(os.listdir(folder_name))
|
de44984fae5a8b7ab446b30826b93f98
|
{
"intermediate": 0.37205228209495544,
"beginner": 0.3062642514705658,
"expert": 0.32168346643447876
}
|
1,144
|
Here's my code:
_______________________
library(rvest)
# create data frames for each section of data
data_A <- data.frame(
protocol_url_segment = character(),
A.1 = character(), A.2 = character(), A.3 = character(), A.3.1 = character(), A.3.2 = character(), A.4.1 = character(), A.5.1 = character(), A.5.2 = character(), A.5.3 = character(), A.5.4 = character(), A.7 = character(), A.8 = character(),
stringsAsFactors = FALSE
)
[TRUNCATED]
data_P <- data.frame(
protocol_url_segment = character(),
P.A = character(), P.B = character(),
stringsAsFactors = FALSE
)
# specify the base URL of the protocol page
protocol_url_segment <- "2015-003589-10/GR"
base_url <- "https://www.clinicaltrialsregister.eu/ctr-search/trial/"
url <- paste0(base_url, protocol_url_segment)
# read in the HTML content of the page
page <- read_html(url)
# extract the tricell rows as a list of nodes
tricell_rows <- page %>% html_nodes("tr.tricell")
# function to extract the text from row td elements and create a row vector
extract_td_text <- function(row) {
td_elements <- html_children(row)
td_texts <- sapply(td_elements, html_text)
td_texts <- trimws(td_texts)
return(as.vector(td_texts))
}
# extract the text from the td elements in each row and store them in rows_list
rows_list <- lapply(tricell_rows, extract_td_text)
# create a data frame from the rows_list
tricell_df <- do.call(rbind.data.frame, c(rows_list, stringsAsFactors = FALSE))
colnames(tricell_df) <- c("Column1", "Column2", "Column3")
# Create a data frame with the codes and their corresponding replacements
lookup_df <- data.frame(
code = c("E.8.9.1", "E.8.9.1", "E.8.9.1", "E.8.9.2", "E.8.9.2", "E.8.9.2",
[TRUNCATED]
)
)
# Loop through each row in the target data frame and check if the code and value match
for (i in 1:nrow(tricell_df)) {
code <- tricell_df[i, 1]
value <- tricell_df[i, 2]
replacement <- lookup_df[lookup_df$code == code & lookup_df$value == value, "replacement"]
# If a match is found, replace the code with the corresponding replacement
if (length(replacement) > 0) {
tricell_df[i, 1] <- replacement
}
}
# Function that filters dataframe by the first letter in ‘Column1’ and returns the filtered dataframe
filter_by_first_letter <- function(df, letter) {
index <- grep(paste0("^", letter), df$Column1)
filtered_df <- df[index,]
return(filtered_df)
}
# Filter the dataframe for each letter, then create separate dataframes
df_A <- filter_by_first_letter(tricell_df, "A")
[TRUNCATED]
df_P <- filter_by_first_letter(tricell_df, "P")
data_list <- list(data_A, data_B, data_D, data_E, data_F, data_G, data_H, data_N, data_P)
df_list <- list(df_A, df_B, df_D, df_E, df_F, df_G, df_H, df_N, df_P)
# Loop through each pair of data_ and df_ dataframes
for (k in 1:length(data_list)) {
data_df <- data_list[[k]]
merge_df <- df_list[[k]]
if (nrow(merge_df) == 0) {
next
}
new_row <- data_df[1,] # Create a new row based on the structure of the data_ dataframe
# Set all values in the new row to NA except the protocol_url_segment column
new_row[,-1] <- NA
new_row$protocol_url_segment <- protocol_url_segment
# Loop through each row in the df_ dataframe
for (i in 1:nrow(merge_df)) {
code <- merge_df[i, 1]
value <- merge_df[i, 3]
# Check if the code exists in the data_ dataframe
if (code %in% colnames(data_df)) {
# Insert the value at the corresponding column in the new row
new_row[, code] <- value
}
}
# Add the new row to the data_ dataframe
data_list[[k]] <- rbind(data_list[[k]], new_row)
}
# Update the data_ dataframes with the merged values
data_A <- data_list[[1]]
[TRUNCATED]
data_N <- data_list[[8]]
_________________________
We need to change a thing... Handling of multiple entries is not working.
The problem is with the data from B, D and G.
While for the others, there's only one entry per df_, for B, D and G, each protocol_url may have multiple entries. If there are multiple entries I want them saved with a row each in the data_ dataframes.
Multiple entries in those dataframes will appear sequentially, and not in multiple columns. You can detect it's a new entry if the codes start repeating.
It may help to know that each entry will always start with the same code: "B.1.1", "D.1.2andD.1.3" or "G.4.1", respectively.
If there are multiple, they will be sequentially in the df dataframe, per example:
"D.1.2andD.1.3" "D.2.1" "D.2.5" "D.2.5.1" "D.3.1" "D.3.2" "D.3.4" "D.3.4.1"
"D.3.7" "D.3.8" "D.3.9.1" "D.3.9.2" "D.3.10.1" "D.3.10.2" "D.3.10.3" "D.3.11.1"
"D.3.11.2" "D.3.11.3" "D.3.11.3.1" "D.3.11.3.2" "D.3.11.3.3" "D.3.11.3.4" "D.3.11.3.5" "D.3.11.4"
"D.3.11.5" "D.3.11.6" "D.3.11.7" "D.3.11.8" "D.3.11.9" "D.3.11.10" "D.3.11.11" "D.3.11.12"
"D.3.11.13" "D.1.2andD.1.3" "D.2.1" "D.2.5"
|
faeb8d03fcd324aebcd83f642de8cf21
|
{
"intermediate": 0.527786910533905,
"beginner": 0.3039166331291199,
"expert": 0.16829648613929749
}
|
1,145
|
is there is a way to dial a code on an Android device from a C# Windows application that doesn’t require ADB or ADB bridge?
|
bca36baac7682f919ed2312f9c6e3db6
|
{
"intermediate": 0.6812052130699158,
"beginner": 0.12804056704044342,
"expert": 0.190754234790802
}
|
1,146
|
how to make this accepted json.loads() modifying the string only using python “{{message_agent}} Use this command to reach out for more information: “message_agent”, args: “name”: “main”, “message”: “<message>”;”
|
948fb4cdd855f993b4d6dd9c85289f3b
|
{
"intermediate": 0.4221298396587372,
"beginner": 0.2842732071876526,
"expert": 0.29359692335128784
}
|
1,147
|
My suggestion is , Can it be more optimized if we do computations on tensors instead of arrays like in this line here running_test_acc += (y_pred.argmax(dim=1) == y_batch).sum().item(). So, what’s your take and if I’m correct I want the computation to be done in tensors. Here is the code:def train_model(model, train_loader, test_loader, epochs = None, learning_rate = None, optimization_technique = None, patience=None, scheduler_patience=None,num_batches = None, **kwargs):
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience:
scheduler = ReduceLROnPlateau(optimizer, 'min', patience=scheduler_patience, verbose=True)
else:
scheduler = None
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
best_loss = float('inf')
stopping_counter = 0
# Enable cudnn benchmark
torch.backends.cudnn.benchmark = True
with_dropout = model.classifier[6]
without_dropout = nn.Sequential(*[layer for layer in model.classifier if layer != with_dropout])
for epoch in range(epochs):
running_train_loss = 0.0
running_train_acc = 0
num_batches_train = 0
#for X_batch, y_batch in itertools.islice(train_loader, 0, num_batches):
for X_batch, y_batch in train_loader:
# Move batch to device
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
optimizer.zero_grad()
y_pred = model(X_batch.half()) #if kwargs.get('use_mixed_precision', False) else X_batch)
#y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
loss.backward()
optimizer.step()
running_train_loss += loss.item()
#running_train_acc += accuracy_score(y_batch.cpu().numpy(), y_pred.argmax(dim=1).cpu().numpy())
running_train_acc += (y_pred.argmax(dim=1) == y_batch).sum().item()
num_batches_train += 1
train_losses.append(running_train_loss / num_batches_train)
train_accuracies.append(running_train_acc / len(train_loader.dataset))
print(num_batches_train, len(train_loader.dataset))
# Testing segment
running_test_loss = 0.0
running_test_acc = 0
num_batches_test = 0
with torch.no_grad():
for X_batch, y_batch in test_loader:
#for X_batch, y_batch in itertools.islice(test_loader, 0, num_batches):
# Move batch to device
#X_batch, y_batch = X_batch.to(device), y_batch.to(device)
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
y_pred = model(X_batch.half()) #if kwargs.get(‘use_mixed_precision’, False) else X_batch)
#y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
running_test_loss += loss.item()
running_test_acc += (y_pred.argmax(dim=1) == y_batch).sum().item()
#running_test_acc += accuracy_score(y_batch.cpu().numpy(), y_pred.argmax(dim=1).cpu().numpy())
num_batches_test += 1
test_losses.append(running_test_loss / num_batches_test)
test_accuracies.append(running_test_acc / len(test_loader.dataset))
# Early stopping
if optimization_technique == 'early_stopping' and patience:
if test_losses[-1] < best_loss:
best_loss = test_losses[-1]
stopping_counter = 0
else:
stopping_counter += 1
if stopping_counter > patience:
print(f"Early stopping at epoch {epoch+1}/{epochs}")
break
# Learning rate scheduler
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience and scheduler:
scheduler.step(test_losses[-1])
print(f"Epoch: {epoch+1}/{epochs}, Training Loss: {train_losses[-1]}, Test Loss: {test_losses[-1]}, Training Accuracy: {train_accuracies[-1]}, Test Accuracy: {test_accuracies[-1]}")
return train_losses, train_accuracies, test_losses, test_accuracies
|
99653f4e86c20f4f8dc2ce0c544508eb
|
{
"intermediate": 0.30868756771087646,
"beginner": 0.48942017555236816,
"expert": 0.2018921971321106
}
|
1,148
|
I am need to create a CSV file for me using Python. This CSV file will include both numbers and text, and I have a specific format that must be followed. We need to append the given config to the csv file and later data needs to be added to that. I have the data part written. Just need to append the config before adding the data. It needs to be done using dataframes.
|
164cce13470d4ea4f00de3a6f612b63b
|
{
"intermediate": 0.47531136870384216,
"beginner": 0.23600374162197113,
"expert": 0.2886848747730255
}
|
1,149
|
Could you explain how the kernel trick works? use numerical example and walk through it step by step by hand to prove your claims
|
2b9ce55d4e825b4d9067549e6c0737e9
|
{
"intermediate": 0.20638833940029144,
"beginner": 0.11316654086112976,
"expert": 0.68044513463974
}
|
1,151
|
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<style>
#controls {
position: fixed;
left: 0px;
width: 20%;
top: 0px;
height: 10%;
}
#chart {
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
path.link {
fill: none;
stroke: #c5c5c5;
stroke-width: 1.0px;
}
circle {
fill: #ccc;
stroke: #fff;
stroke-width: 1.5px;
}
text {
fill: #000000;
font: 11px sans-serif;
pointer-events: none;
}
.ingoing {
stroke: #237690!important;
stroke-width: 1.5px!important;
}
.outgoing {
stroke: #FA1209!important;
stroke-width: 1.5px!important;
}
.selected {
stroke: #000000!important;
stroke-width: 1.5px!important;
}
</style>
<body>
<div id="chart"></div>
<div id="controls">
<input type="checkbox" id="cb_hierarchical" checked="True" onclick='redraw();'>Order by dependency chain<br>
<input type="checkbox" id="cb_curved" checked="True" onclick='redraw();'>Curved Lines<br>
</div>
<script>
var cb_hierarchical = document.getElementById("cb_hierarchical");
var cb_curved = document.getElementById("cb_curved");
var chartDiv = document.getElementById("chart");
var svg = d3.select(chartDiv).append("svg");
var linkedByIndex = {};
var num_links = {};
var num_links_incoming = {};
graph.links.forEach(function(d) {
linkedByIndex[d.source + "," + d.target] = 1;
num_links[d.target] = (num_links[d.target] != undefined ? num_links[d.target] + 1 : 1)
num_links[d.source] = (num_links[d.source] != undefined ? num_links[d.source] + 1 : 1)
num_links_incoming[d.target] = (num_links_incoming[d.target] != undefined ? num_links_incoming[d.target] + 1 : 1)
d.distance = graph.nodes[d.target].level - graph.nodes[d.source].level;
});
const maxlevel = graph.nodes.reduce(function(currentValue, node) {
return Math.max(node.level, currentValue);
}, 0);
var maxlinks = Object.values(num_links).reduce(function(currentValue, entry) {
return Math.max(entry, currentValue);
}, 0);
var white_background = svg.append("svg:defs")
.append("filter")
.attr("x", 0)
.attr("y", 0)
.attr("width", 1)
.attr("height", 1)
.attr("id", "white_background");
white_background
.append("feFlood")
.attr("flood-color", "white");
white_background
.append("feComposite")
.attr("in", "SourceGraphic")
var simulation = d3.forceSimulation(graph.nodes)
.on('tick', tick);
// add the links
var path = svg.selectAll("path")
.data(graph.links)
.enter().append("svg:path")
.attr("class", "link");
// define the nodes
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.on("mouseover", highlight(true))
.on("mouseout", highlight(false))
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
use minimal from code above to draw following structure type: [{locationId:"someLocationId ", id:"someId", title:"название кнопки" content:"текст",choices:[someId, someId]},{locationId:"someLocationId", id:"someId", title:"название кнопки" content: "text",choices:[someId, someId]},...]
|
c59faf3102ae4b08ef6c5370186c8de8
|
{
"intermediate": 0.24774795770645142,
"beginner": 0.5017282962799072,
"expert": 0.2505236864089966
}
|
1,152
|
In python, make a machine learning model to predict a 5x5 minesweeper game. You can’t make it random or make it predict 2 same results in a row if a new game is started. You have data for the past 30 games [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9] and you need to predict x safe spots that are giving by the user and bomb locations which is the minesThe data lenght changes by the selected mines. It's mines x 30, = all mine past data. So 3 mines becomes 90 past mines. You need to use the list raw and it needs to get the same data if the mine locations are not changed. It also needs to the accuracy
|
02ac12e279a39e52c1cf0d562ed2fb3a
|
{
"intermediate": 0.12122253328561783,
"beginner": 0.06032956764101982,
"expert": 0.8184478878974915
}
|
1,153
|
I forgot to set the rank for GPU here in this code: import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
import torch.distributed as dist
import itertools
# Initialize Distributed Training
dist.init_process_group(backend=“nccl”)
device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
torch.cuda.set_device(dist.get_rank())
# Define Training Hyperparameters
batch_size = 128
learning_rate = 0.001
epochs = 10
patience = None
scheduler_patience = None
optimization_technique = ‘early_stopping’
num_workers = 4
prefetch_factor = 2
persistent_workers = True
accumulation_steps = 4
# Define Model
model = …
# Define Data Loaders
image_dataset = …
train_sampler = DistributedSampler(image_dataset, num_replicas=dist.get_world_size(), rank=dist.get_rank())
train_loader = DataLoader(
image_dataset,
batch_size=batch_size,
sampler=train_sampler,
num_workers=num_workers,
pin_memory=True,
prefetch_factor=prefetch_factor,
persistent_workers=persistent_workers
)
test_loader = DataLoader(
image_dataset,
batch_size=batch_size,
sampler=torch.utils.data.SubsetRandomSampler(test_indices),
num_workers=num_workers,
pin_memory=True,
prefetch_factor=prefetch_factor,
persistent_workers=persistent_workers
)
# Define Training Loop
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
if optimization_technique == ‘learning_rate_scheduler’ and scheduler_patience:
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, ‘min’, patience=scheduler_patience, verbose=True)
else:
scheduler = None
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
best_loss = float(‘inf’)
stopping_counter = 0
# Enable cudnn benchmark
torch.backends.cudnn.benchmark = True
# Enable Automatic Mixed Precision (AMP)
scaler = torch.cuda.amp.GradScaler()
for epoch in range(epochs):
train_stream = torch.cuda.Stream()
test_stream = torch.cuda.Stream()
running_train_loss = 0.0
running_train_acc = 0
num_batches_train = 0
optimizer.zero_grad(set_to_none=True)
for i, (X_batch, y_batch) in enumerate(train_loader):
# Move batch to device
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
# Start asynchronous data transfer
with torch.cuda.stream(train_stream):
# Automatic Mixed Precision (AMP)
with torch.cuda.amp.autocast():
y_pred = model(X_batch.half())
loss = criterion(y_pred, y_batch)
scaler.scale(loss/accumulation_steps).backward()
if (i + 1) % accumulation_steps == 0:
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad(set_to_none=True)
running_train_loss += loss.item()
running_train_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item()
num_batches_train += 1
train_stream.synchronize()
train_losses.append(running_train_loss / num_batches_train)
train_accuracies.append(running_train_acc / len(train_loader.dataset))
# Testing segment
running_test_loss = 0.0
running_test_acc = 0
num_batches_test = 0
with torch.no_grad():
for X_batch, y_batch in test_loader:
# Move batch to device
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
# Start asynchronous data transfer
with torch.cuda.stream(test_stream):
with torch.cuda.amp.autocast():
y_pred = model(X_batch.half())
loss = criterion(y_pred, y_batch)
running_test_loss += loss.item()
running_test_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item()
num_batches_test += 1
test_stream.synchronize()
test_losses.append(running_test_loss / num_batches_test)
test_accuracies.append(running_test_acc / len(test_loader.dataset))
# Early stopping
if optimization_technique == ‘early_stopping’ and patience:
if test_losses[-1] < best_loss:
best_loss = test_losses[-1]
stopping_counter = 0
else:
stopping_counter += 1
if stopping_counter > patience:
print(f"Early stopping at epoch {epoch+1}/{epochs}")
break
# Learning rate scheduler
if optimization_technique == ‘learning_rate_scheduler’ and scheduler_patience and scheduler:
scheduler.step(test_losses[-1])
print(f"Epoch: {epoch+1}/{epochs}, Training Loss: {train_losses[-1]}, Test Loss: {test_losses[-1]}, Training Accuracy: {train_accuracies
|
db89354f351ed175aa15322c75645b72
|
{
"intermediate": 0.3153258264064789,
"beginner": 0.4350565969944,
"expert": 0.2496175915002823
}
|
1,154
|
In python, you need to create a predictor for a minesweeper game. You've data for the past 30 games with 3 mines in each. Each number in the list is a bomb location from the past 30 games.The field is a 5x5. List is:[5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9]
You need to predict 5 safe spots and you need to use machine learning to do it
|
58753371bd615b1511b85eca74656c53
|
{
"intermediate": 0.18801794946193695,
"beginner": 0.09280750900506973,
"expert": 0.7191746234893799
}
|
1,155
|
Hi
In python, you need to create a predictor for a minesweeper game. You've data for the past 30 games with 3 mines in each. Each number in the list is a bomb location from the past 30 games.The field is a 5x5. List is:[5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9] this list contains data for 3 mines games
Include this: The user has to input number of safe spots he wants, and the amount of mines there are. If the user inputs for example, 3 mines, you have to predict the amount of safe spots he chose. The user can max input up to 7 mines.Also one thing: The data will automaticly change.
Important: You have to chose the model thats best for the task. The accuracy has to be minium 70%
|
f8da72c728956419ba2d560167b9057c
|
{
"intermediate": 0.29705488681793213,
"beginner": 0.16599547863006592,
"expert": 0.5369496941566467
}
|
1,156
|
b562bf0b-54e6-4185-8c50-0cabf793339c
d510d03e-a6ad-427c-b2e9-aef730072049
is there a pattern in the strings I sent?
|
135bc4399600f6e3a2edf10e50f4b1d2
|
{
"intermediate": 0.4189550578594208,
"beginner": 0.2565339505672455,
"expert": 0.32451096177101135
}
|
1,157
|
use this string d510d03e-a6ad-427c-b2e9-aef730072049
I am trying to predict a minesweeper game out of the id of it. the board is a 5x5 one please help in python
|
7c6c89042c270b87e3f25516005e0366
|
{
"intermediate": 0.3266650438308716,
"beginner": 0.3756372928619385,
"expert": 0.29769769310951233
}
|
1,158
|
Java palindrome chwck function that takes str input please provide most effficient solutuon with explanation
|
5b58695f249d78535782d5d18766c293
|
{
"intermediate": 0.4086105227470398,
"beginner": 0.3711739778518677,
"expert": 0.22021552920341492
}
|
1,159
|
Java. Functuon takes input str return number of vowels. Y is not vowel. Most effficient solutuon
|
f09c473552bd555c69a713393bc67a60
|
{
"intermediate": 0.42289528250694275,
"beginner": 0.22604382038116455,
"expert": 0.3510608375072479
}
|
1,160
|
In python, you need to create a predictor for a minesweeper game. You've data for the past 30 games with 3 mines in each. Each number in the list is a bomb location from the past 30 games.The field is a 5x5. List is:[5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9]
You need to predict 5 safe spots and you need to use machine learning to do it
|
ae86e8e48bf015e20e6ef287265eca4d
|
{
"intermediate": 0.18801794946193695,
"beginner": 0.09280750900506973,
"expert": 0.7191746234893799
}
|
1,161
|
[{locationId:"someLocationId ", id:"someId", title:"название кнопки" content:"текст",choices:[someId, someId]},{locationId:"someLocationId", id:"someId", title:"название кнопки" content: "text",choices:[someId, someId]},...]
/////////////////////////
write JS func to visualize data format, we need it to show rectangles connected with lines, so we can move them with mouse to see the whole structure
|
c8ffbdce0ba58e6b6e6ea0e386338e7f
|
{
"intermediate": 0.5038512349128723,
"beginner": 0.2547435164451599,
"expert": 0.24140521883964539
}
|
1,162
|
Evaluate these classes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
public class HashMap<K, V> : IMap<K, V>
{
/* Properties */
public Entry<K, V>[] Table { get; set; }
public int Capacity { get; set; }
public double LoadFactor { get; set; }
public int size; // Had to use a field to satisfy the IMap requirements of using the Size() method.
public int Placeholders { get; set; } // Keeps track of the number of placeholders in the HashMap.
/* Constructors */
public HashMap()
{
this.Capacity = 11;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = 0.75;
this.size = 0;
}
public HashMap(int initialCapacity)
{
if (initialCapacity <= 0)
{
throw new ArgumentException();
}
this.Capacity = initialCapacity;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = 0.75;
this.size = 0;
}
public HashMap(int initialCapacity, double loadFactor)
{
if (initialCapacity <= 0 || loadFactor <= 0)
{
throw new ArgumentException();
}
this.Capacity = initialCapacity;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = loadFactor;
this.size = 0;
}
/* Methods */
/// <summary>
/// Returns the current size.
/// </summary>
/// <returns></returns>
public int Size()
{
return this.size;
}
/// <summary>
/// Returns true if number of ctive entries in the array is 0.
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return this.size == 0;
}
/// <summary>
/// Wipes out the array and all placeholders.
/// </summary>
public void Clear()
{
Array.Clear(this.Table, 0, this.Table.Length);
this.size = 0;
this.Placeholders = 0;
}
/// <summary>
/// Looks for the next available bucket based on the key passed.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public int GetMatchingOrNextAvailableBucket(K key)
{
int startPosition = Math.Abs(key.GetHashCode()) % this.Table.Length;
for (int i = 0; i < this.Capacity; i++)
{
int bucket = (startPosition + i) % this.Capacity;
if (this.Table[bucket] == null || this.Table[bucket].Key.Equals(key))
{
return bucket;
}
}
throw new InvalidOperationException("“No available bucket found.");
}
/// <summary>
/// Returns the value located at the bucket found by hashing the key.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public V Get(K key)
{
if (key == null)
{
throw new ArgumentNullException();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
if (this.Table[bucket] != null && this.Table[bucket].Key.Equals(key))
{
return this.Table[bucket].Value;
}
else
{
return default(V); // If no matching key is found, return the default value of the V type.
}
}
/// <summary>
/// Adds or updates the bucket found by hashing the key. If the bucket is emtpy insert a new entry with the passed key and value pair and return default.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public V Put(K key, V value)
{
if (key == null)
{
throw new ArgumentNullException();
}
if (value == null)
{
throw new ArgumentNullException();
}
if ((this.size + this.Placeholders + 1) >= (int)(this.Capacity * this.LoadFactor))
{
ReHash();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
for (Entry<K, V> entry = this.Table[bucket]; entry != null; entry = entry.Next)
{
if (entry.Key.Equals(key))
{
V oldValue = entry.Value;
entry.Value = value;
return oldValue;
}
}
Entry<K, V> newEntry = new Entry<K, V>(key, value);
newEntry.Next = this.Table[bucket];
this.Table[bucket] = newEntry;
this.size++;
return default(V);
}
/// <summary>
/// Looks u the buket based on the hashcode of the key. If a value exists at this bucket, set the value to null and icnrease plaecholder counter by one.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public V Remove(K key)
{
if (key == null)
{
throw new ArgumentNullException();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
if (this.Table[bucket] != null && this.Table[bucket].Key.Equals(key))
{
V removedValue = this.Table[bucket].Value;
this.Table[bucket].Value = default(V);
this.Placeholders++;
this.size--;
return removedValue;
}
else
{
return default(V); // If no matching key is found, return the default value of the V type.
}
}
/// <summary>
/// During a rehash, a new array size must be calculated. We start by doubling the original size, adding 1 and finding the next prime number.
/// </summary>
/// <returns></returns>
private int ReSize()
{
int newCapacity = this.Capacity;
// Find the nearest prime number greater than or equal to double the current capacity.
if (newCapacity == 1)
{
newCapacity = 2;
}
else
{
newCapacity = this.Capacity * 2;
while (!IsPrime(newCapacity))
{
newCapacity++;
}
}
return newCapacity;
}
/// <summary>
/// Occurs when the threshold (table length * load factor) is reached when adding a new Entry<K,V> to the Table.
/// </summary>
public void ReHash()
{
Entry<K, V>[] oldTable = this.Table;
int newCapacity = ReSize(); // Store the result of ReSize() in a local variable
Entry<K, V>[] newTable = new Entry<K, V>[newCapacity]; // Create a new table with the updated Capacity
this.size = 0; // Reset the size to 0 as we’ll be adding back all the elements.
this.Placeholders = 0;
// Rehash the entire hash map by iterating through the oldTable.
for (int i = 0; i < oldTable.Length; i++)
{
Entry<K, V> entry = oldTable[i];
while (entry != null)
{
Entry<K, V> nextEntry = entry.Next;
int startPosition = Math.Abs(entry.Key.GetHashCode()) % newTable.Length;
for (int j = 0; j < newCapacity; j++)
{
int bucket = (startPosition + j) % newCapacity;
if (newTable[bucket] == null)
{
newTable[bucket] = entry;
entry.Next = null;
this.size++;
break;
}
}
entry = nextEntry;
}
}
this.Table = newTable;
this.Capacity = newCapacity;
}
/// <summary>
/// Returns an IEnumerator compatible object containing only the values of each Entry in the Table.
/// </summary>
/// <returns></returns>
public IEnumerator<V> Values()
{
List<V> valuesList = new List<V>();
for (int i = 0; i < this.Capacity; i++)
{
Entry<K, V> entry = this.Table[i];
if (entry != null && entry.Value != null)
{
valuesList.Add(entry.Value);
}
}
return valuesList.GetEnumerator();
}
/// <summary>
/// Returns an IEnumerator compatible object containing only the keys of each Entry in the Table.
/// </summary>
/// <returns></returns>
public IEnumerator<K> Keys()
{
List<K> keysList = new List<K>();
for (int i = 0; i < this.Capacity; i++)
{
Entry<K, V> entry = this.Table[i];
if (entry != null && entry.Value != null)
{
keysList.Add(entry.Key);
}
}
return keysList.GetEnumerator();
}
/// <summary>
/// Checks to see if the number passed is a prime number or not.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2 || number == 3) return true;
if (number % 2 == 0) return false;
for (int i = 3; i * i <= number; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
public class Entry<K, V>
{
/* Properties */
public K Key { get; set; }
public V Value { get; set; }
public Entry<K, V> Next { get; set; } // Used for the next entry in HashMap.cs
/* Constructors */
public Entry(K key, V value)
{
this.Key = key;
this.Value = value;
}
}
}
|
3bc43ae234d3e57104749c069013cede
|
{
"intermediate": 0.40267544984817505,
"beginner": 0.4282904267311096,
"expert": 0.16903413832187653
}
|
1,163
|
Как мне исправить ошибку? Ошибка при добавлении товара:ADOQuery1: Parameter 'name' not found
C++
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include "Unit108.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm108 *Form108;
TADOConnection *ADOConnection1;
TADOQuery *ADOQuery1;
TDBGrid *DBGrid1;
TDataSource *DataSource1;
//---------------------------------------------------------------------------
__fastcall TForm108::TForm108(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm108::FormCreate(TObject *Sender)
{
// создание базы данных / таблицы, если их ещё не существует
String s;
s = "CREATE DATABASE IF NOT EXISTS `catalog`";
ADOQuery1->SQL->Text = s;
ADOQuery1->ExecSQL();
s = "CREATE TABLE IF NOT EXISTS `catalog`.`products` (`ID` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `price` FLOAT(8, 2) NOT NULL, `description` TEXT NOT NULL, `image` LONGBLOB NOT NULL, PRIMARY KEY (`ID`))";
ADOQuery1->SQL->Text = s;
ADOQuery1->ExecSQL();
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button2Click(TObject *Sender)
{
// Проверяем пустые поля
if (Edit1->Text == "" || Edit2->Text == "" || Edit3->Text == "")
{
ShowMessage("Заполните все поля!");
return;
}
// Проверяем наличие изображения
if (OpenPictureDialog1->FileName.IsEmpty())
{
ShowMessage("Выберите изображение!");
return;
}
try
{
TFileStream *fs = new TFileStream(OpenPictureDialog1->FileName, fmOpenRead);
try
{
// Указываем параметры для запроса
ADOQuery1->SQL->Text = "INSERT INTO `catalog`.`products` (`name`, `price`, `description`, `image`) VALUES (?, ?, ?, ?)";
ADOQuery1->Parameters->ParamByName("name")->Value = Edit1->Text;
ADOQuery1->Parameters->ParamByName("price")->Value = StrToFloat(Edit2->Text);
ADOQuery1->Parameters->ParamByName("description")->Value = Edit3->Text;
// Создаем поток для передачи изображения в базу данных
TMemoryStream *stream = new TMemoryStream();
try
{
stream->CopyFrom(fs, 0);
stream->Position = 0;
ADOQuery1->Parameters->ParamByName("image")->LoadFromStream(stream, ftBlob);
ADOQuery1->ExecSQL();
}
__finally
{
delete stream;
}
}
__finally
{
delete fs;
}
// Очистка полей ввода
Edit1->Clear();
Edit2->Clear();
Edit3->Clear();
// Очистка изображения
Image1->Picture->Assign(NULL);
// Обновление данных в таблице
ADOQuery1->Close();
ADOQuery1->Open();
}
catch (Exception &e)
{
ShowMessage("Ошибка при добавлении товара: " + e.Message);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button3Click(TObject *Sender)
{
if (OpenPictureDialog1->Execute())
{
Image1->Picture->LoadFromFile(OpenPictureDialog1->FileName);
}
}
//---------------------------------------------------------------------------
|
6a1f38d710d399fe618a575001dbef17
|
{
"intermediate": 0.3351594805717468,
"beginner": 0.36593908071517944,
"expert": 0.29890140891075134
}
|
1,164
|
Can you generate the code for the snake game in HTML, CSS and Javascript?
|
e6bf40334c53280910764ae7d5f667df
|
{
"intermediate": 0.4715995192527771,
"beginner": 0.3287428021430969,
"expert": 0.19965767860412598
}
|
1,165
|
Hi, I've implemented the following train function. I think there are some issues with the accuracy calculations. I might be due to appending issues or might be a division issuse. And also look for other potential issues and feel free to modify the code. Even come with a much more optimized way. here is the code: def train_model(model, device, train_loader, test_loader, epochs = None, learning_rate = None, optimization_technique = None, patience=None, scheduler_patience=None,num_batches = None, **kwargs):
criterion = nn.CrossEntropyLoss()
#optimizer = optim.SGD(model.parameters(), lr=learning_rate, weight_decay=5e-4)
optimizer = optim.Adam(model.parameters(), lr=learning_rate) # ,momentum = 0.9)
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience:
scheduler = ReduceLROnPlateau(optimizer, 'min', patience=scheduler_patience, verbose=True)
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
best_loss = float('inf')
stopping_counter = 0
# with_dropout = model.classifier[6]
# without_dropout = nn.Sequential(*[layer for layer in model.classifier if layer != with_dropout])
for epoch in range(epochs):
running_train_loss = 0.0
running_train_acc = 0
num_batches_train = 0
#for X_batch, y_batch in itertools.islice(train_loader, 0, num_batches):
for X_batch, y_batch in train_loader:
# Move batch to device
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
optimizer.zero_grad()
y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
loss.backward()
optimizer.step()
running_train_loss += loss.item()
running_train_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item()
num_batches_train += 1
train_losses.append(running_train_loss / num_batches_train)
train_accuracies.append(running_train_acc / len(train_loader.dataset))
# Testing segment
running_test_loss = 0.0
running_test_acc = 0
num_batches_test = 0
with torch.no_grad():
for X_batch, y_batch in test_loader:
#for X_batch, y_batch in itertools.islice(test_loader, 0, num_batches):
# Move batch to device
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
running_test_loss += loss.item()
running_test_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item()
# running_test_acc += accuracy_score(y_batch.cpu().numpy(), y_pred.argmax(dim=1).cpu().numpy())
num_batches_test += 1
test_losses.append(running_test_loss / num_batches_test)
test_accuracies.append(running_test_acc / len(test_loader.dataset))
# Early stopping
if optimization_technique == 'early_stopping' and patience:
if test_losses[-1] < best_loss:
best_loss = test_losses[-1]
stopping_counter = 0
else:
stopping_counter += 1
if stopping_counter > patience:
print(f"Early stopping at epoch {epoch+1}/{epochs}")
break
# Learning rate scheduler
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience and scheduler:
scheduler.step(test_losses[-1])
print(f"Epoch: {epoch+1}/{epochs}, Training Loss: {train_losses[-1]}, Test Loss: {test_losses[-1]}, Training Accuracy: {train_accuracies[-1]}, Test Accuracy: {test_accuracies[-1]}")
return train_losses, train_accuracies, test_losses, test_accuracies
|
d0a05cced15210bb4f024ee030138536
|
{
"intermediate": 0.2744673490524292,
"beginner": 0.4462796151638031,
"expert": 0.2792530357837677
}
|
1,166
|
Java fynctuon takes string array are that models a non looping graph. First element of array is the number of nodes (n) in the array as a string. The next n elementsare nodes and can be anything. After nth element rest are connections betwwen nodes as elements. Example input: ["4","A","B","C","D","A-B","B-D","B-C","C-D"] return the shortest path if no path betwwen first and last node exist return -1 please provide most effficient and shortest splution non conplicated something a junior developer d do
|
9cb2b433a90b2cee51c8389c8e132067
|
{
"intermediate": 0.5957247018814087,
"beginner": 0.08910457789897919,
"expert": 0.3151707351207733
}
|
1,167
|
def putExchangeDataAndDb(self, statusError, typeExchange):
zipPath = f'{squishinfo.testCase}/stmobile.zip'
config = self.config[statusError][typeExchange]
with open(zipPath, "rb") as outboxFile:
outboxContent = outboxFile.read()
files = {
"outbox": (outboxFile.name, outboxContent)
}
requests.put(self.url, data=config, files=files, verify=False)
как добавить в конструкцию чтение еще одного файла, так как у меня в архиве 2 файла
with open(zipPath, "rb") as outboxFile:
outboxContent = outboxFile.read()
files = {
"outbox": (outboxFile.name, outboxContent)
}
|
60e791a3be5e4bde2836b156cc72d7f9
|
{
"intermediate": 0.3607872426509857,
"beginner": 0.3454729914665222,
"expert": 0.29373979568481445
}
|
1,168
|
library(rvest)
# create data frames for each section of data
data_A <- data.frame(
protocol_url_segment = character(),
A.1 = character(), A.2 = character(), A.3 = character(), A.3.1 = character(), A.3.2 = character(), A.4.1 = character(), A.5.1 = character(), A.5.2 = character(), A.5.3 = character(), A.5.4 = character(), A.7 = character(), A.8 = character(),
stringsAsFactors = FALSE
)
[TRUNCATED]
data_P <- data.frame(
protocol_url_segment = character(),
P.A = character(), P.B = character(),
stringsAsFactors = FALSE
)
# specify the base URL of the protocol page
protocol_url_segment <- "2015-003589-10/GR"
base_url <- "https://www.clinicaltrialsregister.eu/ctr-search/trial/"
url <- paste0(base_url, protocol_url_segment)
# read in the HTML content of the page
page <- read_html(url)
# extract the tricell rows as a list of nodes
tricell_rows <- page %>% html_nodes("tr.tricell")
# function to extract the text from row td elements and create a row vector
extract_td_text <- function(row) {
td_elements <- html_children(row)
td_texts <- sapply(td_elements, html_text)
td_texts <- trimws(td_texts)
return(as.vector(td_texts))
}
# extract the text from the td elements in each row and store them in rows_list
rows_list <- lapply(tricell_rows, extract_td_text)
# create a data frame from the rows_list
tricell_df <- do.call(rbind.data.frame, c(rows_list, stringsAsFactors = FALSE))
colnames(tricell_df) <- c("Column1", "Column2", "Column3")
[TRUNCATED]
data_list <- list(data_A, data_B, data_D, data_E, data_F, data_G, data_H, data_N, data_P)
df_list <- list(df_A, df_B, df_D, df_E, df_F, df_G, df_H, df_N, df_P)
# Loop through each pair of data_ and df_ dataframes
for (k in 1:length(data_list)) {
data_df <- data_list[[k]]
merge_df <- df_list[[k]]
if (nrow(merge_df) == 0) {
next
}
new_row <- data_df[1,] # Create a new row based on the structure of the data_ dataframe
# Set all values in the new row to NA except the protocol_url_segment column
new_row[,-1] <- NA
new_row$protocol_url_segment <- protocol_url_segment
# Define the starting codes for new entries
starting_codes <- c("B.1.1", "D.1.2andD.1.3", "G.4.1")
entry_counter <- 1 # Initialize entry counter
# Loop through each row in the df_ dataframe
for (i in 1:nrow(merge_df)) {
code <- merge_df[i, 1]
value <- merge_df[i, 3]
# Check if the code exists in the data_ dataframe
if (code %in% colnames(data_df)) {
# If the code is a starting code of a new entry and it is not the first row
# then add the current new_row to the data_ dataframe and create a new new_row
if (code %in% starting_codes && i > 1) {
# Assign the entry counter value to the corresponding column
if (k == 2) { # data_B
new_row$sponsor_number <- entry_counter
} else if (k == 3) { # data_D
new_row$IMP_number <- entry_counter
} else if (k == 6) { # data_G
new_row$network_number <- entry_counter
}
data_list[[k]] <- rbind(data_list[[k]], new_row)
new_row <- data_df[1,]
new_row[,-1] <- NA
new_row$protocol_url_segment <- protocol_url_segment
entry_counter <- entry_counter + 1 # Increment the entry counter
}
# Insert the value at the corresponding column in the new row
new_row[, code] <- value
}
}
# Assign the entry counter value to the corresponding column in the last new_row
if (k == 2) { # data_B
new_row$sponsor_number <- entry_counter
} else if (k == 3) { # data_D
new_row$IMP_number <- entry_counter
} else if (k == 6) { # data_G
new_row$network_number <- entry_counter
}
# Add the last new row to the data_ dataframe
data_list[[k]] <- rbind(data_list[[k]], new_row)
}
# Update the data_ dataframes with the merged values
data_A <- data_list[[1]]
data_B <- data_list[[2]]
data_D <- data_list[[3]]
data_E <- data_list[[4]]
data_F <- data_list[[5]]
data_G <- data_list[[6]]
data_H <- data_list[[7]]
data_N <- data_list[[8]]
data_P <- data_list[[9]]
___________________________
This is working great!
Great! How can i loop through multiple protocol_url_segment values and compile them in the data_ dataframes?
|
f2525b2ad89e25a49db8bd638c27bcc6
|
{
"intermediate": 0.3650023639202118,
"beginner": 0.4172418713569641,
"expert": 0.2177557498216629
}
|
1,169
|
from pyrogram import Client
app = Client("my_bot", bot_token="AAFpAyKpaR6_QyfkFqYnPkXY2t2e1fEUc-w")
# Определяем функцию для отправки сообщения
@app.on_message()
def send_message():
# Получаем объект чата по ID
chat = app.get_chat(chat_id="-1001936058870")
# Отправляем текстовое сообщение в чат
Client.send_message(chat_id=chat.id, text="Привет, мир!")
# Вызываем функцию для отправки сообщения
send_message()
# Запускаем клиент Pyrogram
app.run()
В чем тут ошибка?
|
8b65fd164a5c64c088181a2623a7bba2
|
{
"intermediate": 0.42967933416366577,
"beginner": 0.2668026089668274,
"expert": 0.3035181164741516
}
|
1,170
|
In python, you need to predict a minesweeper game on a 5x5 field. You need to predict 4 safe spots in a 3 mines game. You have data for the past 30 games played: [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9]
|
e3ece37754a1190c3d2a293103226433
|
{
"intermediate": 0.319151371717453,
"beginner": 0.22913414239883423,
"expert": 0.45171448588371277
}
|
1,171
|
Evaluate the following classes:
'''
A module that encapsulates a web scraper. This module scrapes data from a website.
'''
from html.parser import HTMLParser
import urllib.request
from datetime import datetime, timedelta
import logging
from dateutil.parser import parse
class WeatherScraper(HTMLParser):
"""A parser for extracting temperature values from a website."""
logger = logging.getLogger("main." + __name__)
def __init__(self):
try:
super().__init__()
self.is_tbody = False
self.is_td = False
self.is_tr = False
self.last_page = False
self.counter = 0
self.daily_temps = {}
self.weather = {}
self.row_date = ""
except Exception as error:
self.logger.error("scrape:init:%s", error)
def is_valid_date(self, date_str):
"""Check if a given string is a valid date."""
try:
parse(date_str, default=datetime(1900, 1, 1))
return True
except ValueError:
return False
def is_numeric(self, temp_str):
"""Check if given temperature string can be converted to a float."""
try:
float(temp_str)
return True
except ValueError:
return False
def handle_starttag(self, tag, attrs):
"""Handle the opening tags."""
try:
if tag == "tbody":
self.is_tbody = True
if tag == "tr" and self.is_tbody:
self.is_tr = True
if tag == "td" and self.is_tr:
self.counter += 1
self.is_td = True
# Only parses the valid dates, all other values are excluded.
if tag == "abbr" and self.is_tr and self.is_valid_date(attrs[0][1]):
self.row_date = str(datetime.strptime(attrs[0][1], "%B %d, %Y").date())
# if len(attrs) == 2:
# if attrs[1][1] == "previous disabled":
# self.last_page = True
except Exception as error:
self.logger.error("scrape:starttag:%s", error)
def handle_endtag(self, tag):
"""Handle the closing tags."""
try:
if tag == "td":
self.is_td = False
if tag == "tr":
self.counter = 0
self.is_tr = False
except Exception as error:
self.logger.error("scrape:end:%s", error)
def handle_data(self, data):
"""Handle the data inside the tags."""
if data.startswith("Daily Data Report for January 2022"):
self.last_page = True
try:
if self.is_tbody and self.is_td and self.counter <= 3 and data.strip():
if self.counter == 1 and self.is_numeric(data.strip()):
self.daily_temps["Max"] = float(data.strip())
if self.counter == 2 and self.is_numeric(data.strip()):
self.daily_temps["Min"] = float(data.strip())
if self.counter == 3 and self.is_numeric(data.strip()):
self.daily_temps["Mean"] = float(data.strip())
self.weather[self.row_date] = self.daily_temps
self.daily_temps = {}
except Exception as error:
self.logger.error("scrape:data:%s", error)
def get_data(self):
"""Fetch the weather data and return it as a dictionary of dictionaries."""
current_date = datetime.now()
while not self.last_page:
try:
url = f"https://climate.weather.gc.ca/climate_data/daily_data_e.html?StationID=27174&timeframe=2&StartYear=1840&EndYear=2018&Day={current_date.day}&Year={current_date.year}&Month={current_date.month}"
with urllib.request.urlopen(url) as response:
html = response.read().decode()
self.feed(html)
# Subtracts one day from the current date and assigns the
# resulting date back to the current_date variable.
current_date -= timedelta(days=1)
except Exception as error:
self.logger.error("scrape:get_data:%s", error)
return self.weather
# Test program.
if __name__ == "__main__":
print_data = WeatherScraper().get_data()
for k, v in print_data.items():
print(k, v)
'''
A Module that creates and modifies a database. In this case, the data is weather information
scraped from a webpage.
'''
import sqlite3
import logging
from dateutil import parser
from scrape_weather import WeatherScraper
class DBOperations:
"""Class for performing operations on a SQLite database"""
def __init__(self, dbname):
"""
Constructor for DBOperations class.
Parameters:
- dbname: str, the name of the SQLite database file to use
"""
self.dbname = dbname
self.logger = logging.getLogger(__name__)
def initialize_db(self):
"""
Initialize the SQLite database by creating the weather_data table.
This method should be called every time the program runs.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('''
CREATE TABLE IF NOT EXISTS weather_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sample_date TEXT UNIQUE,
location TEXT,
min_temp REAL,
max_temp REAL,
avg_temp REAL
)
''')
self.logger.info("Initialized database successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while creating the table: %s", error)
def save_data(self, data):
"""
Save weather data to the SQLite database.
If the data already exists in the database, it will not be duplicated.
Parameters:
- data: dict, the weather data to save to the database. Must have keys for
sample_date, location, min_temp, max_temp, and avg_temp.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('''
INSERT OR IGNORE INTO weather_data
(sample_date, location, min_temp, max_temp, avg_temp)
VALUES (?, ?, ?, ?, ?)
''', (data['sample_date'], data['location'], data['min_temp'], data['max_temp'],
data['avg_temp']))
self.logger.info("Data saved successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while saving data to the database: %s", error)
def fetch_data(self, location):
"""
Fetch weather data from the SQLite database for a specified location.
Parameters:
- location: str, the location to fetch weather data for
Returns:
- A list of tuples containing the weather data for the specified location,
where each tuple has the format (sample_date, min_temp, max_temp, avg_temp).
Returns an empty list if no data is found for the specified location.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('''
SELECT sample_date, min_temp, max_temp, avg_temp
FROM weather_data
WHERE location = ?
''', (location,))
data = cursor.fetchall()
self.logger.info("Data fetched successfully.")
return data
except sqlite3.Error as error:
self.logger.error("An error occurred while fetching data from the database: %s",
error)
return []
def fetch_data_year_to_year(self, first_year, last_year):
'''
Fetch weather data from the SQLite database for a specified year range.
Parameters:
- first_year: int, the first year in the range.
- end_year: int, the final year in the range.
Returns:
- A list of data that falls in the range of years specified by the user.'''
month_data = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[],
7:[], 8:[], 9:[], 10:[], 11:[], 12:[]}
start_year = f'{first_year}-01-01'
end_year = f'{last_year}-01-01'
with self.get_cursor() as cursor:
try:
for row in cursor.execute('''
SELECT sample_date, avg_temp
FROM weather_data
WHERE sample_date BETWEEN ? AND ?
ORDER BY sample_date''',(start_year, end_year)):
month = parser.parse(row[0]).month
month_data[month].append(row[1])
self.logger.info("Data fetched successfully.")
return month_data
except sqlite3.Error as error:
self.logger.error("An error occurred while fetching data from the database: %s",
error)
return []
def fetch_data_single_month(self, month, year):
'''
Fetch weather data from the SQLite database for a specified month and year.
Parameters:
- month: int, the month to search for.
- year: int, the year to search for.
Returns:
- A list of temperatures for the month and year the user searched for'''
temperatures = {}
with self.get_cursor() as cursor:
try:
for row in cursor.execute('''
SELECT sample_date, avg_temp
FROM weather_data
WHERE sample_date LIKE ?||'-'||'0'||?||'-'||'%'
ORDER BY sample_date''',(year, month)):
temperatures[row[0]] = row[1]
return temperatures
except sqlite3.Error as error:
self.logger.error("An error occurred while fetching data from the database: %s",
error)
return []
def purge_data(self):
"""
Purge all weather data from the SQLite database.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('DELETE FROM weather_data')
self.logger.info("Data purged successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while purging data from the database: %s",
error)
def get_cursor(self):
"""
Get a cursor to use for database operations.
Returns:
- A cursor object for the SQLite database.
"""
return DBCM(self.dbname)
class DBCM:
'''
A class that represents a connection to a database.
'''
def __init__(self, dbname):
self.dbname = dbname
self.logger = logging.getLogger(__name__)
def __enter__(self):
try:
self.conn = sqlite3.connect(self.dbname)
self.cursor = self.conn.cursor()
self.logger.info("Connection to database established successfully.")
return self.cursor
except sqlite3.Error as error:
self.logger.error("An error occurred while connecting to the database: %s", error)
return None
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.conn.rollback()
else:
try:
self.conn.commit()
self.logger.info("Changes committed successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while committing changes to the database: %s",
error)
try:
self.cursor.close()
self.conn.close()
self.logger.info("Connection to database closed successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while closing the database connection: %s", error)
def main():
'''
The main method.
'''
# Initialize the database
data_base = DBOperations("mydatabase.db")
data_base.initialize_db()
# Get the weather data
scraper = WeatherScraper()
data = scraper.get_data()
# Process the data and prepare the rows
rows = []
for date, temps in data.items():
row = (
date,
"Winnipeg",
temps["Max"],
temps["Min"],
temps["Mean"]
)
rows.append(row)
# Save the data to the database
with data_base.get_cursor() as cursor:
try:
cursor.executemany('''
INSERT OR IGNORE INTO weather_data
(sample_date, location, min_temp, max_temp, avg_temp)
VALUES (?, ?, ?, ?, ?)
''', rows)
data_base.logger.info("Inserted %s rows into the database.", len(rows))
except sqlite3.Error as error:
data_base.logger.error("An error occurred while inserting data: %s", error)
if __name__ == '__main__':
main()
from plot_operations import PlotOperations
import sys
import logging
from datetime import datetime
from scrape_weather import WeatherScraper
from db_operations import DBOperations
from plot_operations import PlotOperations
class WeatherProcessor:
def __init__(self):
self.db_operations = DBOperations("../mydatabase.db")
self.create_plot = PlotOperations()
self.scrape_weather = WeatherScraper()
self.logger = logging.getLogger(__name__)
def main_menu(self):
while True:
print("\nWeather Data Processor")
print("1. Download a full set of weather data")
print("2. Update weather data")
print("3. Generate box plot based on year range")
print("4. Generate line plot based on a month and year")
print("5. Exit")
selection = input("Make a selection: ")
if selection == "1":
self.download_full_set()
input("Press Enter to continue...")
elif selection == "2":
self.update_weather_data()
input("Press Enter to continue...")
elif selection == "3":
self.generate_box_plot()
input("Press Enter to continue...")
elif selection == "4":
self.generate_line_plot()
input("Press Enter to continue...")
elif selection == "5":
sys.exit(0)
else:
print("Invalid choice. Select another option.")
#TODO
def download_full_set(self):
self.db_operations.initialize_db()
data = self.scrape_weather.get_data()
self.db_operations.save_data(data)
#TODO
def update_weather_data(self):
return None
def generate_box_plot(self):
start_year = input("Enter the year to start gathering data from: ")
end_year = input("Enter the year to end the search for data at: ")
data = self.db_operations.fetch_data_year_to_year(start_year, end_year)
self.create_plot.create_box_plot(start_year, end_year, data)
def generate_line_plot(self):
month = input("Enter a month to search for weather data (January = 1, February = 2): ")
year = input("Enter the year of the month you wish to view data from: ")
data = self.db_operations.fetch_data_single_month(month, year)
self.create_plot.create_line_plot(data)
if __name__ == '__main__':
processor = WeatherProcessor()
processor.main_menu()
|
af7a56af78ee25a4509ab67f49072781
|
{
"intermediate": 0.3676638603210449,
"beginner": 0.49274396896362305,
"expert": 0.13959212601184845
}
|
1,172
|
Нужно добавить код в макрос, чтобы он проверял изменения в столбцах на копируемых листах из книги, если были изменения , то он должен их добавить на Лист6, в строчки где содержится названия листов в столбце A. Sub MergeSheetsContainingAshan3()
Dim SourceWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim TargetWorkbook As Workbook
Dim TargetWorksheet As Worksheet
Dim LastRow As Long
Dim NextRow As Long
Dim ExistingSheetRow As Long
Dim SheetExists As Boolean
Dim ContentMatch As Boolean
' Открываем рабочую книгу-источник по ссылке в ячейке A1 на листе5
Set TargetWorkbook = ThisWorkbook
Set SourceWorkbook = Workbooks.Open(TargetWorkbook.Worksheets("Лист5").Range("A1").Value)
' Создаем новый лист “Лист6” в целевой рабочей книге
On Error Resume Next ' Если лист с таким именем уже существует, переходим к следующей строке
Set TargetWorksheet = TargetWorkbook.Worksheets("Лист6")
If TargetWorksheet Is Nothing Then
Set TargetWorksheet = TargetWorkbook.Worksheets.Add(After:=TargetWorkbook.Worksheets(TargetWorkbook.Worksheets.Count))
TargetWorksheet.Name = "Лист6"
End If
On Error GoTo 0
' Цикл копирования данных
For Each SourceWorksheet In SourceWorkbook.Worksheets
If InStr(1, SourceWorksheet.Name, "ашан", vbTextCompare) > 0 Then
' Проверяем наличие совпадений имени листа и содержимого
SheetExists = False
ContentMatch = False
For ExistingSheetRow = 1 To TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 1).End(xlUp).Row
If TargetWorksheet.Cells(ExistingSheetRow, 1).Value = SourceWorksheet.Name Then
SheetExists = True
If TargetWorksheet.Cells(ExistingSheetRow, 2).Value = SourceWorksheet.Cells(1, 1).Value Then
ContentMatch = True
Exit For
End If
End If
Next ExistingSheetRow
' Если имя листа и содержимое не совпадает, копируем данные
If Not SheetExists Or Not ContentMatch Then
' Находим следующую пустую строку в столбце B на “Лист6”
LastRow = TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 2).End(xlUp).Row + 1
' Копируем данные из найденного листа на “Лист6”
SourceWorksheet.UsedRange.Copy TargetWorksheet.Cells(LastRow, 2)
' Записываем имя листа в столбец A на той же строке, где были скопированы данные
NextRow = TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 2).End(xlUp).Row + 1
With TargetWorksheet.Range("A" & LastRow & ":A" & NextRow - 1)
.Value = SourceWorksheet.Name
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
End If
End If
Next SourceWorksheet
' Закрываем рабочую книгу-источник
SourceWorkbook.Close SaveChanges:=False
End Sub
|
bd03afeaf33e25029478102c2b68c703
|
{
"intermediate": 0.33682265877723694,
"beginner": 0.47477591037750244,
"expert": 0.18840143084526062
}
|
1,173
|
write me a page on html, with buttons and the ability to change the number, raising the level and adding characteristics, the name of the character is Fran, the character has the first level of 29HP and 17MP, each level receives 4 points to the characteristics of strength, endurance, dexterity, intelligence, magic, agility
|
dd270d03c8b13b4ed9570f00c2b50753
|
{
"intermediate": 0.3493584990501404,
"beginner": 0.29495227336883545,
"expert": 0.3556891977787018
}
|
1,174
|
Сделай так, чтобы пользователь мог просматривать изображения и описание в TDBGrid, потому что на данный момент данные в этих двух столбцах отображаются description как WIDEMEMO а содержимое image как BLOB. Придумай решение этой проблемы. C++ Builder 10.4, RAD STUDIO
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include "Unit108.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm108 *Form108;
TADOConnection *ADOConnection1;
TADOQuery *ADOQuery1;
TDBGrid *DBGrid1;
TDataSource *DataSource1;
//---------------------------------------------------------------------------
__fastcall TForm108::TForm108(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm108::FormCreate(TObject *Sender)
{
// создание базы данных / таблицы, если их ещё не существует
String s;
s = "CREATE DATABASE IF NOT EXISTS `catalog`";
ADOQuery1->SQL->Text = s;
ADOQuery1->ExecSQL();
s = "CREATE TABLE IF NOT EXISTS `catalog`.`products` (`ID` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `price` FLOAT(8, 2) NOT NULL, `description` TEXT NOT NULL, `image` LONGBLOB NOT NULL, PRIMARY KEY (`ID`))";
ADOQuery1->SQL->Text = s;
ADOQuery1->ExecSQL();
ADOQuery1->Close();
ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`";
ADOQuery1->Open();
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button2Click(TObject *Sender)
{
try
{
TFileStream *fs = new TFileStream(OpenPictureDialog1->FileName, fmOpenRead);
try
{
// Указываем параметры для запроса
ADOQuery1->SQL->Text = "INSERT INTO `catalog`.`products` (`name`, `price`, `description`, `image`) VALUES (:name, :price, :description, :image)";
ADOQuery1->Parameters->ParamByName("name")->Value = Edit1->Text;
ADOQuery1->Parameters->ParamByName("price")->Value = StrToFloat(Edit2->Text);
ADOQuery1->Parameters->ParamByName("description")->Value = Edit3->Text;
// Создаем поток для передачи изображения в базу данных
TMemoryStream *stream = new TMemoryStream();
try
{
stream->CopyFrom(fs, 0);
stream->Position = 0;
ADOQuery1->Parameters->ParamByName("image")->LoadFromStream(stream, ftBlob);
ADOQuery1->ExecSQL();
}
__finally
{
delete stream;
}
}
__finally
{
delete fs;
}
// Очистка полей ввода
Edit1->Clear();
Edit2->Clear();
Edit3->Clear();
// Очистка изображения
Image1->Picture->Assign(NULL);
// Обновление данных в таблице
ADOQuery1->Close();
ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`";
ADOQuery1->Open();
}
catch (Exception &e)
{
ShowMessage("Ошибка при добавлении товара: " + e.Message);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button3Click(TObject *Sender)
{
if (OpenPictureDialog1->Execute())
{
Image1->Picture->LoadFromFile(OpenPictureDialog1->FileName);
}
}
//---------------------------------------------------------------------------
|
be5de3dbc79e0edeb38151223fd51bc0
|
{
"intermediate": 0.37104377150535583,
"beginner": 0.48080533742904663,
"expert": 0.14815083146095276
}
|
1,175
|
Help me with my shiny app. First, let me show you my code:
EUCTR_shiny.R:
________
EUCTR_function <- function(input_var) {
[TRUNCATED]
# Save the workbook to the file
saveWorkbook(wb, file.path("outputs", paste0("EUCTR_", format(Sys.Date(), "%Y%m%d"), "_", format(Sys.time(), "%H%M"), ".xlsx")))
print(metadata, row.names = FALSE)
}
________________________
server.R:
__________________
library(shiny)
source("EUCTR_shiny.R")
shinyServer(function(input, output) {
# When the Start button is pressed
observeEvent(input$start, {
print("Start button pressed")
# Call the EUCTR_shiny script function and pass the input variable
output$shiny_output <- renderPrint({
EUCTR_function(input$input_var)
})
})
})
__________________________
ui.R:
_______________________
library(shiny)
# User interface definition
shinyUI(fluidPage(
# App title
titlePanel("EUCTR Automagic Scraper 🤖🪄"),
# Instruction text
p("This is a web scraper for the EU Clinical Trials Register."),
# Input box for a one-line variable
textInput("input_var", "Enter the URL for the search query:"),
# ‘Start’ button
actionButton("start", "Start"),
# Output console
verbatimTextOutput("shiny_output")
))
________________________________
I want the UI to include a real-time printing of what's printed inside the EUCTR_shiny.R script.
|
e286c3b9007b632cf8f807bc88b48941
|
{
"intermediate": 0.44430720806121826,
"beginner": 0.4325993061065674,
"expert": 0.12309353053569794
}
|
1,176
|
Help me with my shiny app. First, let me show you my code:
EUCTR_shiny.R:
________
EUCTR_function <- function(input_var, status_update_fun) {
[TRUNCATED]
# Update progress message
status_update_fun(cat(sprintf("\r%s%d/%d", progress_message, progress_index, total_codes)))
[TRUNCATED]
# Save the workbook to the file
saveWorkbook(wb, file.path("outputs", paste0("EUCTR_", format(Sys.Date(), "%Y%m%d"), "_", format(Sys.time(), "%H%M"), ".xlsx")))
status_update_fun(metadata)
}
________________________
server.R:
__________________
library(shiny)
source("EUCTR_shiny.R")
shinyServer(function(input, output) {
# Create a reactive value to store status messages
status_msg <- reactiveVal("")
# When the Start button is pressed
observeEvent(input$start, {
print("Start button pressed")
# Optional: startProgress for showing progress
withProgress(message = 'Processing, please wait...', {
# Call the EUCTR_shiny script function and pass the input variable and observe function for status update
EUCTR_function(isolate(input$input_var), function(msg) {
status_msg(paste0(status_msg(), msg, "\n"))
})
})
output$shiny_output <- renderPrint({
status_msg()
})
})
})__________________________
ui.R:
_______________________
library(shiny)
# User interface definition
shinyUI(fluidPage(
# App title
titlePanel("EUCTR Automagic Scraper 🤖🪄"),
# Instruction text
p("This is a web scraper for the EU Clinical Trials Register."),
# Input box for a one-line variable
textInput("input_var", "Enter the URL for the search query:"),
# ‘Start’ button
actionButton("start", "Start"),
# Output console
verbatimTextOutput("shiny_output")
))
________________________________
I want the UI to display a real-time message of what's on status_update_fun to inform the user of the progress.
|
f4e33944d0a9e5db69972617aeaa7616
|
{
"intermediate": 0.4521673917770386,
"beginner": 0.4282147288322449,
"expert": 0.11961791664361954
}
|
1,177
|
Hey GPT, I'm learning about the Hugging Face transformers library, and was wondering.. what are those "heads" they are talking about? For example, you pass a text to the tokenizer, or can pass multiple at once as an array/dictionary - but with the "QuestionAnswering" one, the tokenizer takes two text inputs for one query (in the tutorial dubbed "question" and "text", but it is the same tokenizer. How does this work? Is the "head" some kind of mechanism in this case, directing two inputs to the same model in sequence to get the expected result? Thanks.
From Hugging Face:
OPTForSequenceClassification:
"The OPT Model transformer with a sequence classification head on top (linear layer)."
OPTForQuestionAnswering:
"The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits)."
|
6a958a71a8bd5b62743247b4d29001d5
|
{
"intermediate": 0.5607644319534302,
"beginner": 0.036025770008563995,
"expert": 0.4032098352909088
}
|
1,178
|
rewrite this to be a function:
|
4d50dfca1686714c9359c9338d835991
|
{
"intermediate": 0.20021915435791016,
"beginner": 0.5984486937522888,
"expert": 0.20133215188980103
}
|
1,181
|
tell me how to incorporate you into a course
|
33c4941ae5151e0b80dfe2b332467589
|
{
"intermediate": 0.35658302903175354,
"beginner": 0.25271058082580566,
"expert": 0.3907063603401184
}
|
1,182
|
C++, RAD STUDIO.
Измени Edit3 на TMemo, сделай так, чтобы пользователь в Edit2 мог вводить только число и запятые. Добавь проверку на загруженно ли изображение (не _blank.png) при нажатии на кнопку добавить.
|
5ea5053844501b79ab78e3708bdeff61
|
{
"intermediate": 0.4456748962402344,
"beginner": 0.3306560218334198,
"expert": 0.2236691117286682
}
|
1,183
|
escribe el codigo en unity c# de esta clase: "Clase GameManager (MonoBehaviour):
- Variables: instance, faderObj, faderImg, gameOver, fadeSpeed, fadeTransparency, currentScene, async
- Métodos: Awake(), Update(), LoadScene(sceneName), ReloadScene(), OnLevelFinishedLoading(scene, mode), FadeOut(faderObject, fader), FadeIn(faderObject, fader), Load(sceneName), ActivateScene(), CurrentSceneName (propiedad), ExitGame(), ReturnToMenu()"
|
a5556b8452d657692a575bfcbbf716a7
|
{
"intermediate": 0.27355682849884033,
"beginner": 0.519368588924408,
"expert": 0.20707452297210693
}
|
1,184
|
You can create a method in the GameManager class to save the game data using PlayerPrefs. For example, you can create a SaveGame method that saves the current game progress: Clase GameManager (MonoBehaviour):
- Variables: instance, faderObj, faderImg, gameOver, fadeSpeed, fadeTransparency, currentScene, async
- Métodos: Awake(), Update(), LoadScene(sceneName), ReloadScene(), OnLevelFinishedLoading(scene, mode), FadeOut(faderObject, fader), FadeIn(faderObject, fader), Load(sceneName), ActivateScene(), CurrentSceneName (propiedad), ExitGame(), ReturnToMenu()
|
cff2f9e26f5c9c4b3f81da0c53eb3ef8
|
{
"intermediate": 0.38462039828300476,
"beginner": 0.4029976427555084,
"expert": 0.2123819887638092
}
|
1,185
|
C++ BUILDER, RAD STUDIO IDE.
Задание: Замени в коде Edit3 на TMemo, адаптируй использование Memo1.
Добавь проверку на пустые поля Edit1, Memo1, Edit3.
Код:
|
972d7586e82ce44c6b52bdebe51bdff9
|
{
"intermediate": 0.40439409017562866,
"beginner": 0.2831701934337616,
"expert": 0.31243568658828735
}
|
1,186
|
Analyze similar existing code in Unity C# for swapping positions in 2D match-3 games
|
116ea9ef824b8f6f23f3846fa28b604b
|
{
"intermediate": 0.5506443381309509,
"beginner": 0.27987125515937805,
"expert": 0.16948440670967102
}
|
1,187
|
Hey, can you explain the following code to me? It's inference code for "GPTQ-for-LLaMa", a branch of GPTQ for Meta's LLM so it can be quantized to 4 bit precision. I am not really interested in quantizing myself, but I'd like to know how I can run inference myself using PyTorch/HF Transformers on such a 4-bit quantized LLaMA model. Thanks!
import time
import torch
import torch.nn as nn
from gptq import *
from modelutils import *
import quant
from transformers import AutoTokenizer
DEV = torch.device('cuda:0')
def get_llama(model):
import torch
def skip(*args, **kwargs):
pass
torch.nn.init.kaiming_uniform_ = skip
torch.nn.init.uniform_ = skip
torch.nn.init.normal_ = skip
from transformers import LlamaForCausalLM
model = LlamaForCausalLM.from_pretrained(model, torch_dtype='auto')
model.seqlen = 2048
return model
def load_quant(model, checkpoint, wbits, groupsize = -1, fused_mlp = True, eval=True, warmup_autotune = True):
from transformers import LlamaConfig, LlamaForCausalLM
config = LlamaConfig.from_pretrained(model)
def noop(*args, **kwargs):
pass
torch.nn.init.kaiming_uniform_ = noop
torch.nn.init.uniform_ = noop
torch.nn.init.normal_ = noop
torch.set_default_dtype(torch.half)
transformers.modeling_utils._init_weights = False
torch.set_default_dtype(torch.half)
model = LlamaForCausalLM(config)
torch.set_default_dtype(torch.float)
if eval:
model = model.eval()
layers = find_layers(model)
for name in ['lm_head']:
if name in layers:
del layers[name]
quant.make_quant_linear(model, layers, wbits, groupsize)
del layers
print('Loading model ...')
if checkpoint.endswith('.safetensors'):
from safetensors.torch import load_file as safe_load
model.load_state_dict(safe_load(checkpoint), strict = False)
else:
model.load_state_dict(torch.load(checkpoint), strict = False)
quant.make_quant_attn(model)
if eval and fused_mlp:
quant.make_fused_mlp(model)
if warmup_autotune:
quant.autotune_warmup_linear(model,transpose=not(eval))
if eval and fused_mlp:
quant.autotune_warmup_fused(model)
model.seqlen = 2048
print('Done.')
return model
if __name__ == '__main__':
import argparse
from datautils import *
parser = argparse.ArgumentParser()
parser.add_argument(
'model', type=str,
help='llama model to load'
)
parser.add_argument(
'--wbits', type=int, default=16, choices=[2, 3, 4, 8, 16],
help='#bits to use for quantization; use 16 for evaluating base model.'
)
parser.add_argument(
'--groupsize', type=int, default=-1,
help='Groupsize to use for quantization; default uses full row.'
)
parser.add_argument(
'--load', type=str, default='',
help='Load quantized model.'
)
parser.add_argument(
'--text', type=str,
help='input text'
)
parser.add_argument(
'--min_length', type=int, default=10,
help='The minimum length of the sequence to be generated.'
)
parser.add_argument(
'--max_length', type=int, default=50,
help='The maximum length of the sequence to be generated.'
)
parser.add_argument(
'--top_p', type=float , default=0.95,
help='If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.'
)
parser.add_argument(
'--temperature', type=float, default=0.8,
help='The value used to module the next token probabilities.'
)
parser.add_argument(
'--device', type=int, default=-1,
help='The device used to load the model when using safetensors. Default device is "cpu" or specify, 0,1,2,3,... for GPU device.'
)
args = parser.parse_args()
if type(args.load) is not str:
args.load = args.load.as_posix()
if args.load:
model = load_quant(args.model, args.load, args.wbits, args.groupsize, args.device)
else:
model = get_llama(args.model)
model.eval()
model.to(DEV)
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=False)
input_ids = tokenizer.encode(args.text, return_tensors="pt").to(DEV)
with torch.no_grad():
generated_ids = model.generate(
input_ids,
do_sample=True,
min_length=args.min_length,
max_length=args.max_length,
top_p=args.top_p,
temperature=args.temperature,
)
print(tokenizer.decode([el.item() for el in generated_ids[0]]))
|
00671a0ff79723730eb8cc577b887051
|
{
"intermediate": 0.39677882194519043,
"beginner": 0.4426107704639435,
"expert": 0.1606103926897049
}
|
1,188
|
CSCI 1100 — Computer Science 1 Homework 8
Bears, Berries and Tourists Redux: Classes
Overview
This homework is worth 100 points toward your overall homework grade, and is due Wednesday,
April 26, 2022 at 11:59:59 pm. It has three parts. The first two are not worth many points, and
may end up being worth 0. They are mainly there to give you information to help you debug your
solution. Please download hw8_files.zip. and unzip it into the directory for your HW8. You will
find data files and sample outputs for each of the parts.
The goal of this assignment is to work with classes. You will be asked to write a simulation engine
and use classes to encapsulate data and functionality. You will have a lot of design choices to make.
While we have done simulations before, this one will be more complex. It is especially important
that you start slowly, build a program that works for simple cases, test it and then add more
complexity. We will provide test cases of increasing difficulty. Make sure you develop slowly and
test throughly.
Submission Instructions
In this homework, for the first time, you will be submitting multiple files to Submitty that together
comprise a single program.
Please follow these instructions carefully.
Each of Part 1, Part 2 and Part 3 will require you to to write a main program: hw8_part1.py,
hw8_part2.py and hw8_part3.py, respectively. You must also submit three modules per part in
addition to this main file, each of which encapsulates a class. The first is a file called BerryField.py
that contains your berry class, a file called Bear.py that contains your Bear class and a file called
Tourist.py that contains your Tourist class.
As always, make sure you follow the program structure guidelines. You will be graded on good
program structure as well as program correctness.
Remember as well that we will be continuing to test homeworks for similarity. So,
follow our guidelines for the acceptable levels of collaboration. You can download the
guidelines from the resources section in the Course Materials if you need a refresher.
We take this very seriously and will not hesitate to impose penalties when warranted.
Getting Started
You will need to write at least three classes for this assignment corresponding to a BerryField, a
Bear and a Tourist. We are going to give you a lot of freedom in how you organize these three
classes, but each class must have at least an initializer and a string method. Additional methods
are up to you. Each of the classes is described below.
BerryField
The berry field must maintain and manage the location of berries as a square Row X Column grid
with (0,0) being the upper left corner and (N-1, N-1) being the lower right corner. Each space
holds 0-10 berry units.
The initializer class must, minimally, be able to take in a grid of values (think of our Sodoku
lab) and use it to create a berry field with the values contained in the grid.
The string function must, minimally, be able to generate a string of the current state of the
berry patch. Each block in the grid must be formatted with the "{:>4}" format specifier. If
there is a bear at the location the grid should have a "B", if there is a tourist the grid should
have a "T", and if there is both a bear and a tourist the grid should have an "X". If there is
neither a bear nor a tourist, it should have the number of berries at the location.
Berries grow. The berry class must provide a way to grow the berry field. When the berries
grow, any location with a value 1 <= number of berries < 10 will gain an extra berry.
Berries also spread. Any location with no berries that is adjacent to a location with 10 berries
will get 1 berry during the grow operation.
Bear
Each bear has a location and a direction in which they are walking. Bears are also very hungry. In
your program, You must manage 2 lists of bears. The first list are those bears that are currently
walking in the field. The second is a queue of bears waiting to enter the field.
The initializer class must, minimally, be able to take in a row and column location and a
direction of travel.
The string function must, minimally, be able to print out the location and direction of travel
for the bear and if the bear is asleep.
Bears can walk North (N), South (S), East (E), West (W), NorthEast (NE), NorthWest (NW),
SouthEast (SE), or SouthWest (SW). Once a bear starts walking in a direction it never turns.
Bears are always hungry. Every turn, unless there is tourist on the same spot, the bear eats
all the berries available on the space and then moves in its current direction to the next space.
This continues during the current turn until the bear eats 30 berries or runs into a tourist.
For the special case of a bear and a tourist being in the same place during a turn, the bear
does not eat any berries, but the tourist mysteriously disappears and the bear falls asleep for
three turns.
Once a bear reaches the boundary of the field (its row or column becomes -1 or N), it is no
longer walking in the field and need not be considered any longer.
Tourist
Each tourist has a location. Just like with bears, you must someplace maintain a list of tourists
currently in the field and a queue of tourists waiting to enter the field.
The initializer class must, minimally, be able to take in a row and column location.
Tourists see a bear if the bear is within 4 of their current position.
The string function must, minimally, be able to print out the location of the tourist and how
many turns have passed since they have seen a bear.
Tourists stand and watch. They do not move, but they will leave the field if
1. Three turns pass without them seeing a bear they get bored and go home.
2. They can see three bears at the same time they get scared and go home
3. A bear runs into them they mysteriously disappear and can no longer be found in the
field.
Execution
Remember to get hw8_files_F19.zip from the Course Materials section of Submitty. It has two
sample input files and the expected output for your program.
For this homework all of the data required to initialize your classes and program can be found in
json files. Each of your 3 parts should start by asking for the name of the json file, reading the
file, and then creating the objects you need based on the data read. The code below will help you
with this.
f = open("bears_and_berries_1.json")
data = json.loads(f.read())
print(data["berry_field"])
print(data["active_bears"])
print(data["reserve_bears"])
print(data["active_tourists"])
print(data["reserve_tourists"])
You will see that field in a list of lists where each [row][column] value is the number of berries
at that location; the "active_bears" and "reserve_bears" entries are lists of three-tuples (row,
column, direction) defining the bears; and the "active_tourists" and "reserve_tourists"
entries are lists of two-tuples (row, column) defining the tourists.
Part 1
In part one, read the json file, create your objects and then simply report on the initial state of the
simulation by printing out the berry field, active bears, and active tourists. Name your program
hw8_part1.py and submit it along with the three classes you developed.
Part 2
In part two, start off the same by reading the json file and create your objects and again print out
the initial state of the simulation. Then run five turns of the simulation by:
Growing the berries
Moving the bears
Checking on the tourists
Print out the state of the simulation
Do not worry about the reserve bears or reserve tourists entering the field, but report on any
tourists or bears that leave. Name your program hw8_part2.py and submit it along with the three
classes you developed.
Part 3
In part three, do everthing you did in part 2, but make the following changes.
After checking on the tourists, if there are still bears in the reserve queue and at least 500
berries, add the next reserve bear to the active bears.
Then, if there is are still tourists in the reserve queue and at least 1 active bear, add the next
reserve tourist to the field.
Instead of stopping after 5 turns, run until there are no more bears on the field and no more
bears in the reserve list; or if there are no more bears on the field and no more berries.
Finally, instead of reporting status every turn, report it every 5 turns and then again when
the simulation ends.
As you go, report on any tourists or bears that leave or enter the field. Name your program
hw8_part3.py and submit it along with the three classes you developed.'
|
dbf3da6c90731fde6abf100c4ab1b1b0
|
{
"intermediate": 0.37033259868621826,
"beginner": 0.4572488069534302,
"expert": 0.17241863906383514
}
|
1,189
|
python script that uses beautifulsoup to write the name, price and url to a .csv on https://www.customsneakers.ch/collections/alle-sneaker?page=1 from ?page=1 to ?page=5
|
12902020da0187ce2a106f076ceee8d8
|
{
"intermediate": 0.3765965700149536,
"beginner": 0.22766202688217163,
"expert": 0.39574134349823
}
|
1,190
|
python script that uses beautifulsoup to write the name, price and url to a .csv on https://www.customsneakers.ch/collections/alle-sneaker?page=1 from ?page=1 to ?page=5
|
2856f19fc9a8af2d987e7abdcd7bb439
|
{
"intermediate": 0.3765965700149536,
"beginner": 0.22766202688217163,
"expert": 0.39574134349823
}
|
1,191
|
python script that uses beautifulsoup to write the name, price and url to a .csv on https://www.customsneakers.ch/collections/alle-sneaker?page=1 from ?page=1 to ?page=5
|
cbc0f1ea44e8fe69f5eef83aa865aee2
|
{
"intermediate": 0.3765965700149536,
"beginner": 0.22766202688217163,
"expert": 0.39574134349823
}
|
1,192
|
python script that uses beautifulsoup to write the name, price and url to a .csv on https://www.customsneakers.ch/collections/alle-sneaker?page=1 from ?page=1 to ?page=5
|
0a43263cb81993d23fe5721decacbc58
|
{
"intermediate": 0.3765965700149536,
"beginner": 0.22766202688217163,
"expert": 0.39574134349823
}
|
1,193
|
python script that uses beautifulsoup to write the name, price and url to a .csv on https://www.customsneakers.ch/collections/alle-sneaker?page=1 from ?page=1 to ?page=5
|
f6acfbc7fdedb09c03ccaf98fbc5f4ad
|
{
"intermediate": 0.3765965700149536,
"beginner": 0.22766202688217163,
"expert": 0.39574134349823
}
|
1,194
|
if response.result.isSuccess {
let data = response.result.value as! NSString
print(data);
let contacts = data.components(separatedBy: "|")
let userDefault = UserDefaults.init(suiteName: "group.incomingCall")
// let phoneNumbersDict = userDefault?.object(forKey: "PhoneNumbers") as! NSDictionary
let dict = NSMutableDictionary()
dict.setObject("ms zh", forKey: "+8618576425847" as NSCopying)
dict.setObject("mss y", forKey: "+8618576425848" as NSCopying)
dict.setObject("mss xxx", forKey: "8618576425849" as NSCopying)
for i in 0 ..< contacts.count {
let contact = contacts[i].components(separatedBy: ",")
let name = contact[0]
if contact.count > 1 {
var number = String(contact[1].characters.filter{$0 != " "})
if number.range(of: "+86") != nil {
if (!self.isTelNumber(num: number.substring(from: number.characters.index(number.startIndex, offsetBy: 3)) as NSString)) {
continue
}
}
if number.isEmpty || !number.characters.contains("+") || number.characters.count < 10 {
continue
}
if number.range(of: "-") != nil {
number = number.replacingOccurrences(of: "-", with: "")
}
number = number.replacingOccurrences(of: " ", with: "")
dict.setObject(name, forKey: number as NSCopying)
}
}
userDefault?.setValue(dict, forKey: "PhoneNumbers")
userDefault?.synchronize()
self.reloadCallExtension(count: contacts.count, name: groups[0].name)
}if response.result.isSuccess {
let data = response.result.value as! NSString
print(data);
let contacts = data.components(separatedBy: "|")
let userDefault = UserDefaults.init(suiteName: "group.incomingCall")
// let phoneNumbersDict = userDefault?.object(forKey: "PhoneNumbers") as! NSDictionary
let dict = NSMutableDictionary()
dict.setObject("ms zh", forKey: "+8618576425847" as NSCopying)
dict.setObject("mss y", forKey: "+8618576425848" as NSCopying)
dict.setObject("mss xxx", forKey: "8618576425849" as NSCopying)
for i in 0 ..< contacts.count {
let contact = contacts[i].components(separatedBy: ",")
let name = contact[0]
if contact.count > 1 {
var number = String(contact[1].characters.filter{$0 != " "})
if number.range(of: "+86") != nil {
if (!self.isTelNumber(num: number.substring(from: number.characters.index(number.startIndex, offsetBy: 3)) as NSString)) {
continue
}
}
if number.isEmpty || !number.characters.contains("+") || number.characters.count < 10 {
continue
}
if number.range(of: "-") != nil {
number = number.replacingOccurrences(of: "-", with: "")
}
number = number.replacingOccurrences(of: " ", with: "")
dict.setObject(name, forKey: number as NSCopying)
}
}
userDefault?.setValue(dict, forKey: "PhoneNumbers")
userDefault?.synchronize()
self.reloadCallExtension(count: contacts.count, name: groups[0].name)
}
|
68a7012b03b9f3b42b5807cd2ee257e4
|
{
"intermediate": 0.37098604440689087,
"beginner": 0.5020914673805237,
"expert": 0.12692245841026306
}
|
1,195
|
make it that the url used is https://www.customsneakers.ch/collections/alle-sneaker?page=1 and the ?page=5 goes from 1 to 5
def get_sneaker_data(base_url, page_number):
url = f"{base_url}?page={page_number}“
response = requests.get(url)
soup = BeautifulSoup(response.content, ‘html.parser’)
sneaker_data = []
for product in soup.find_all(‘div’, class_=‘productgrid–item’):
name = product.find(‘div’, class_=‘product_item–title’).text.strip()
price = product.find(‘div’, class_=‘price_item–regular’).text.strip()
link = product.find(‘a’, class_='productgrid–imglink’)[‘href’]
sneaker_data.append((name, price, link))
return sneaker_data
|
917fe918435cdd05483826364d5a5cd2
|
{
"intermediate": 0.40231019258499146,
"beginner": 0.36252862215042114,
"expert": 0.23516122996807098
}
|
1,196
|
what is m3u8 format
|
be04b7e0951d9f3d08fde47d8d7291da
|
{
"intermediate": 0.2658047378063202,
"beginner": 0.4461957812309265,
"expert": 0.28799939155578613
}
|
1,197
|
Como le agrego a este codigo una función que me de una pitido cuando no aparece una pregunta en Chegg para contestar?var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator"throw"); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
let timerId;
let enabled = false;
console.log(“Chegg Auto Refresh is running”);
// function to refresh the page after 5 seconds if the content is found
function refreshPage(tab) {
return __awaiter(this, void 0, void 0, function* () {
const results = yield chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => {
const contentFound = !!document.querySelector(“.sc-kMizLa”);
return contentFound;
},
});
// console.log(“yooo!: “, results);
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
return;
}
const contentFound = results[0].result;
// If the content is not found, print question found to console
if (contentFound) {
console.log(“refreshing”);
// refresh the page after 5 seconds
// timerId = setTimeout(() => {
chrome.tabs.reload(tab.id);
// }, 5000);
}
// else if content is found, refresh the page after 5 seconds
else {
// console.log(“Content not found”);
// If the content is found, clear the timer
clearTimeout(timerId);
chrome.notifications.create(””, {
title: “Found a question for you!”,
message: “There is a question waiting for you!”,
iconUrl: “/images/chegg-48.png”,
type: “basic”,
});
enabled = false;
// alert the user that the content is not found
}
});
}
// // listen for tab activation
// chrome.tabs.onActivated.addListener(async function (activeInfo) {
// if (!enabled) return;
// let queryOptions = { active: true, currentWindow: true };
// let [tab] = await chrome.tabs.query(queryOptions);
// if (!tab) {
// // console.log(“no tab found”);
// return;
// }
// if (!tab.url?.startsWith(“https://expert.chegg.com/expertqna”)) {
// // console.log(“Not Chegg”);
// return;
// }
// refreshPage(tab);
// });
// listen for tab refresh
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (!enabled)
return;
if (!((_a = tab.url) === null || _a === void 0 ? void 0 : _a.startsWith(“https://expert.chegg.com/expertqna”))) {
// console.log(“Not Chegg”);
return;
}
if (changeInfo.status === “complete”) {
// console.log(“tab updated”, changeInfo, tab);
setTimeout(() => {
refreshPage(tab);
}, 10000);
}
});
});
// set enabled to true if the toggle is checked and false if it is not
chrome.storage.sync.get(“enabled”, ({ enabled }) => {
if (enabled) {
enabled = true;
}
else {
enabled = false;
}
});
// Add a message listener to listen for messages from popup.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
return __awaiter(this, void 0, void 0, function* () {
// If the request action is “runScript”
if (request.action == true) {
console.log(“enabled 3”);
enabled = true;
// Get the active tab
const [tab] = yield chrome.tabs.query({
active: true,
currentWindow: true,
});
console.log(“tab”, tab);
if (!tab)
return;
refreshPage(tab);
}
else {
console.log(“disabled”);
enabled = false;
}
sendResponse({ result: “success” });
return true;
});
});
//# sourceMappingURL=background.js.map
|
53139ca9f545c3c3e9eb765c6b4451ec
|
{
"intermediate": 0.3526522219181061,
"beginner": 0.41526442766189575,
"expert": 0.23208335041999817
}
|
1,198
|
what is m3u8 format
|
8125069621a9c60cac2337dea97c89e8
|
{
"intermediate": 0.2658047378063202,
"beginner": 0.4461957812309265,
"expert": 0.28799939155578613
}
|
1,199
|
fscanf obtains spaces and line breaks
|
b3c667df1ee14174e53a21fe83cfb182
|
{
"intermediate": 0.3669750690460205,
"beginner": 0.2652395963668823,
"expert": 0.36778536438941956
}
|
1,200
|
Удалить дубликаты строчки в Лист6 при проверке названий в столбце A.
Sub MergeSheetsContainingAshan4()
Dim SourceWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim TargetWorkbook As Workbook
Dim TargetWorksheet As Worksheet
Dim LastRow As Long
Dim NextRow As Long
Dim ExistingSheetRow As Long
Dim SheetExists As Boolean
Dim ContentMatch As Boolean
' Открываем рабочую книгу-источник по ссылке в ячейке A1 на листе5
Set TargetWorkbook = ThisWorkbook
Set SourceWorkbook = Workbooks.Open(TargetWorkbook.Worksheets("Лист5").Range("A1").Value)
' Создаем новый лист “Лист6” в целевой рабочей книге
On Error Resume Next ' Если лист с таким именем уже существует, переходим к следующей строке
Set TargetWorksheet = TargetWorkbook.Worksheets("Лист6")
If TargetWorksheet Is Nothing Then
Set TargetWorksheet = TargetWorkbook.Worksheets.Add(After:=TargetWorkbook.Worksheets(TargetWorkbook.Worksheets.Count))
TargetWorksheet.Name = "Лист6"
End If
On Error GoTo 0
' Цикл копирования данных
For Each SourceWorksheet In SourceWorkbook.Worksheets
If InStr(1, SourceWorksheet.Name, "ашан", vbTextCompare) > 0 Then
' Проверяем наличие совпадений имени листа и содержимого
SheetExists = False
ContentMatch = False
For ExistingSheetRow = 1 To TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 1).End(xlUp).Row
If TargetWorksheet.Cells(ExistingSheetRow, 1).Value = SourceWorksheet.Name Then
SheetExists = True
' Сравниваем содержимое столбцов
ContentMatch = True
For col = 1 To SourceWorksheet.UsedRange.Columns.Count
If SourceWorksheet.Cells(1, col).Value <> TargetWorksheet.Cells(ExistingSheetRow, col + 1).Value Then
ContentMatch = False
Exit For
End If
Next col
If ContentMatch Then Exit For
End If
Next ExistingSheetRow
' Если имя листа и содержимое не совпадает, копируем данные
If Not SheetExists Or Not ContentMatch Then
' Находим следующую пустую строку в столбце B на “Лист6”
LastRow = TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 2).End(xlUp).Row + 1
' Копируем данные из найденного листа на “Лист6”
SourceWorksheet.UsedRange.Copy TargetWorksheet.Cells(LastRow, 2)
' Записываем имя листа в столбец A на той же строке, где были скопированы данные
NextRow = TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 2).End(xlUp).Row + 1
With TargetWorksheet.Range("A" & LastRow & ":A" & NextRow - 1)
.Value = SourceWorksheet.Name
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
End If
End If
Next SourceWorksheet
' Закрываем рабочую книгу-источник
SourceWorkbook.Close SaveChanges:=False
End Sub
|
9d000a799d036c3bf7630dcc0aa4ddd8
|
{
"intermediate": 0.3980400264263153,
"beginner": 0.37884026765823364,
"expert": 0.22311966121196747
}
|
1,201
|
async_hooks.executionAsyncId()
|
2d1e2e2e8cf5199c33e3e030b3d9b43d
|
{
"intermediate": 0.4226439893245697,
"beginner": 0.22715869545936584,
"expert": 0.35019734501838684
}
|
1,202
|
is there is a way to dial a code on an Android device from a C# Windows application that doesn’t require ADB or ADB bridge?
|
ddfa23ca4270ec4216bda7f15d3e2cb1
|
{
"intermediate": 0.6812052130699158,
"beginner": 0.12804056704044342,
"expert": 0.190754234790802
}
|
1,203
|
For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order. Use while loops and no quotations in the print statement
|
88df586660143d441cea37207c010998
|
{
"intermediate": 0.1367834210395813,
"beginner": 0.7727622985839844,
"expert": 0.09045427292585373
}
|
1,204
|
Here is AlexNet and train function implementation . class AlexNet_Modified(nn.Module):
def __init__(self):
super(AlexNet_Modified, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 96, kernel_size=11, stride=4),
nn.BatchNorm2d(96),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(96, 256, kernel_size=5, padding=2),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(256, 384, kernel_size=3, padding=1),
nn.BatchNorm2d(384),
nn.ReLU(inplace=True),
nn.Conv2d(384, 384, kernel_size=3, padding=1),
nn.BatchNorm2d(384),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
self.classifier = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(256 * 6 * 6, 4096),
nn.BatchNorm1d(4096),
nn.ReLU(inplace=True),
nn.Dropout(p=0.3),
nn.Linear(4096, 4096),
nn.BatchNorm1d(4096),
nn.ReLU(inplace=True),
nn.Linear(4096, len(folder_names)),
)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x and def train_model(model, device, train_loader, test_loader, epochs = None, learning_rate = None, optimization_technique = None, patience=None, scheduler_patience=None, num_batches = None, **kwargs):
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience:
scheduler = ReduceLROnPlateau(optimizer, 'min', patience=scheduler_patience, verbose=True)
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
best_loss = float('inf')
stopping_counter = 0
for epoch in range(epochs):
running_train_loss = 0.0
running_train_acc = 0
num_samples_train = 0
for X_batch, y_batch in train_loader:
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
optimizer.zero_grad()
y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
loss.backward()
optimizer.step()
running_train_loss += loss.item()
running_train_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item()
num_samples_train += y_batch.size(0)
train_losses.append(running_train_loss / len(train_loader))
train_accuracies.append(running_train_acc / num_samples_train)
# Testing segment
running_test_loss = 0.0
running_test_acc = 0
num_samples_test = 0
with torch.no_grad():
for X_batch, y_batch in test_loader:
X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True)
y_pred = model(X_batch)
loss = criterion(y_pred, y_batch)
running_test_loss += loss.item()
running_test_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item()
num_samples_test += y_batch.size(0)
test_losses.append(running_test_loss / len(test_loader))
test_accuracies.append(running_test_acc / num_samples_test)
# Early stopping
if optimization_technique == 'early_stopping' and patience:
if test_losses[-1] < best_loss:
best_loss = test_losses[-1]
stopping_counter = 0
else:
stopping_counter += 1
if stopping_counter > patience:
print(f"Early stopping at epoch {epoch+1}/{epochs}")
break
# Learning rate scheduler
if optimization_technique == 'learning_rate_scheduler' and scheduler_patience and scheduler:
scheduler.step(test_losses[-1])
print(f"Epoch: {epoch+1}/{epochs}, Training Loss: {train_losses[-1]:.4f}, Test Loss: {test_losses[-1]:.4f}, Training Accuracy: {train_accuracies[-1]: .4f}, Test Accuracy: {test_accuracies[-1]:.4f}")
return train_losses, train_accuracies, test_losses, test_accuracies. Now improve the AlextNEt to perform better for a SVNH dataset and also I'm using data augmentation for SVHN task. Can you also implement steps to import the dataset and also use the code to train the modified model on SVHN dataset.
|
e5f0b5370f25756620a24998df781f89
|
{
"intermediate": 0.2457571029663086,
"beginner": 0.3492105305194855,
"expert": 0.40503233671188354
}
|
1,205
|
Please explain how rust can cascade into lvvm
|
05d40796d973f93dd907c8f650c0d22e
|
{
"intermediate": 0.4201832115650177,
"beginner": 0.17694570124149323,
"expert": 0.40287116169929504
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.