row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
30,413
|
In R find the rows where column 'country_of_bean_origin' =='Tabago'
|
a6248a2f4fce24a00a7e2271456f26ee
|
{
"intermediate": 0.374075710773468,
"beginner": 0.2182067185640335,
"expert": 0.40771758556365967
}
|
30,414
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MarioController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
public float ladderClimbSpeed = 2f;
public int maxHealth = 3;
private int currentHealth;
private bool grounded;
private bool onLadder;
private bool climbingLadder;
private Vector2 direction;
private Rigidbody2D rb2d;
private new Collider2D collider;
private Collider2D[] results;
private void Awake()
{
rb2d = GetComponent<Rigidbody2D>();
collider = GetComponent<Collider2D>();
results = new Collider2D[4];
}
private void Start()
{
currentHealth = maxHealth;
}
private void CheckCollision()
{
grounded = false;
onLadder = false;
Vector2 size = collider.bounds.size;
size.y += 0.1f;
size.x /= 2f;
int amount = Physics2D.OverlapBoxNonAlloc(transform.position, size, 0f, results);
for (int i = 0; i < amount; i++)
{
GameObject hit = results[i].gameObject;
if (hit.layer == LayerMask.NameToLayer("Platform"))
{
grounded = hit.transform.position.y < (transform.position.y - 0.5f);
}
else if (hit.layer == LayerMask.NameToLayer("Ladder"))
{
onLadder = true;
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel"))
{
// If Mario collides with a barrel, decrease health and reset the scene
currentHealth = 0;
ResetScene();
}
}
private void ResetScene()
{
// Reload the current scene
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
private void Update()
{
CheckCollision();
if (grounded && Input.GetButtonDown("Jump"))
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce);
}
float movement = Input.GetAxis("Horizontal");
if (grounded)
{
direction.y = Mathf.Max(direction.y, -1f);
climbingLadder = false;
}
if (onLadder && Input.GetButton("Vertical"))
{
// Climb the ladder vertically
climbingLadder = true;
float climbDirection = Input.GetAxis("Vertical");
rb2d.velocity = new Vector2(0, climbDirection * ladderClimbSpeed);
rb2d.gravityScale = 0f;
}
else if (climbingLadder)
{
rb2d.gravityScale = 1f;
rb2d.velocity = new Vector2(rb2d.velocity.x, 0f);
rb2d.constraints = RigidbodyConstraints2D.FreezePositionX;
}
else
{
rb2d.gravityScale = 1f;
rb2d.constraints = RigidbodyConstraints2D.FreezeRotation;
}
rb2d.velocity = new Vector2(movement * moveSpeed, rb2d.velocity.y);
if (movement > 0)
{
transform.localScale = new Vector3(1f, 1f, 1f);
}
else if (movement < 0)
{
transform.localScale = new Vector3(-1f, 1f, 1f);
}
}
}
make it so if mario collides with the win gameobject (set to win layer) the scene will reset
|
34f9500fc9b162f681cda427ba8badce
|
{
"intermediate": 0.2979227304458618,
"beginner": 0.5409865379333496,
"expert": 0.161090686917305
}
|
30,415
|
как залогиниться с помощью aiohttp, asyncio URL Запроса:
https://xms.miatel.ru/oauth/token
Метод Запроса:
POST
Код Статуса:
201 Created
Удаленный Адрес:
91.206.88.70:443
Правило Для URL Перехода:
no-referrer
Access-Control-Allow-Origin:
*
Access-Control-Expose-Headers:
Request-Id
Content-Length:
295
Content-Type:
application/cbor
Date:
Wed, 08 Nov 2023 08:01:21 GMT
Request-Id:
651100ae3113e087cd17fca263dc0e1f
Request-Time:
0.030
Server:
nginx
Vary:
Origin
:authority:
xms.miatel.ru
:method:
POST
:path:
/oauth/token
:scheme:
https
Accept:
application/cbor
Accept-Encoding:
gzip, deflate, br
Accept-Language:
ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Content-Length:
53
Content-Type:
application/cbor
Origin:
https://xms.miatel.ru
Sec-Ch-Ua:
“Google Chrome”;v=“119”, “Chromium”;v=“119”, “Not?A_Brand”;v=“24”
Sec-Ch-Ua-Mobile:
?0
Sec-Ch-Ua-Platform:
“Windows”
Sec-Fetch-Dest:
empty
Sec-Fetch-Mode:
cors
Sec-Fetch-Site:
same-origin
User-Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36
запрос сведений о полезной нагрузке £!#<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>$tzThiRDvQ6KOQa8QhzJsy
|
9b094c4614720e02d74f6f50da1d6a66
|
{
"intermediate": 0.3865260183811188,
"beginner": 0.3153882324695587,
"expert": 0.2980857491493225
}
|
30,416
|
In my Active worksheet, I have the following code;
If Target.Address = "$B$3" Then
Sheets("Job Request").Activate
End If
What I would like to do is this, when the code runs
then the value of cell A1 in sheet 'Job Request'
becomes the value of B1 from my Active Sheet.
Something like this;
If Target.Address = "$B$3" Then
ActiveSheet.Range("B2").copy values only
Sheets("Job Request").Activate
ActiveSheet.Range("A1").paste values only
End If
How can I do this
|
05204949c6cdeea533e209fd2f469e60
|
{
"intermediate": 0.4939710199832916,
"beginner": 0.3141683042049408,
"expert": 0.19186069071292877
}
|
30,417
|
In my Active worksheet, I have the following code;
If Target.Address = "$B$3" Then
Sheets("Job Request").Activate
End If
What I would like to do is this, when the code runs
then the value of cell A1 in sheet 'Job Request'
becomes the value of B1 from my Active Sheet.
Something like this;
If Target.Address = "$B$3" Then
ActiveSheet.Range("B2").copy values only
Sheets("Job Request").Activate
ActiveSheet.Range("A1").paste values only
End If
How can I do this
|
468950ebc4d961daf0b0e0f85549d2bf
|
{
"intermediate": 0.4939710199832916,
"beginner": 0.3141683042049408,
"expert": 0.19186069071292877
}
|
30,418
|
In my Active worksheet, I have the following code;
If Target.Address = "$B$3" Then
Sheets("Job Request").Activate
End If
What I would like to do is this, when the code runs
then the value of cell A1 in sheet 'Job Request'
becomes the value of B1 from my Active Sheet.
Something like this;
If Target.Address = "$B$3" Then
ActiveSheet.Range("B2").copy values only
Sheets("Job Request").Activate
ActiveSheet.Range("A1").paste values only
End If
How can I do this
|
8ed7973ff25f6b34bafbe585da48a55c
|
{
"intermediate": 0.4939710199832916,
"beginner": 0.3141683042049408,
"expert": 0.19186069071292877
}
|
30,419
|
In my Active worksheet, I have the following code;
If Target.Address = "$B$3" Then
Sheets("Job Request").Activate
End If
What I would like to do is this, when the code runs
then the value of cell A1 in sheet 'Job Request'
becomes the value of B1 from my Active Sheet.
Something like this;
If Target.Address = "$B$3" Then
ActiveSheet.Range("B2").copy values only
Sheets("Job Request").Activate
ActiveSheet.Range("A1").paste values only
End If
How can I do this
|
bebefbbcd54704efb09b7f0199b4674d
|
{
"intermediate": 0.4939710199832916,
"beginner": 0.3141683042049408,
"expert": 0.19186069071292877
}
|
30,421
|
why do i get a "vector erase iterator outside range" error in c++ when i do the following
for (size_t i = 0; i < get_created_icons().size(); i++)
{
if (!get_created_icons()[i])
printf("error! created icon does not exist!\n");//debug, remove this when satisfied with created icon system
if (get_created_icons()[i]->get_id() == icon_id)
{
created_icons.erase(get_created_icons().begin() + i);
return;
}
}
|
0b2ea1a5de4195c19b513fb8b2b606bb
|
{
"intermediate": 0.5301250219345093,
"beginner": 0.34704285860061646,
"expert": 0.12283211201429367
}
|
30,422
|
Hey there. I'm writing a lisp for Autodesk civil 3d 2022. The purpose of the lisp is to gather the data from a layer including area of hatches, length of lines, and length of poly lines. I am having a error on line 27 that is : no function definition: VLA-GETENTITERATOR. I will send the script so you can review and fix the error if possible.
|
25573ff01235395d2cfdf330d1b35292
|
{
"intermediate": 0.41778939962387085,
"beginner": 0.3212278187274933,
"expert": 0.26098281145095825
}
|
30,423
|
(defun c:gather-data ()
(setq layer (getstring "\nEnter layer name: "))
(setq csv-file (strcat (vl-filename-directory (getenv “TEMP”)) “\data.csv”)) ; Fix the path separator
(if (tblobjname “LAYER” layer)
(progn
(setq data '(“Object Type” “Area” “Length”)) ; Header of the CSV file
(defun add-to-data (ent)
(if (eq “AcDbHatch” (vla-get-objectname (vlax-ename->vla-object ent)))
(progn
(setq hatch (vlax-ename->vla-object ent))
(setq area (vla-get-Area hatch))
(setq data (append data (list “HATCH” area)))
))
(if (or (eq “AcDbLine” (vla-get-objectname (vlax-ename->vla-object ent))))
(eq “AcDbPolyline” (vla-get-objectname (vlax-ename->vla-object ent))))
(progn
(setq length (vla-get-trueLength (vlax-ename->vla-object ent)))
(setq data (append data (list (vla-get-objectname (vlax-ename->vla-object ent))) length)))
))
(setq acadApp (vlax-get-acad-object))
(setq doc (vla-get-activedocument acadApp))
(setq ms (vla-get-ModelSpace doc))
(setq csv-str “”) ; Initialize CSV string
(vlax-for ent ms ; Iterate over entities in ModelSpace
(setq current-layer (vlax-get ent 'layer))
(if (and (= (vla-get-objectname current-layer) “AcDbLayerTableRecord”)
(equal (vlax-get current-layer 'name) layer))
(add-to-data ent)
)
)
(foreach item data
(setq csv-str (strcat csv-str (vl-string-quote (strcase (car item))) “,” (vl-princ-to-string (cadr item)) “,”))
)
(setq csv-file (open csv-file “w”))
(write-line csv-str csv-file)
(close csv-file)
(princ “\nData gathering complete. CSV file saved on the desktop.”)
)
(princ “\nSpecified layer does not exist.”)
)
)
(defun c:test-gather-data ()
(c:gather-data)
(princ)
)
(c:test-gather-data)
|
e4bf810fb8e292a74e101b698b71b795
|
{
"intermediate": 0.38999268412590027,
"beginner": 0.3400323688983917,
"expert": 0.269974946975708
}
|
30,424
|
Im trying to use this LSP in Civil 3D 2022. (if (and (= (vla-get-objectname current-layer) “AcDbLayerTableRecord”) in this line it says I Have this error. bad argument type: VLA-OBJECT “0”
|
c7afb84dbd81a884e76b67a144f2ada2
|
{
"intermediate": 0.4539806544780731,
"beginner": 0.25227925181388855,
"expert": 0.29374009370803833
}
|
30,425
|
The Byte Plus platform has n servers, where the data stored on the ih server is represented by the array memory[i]. To manage the server efficiently you can perform the following operation any (possibly zero) number of times:
• Choose an index idx, such that 1 <= idx <= n/2.
• Swap the data of the pair of servers that are equidistant from the beginning and the ending of the array memory and have a distance less than or equal to idx.
The total working efficiency of the servers is calculated as the sum of the product of the data present in each server with the index of that server.
Given an integer n, and an array memory, find the maximum possible total working efficiency that we can get, since the total working efficiency can be very large print it modulo 10^9+7.
Example
Given, n = 4, memory= [2, 4, 1, 3].
Here's a table representing the operations, `idx`, `memory`, and the total working efficiency for the provided examples:
| Operation | idx | Memory | Total Working Efficiency |
|-----------|-----|--------------------|--------------------------|
| 1 | 2 | [3, 1, 4, 2] | 1*3 + 2*1 + 3*4 + 4*2 = 25 |
| 2 | 1 | [2, 1, 4, 3] | 1*2 + 2*1 + 3*4 + 4*3 = 28 |
These are the two operations and their corresponding results for the examples you provided.
Here, we can perform 2 Operations and the maximum possible total working efficiency we can get is 28 modulo 10^9+7, which is equal to 28 itself. If we perform any other operation after performing Operation 1 and Operation 2, the total working efficiency will not increase more than 28.
Given, n = 5, memory= [5, 4, 1, 5, 3, 2]. the result is 81.
Given, n = 8, memory= [5, 1, 4, 2, 4, 1, 2, 3]. the result is 114.
|
5ffe14e48ddfcc74bbeb7acba40d8866
|
{
"intermediate": 0.44859936833381653,
"beginner": 0.22357548773288727,
"expert": 0.327825129032135
}
|
30,426
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BarrelSpawner : MonoBehaviour
{
public GameObject barrelPrefab;
public Transform[] spawnPoints; // Points where barrels will be spawned
public float spawnInterval = 3f; // Interval between barrel spawns
private bool isSpawning = true;
private void Start()
{
InvokeRepeating("SpawnBarrel", 0f, spawnInterval);
// Spawn initial barrels
SpawnInitialBarrels();
}
private void SpawnInitialBarrels()
{
// Create an array of positions
Vector3[] initialPositions = new Vector3[]
{
new Vector3(-6f, -3.25f, 0f),
new Vector3(6f, -1.25f, 0f),
new Vector3(-6f, 0.75f, 0f),
new Vector3(6f, 2.75f, 0f)
};
// Loop through each position and spawn a barrel
foreach (Vector3 position in initialPositions)
{
Instantiate(barrelPrefab, position, Quaternion.identity);
}
}
private void SpawnBarrel()
{
int spawnIndex = Random.Range(0, spawnPoints.Length);
Transform spawnPoint = spawnPoints[spawnIndex];
Instantiate(barrelPrefab, spawnPoint.position, Quaternion.identity);
}
public void StopSpawning()
{
isSpawning = false;
CancelInvoke("SpawnBarrel");
}
}
public class BarrelController : MonoBehaviour
{
public Transform[] movePoints; // Points where barrel moves
public Transform ladderPoint; // Point where barrel goes down the ladder
public float moveSpeed = 3f; // Speed at which barrel moves
private int currentPointIndex = 0;
private void Update()
{
MoveBarrel();
}
private void MoveBarrel()
{
if (currentPointIndex >= movePoints.Length)
{
Destroy(gameObject); // Destroy barrel if it reaches the end
return;
}
if (movePoints[currentPointIndex] == ladderPoint)
{
// Handle ladder movement separately
MoveBarrelDownLadder();
}
else
{
// Move barrel to target point
Transform targetPoint = movePoints[currentPointIndex];
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, moveSpeed * Time.deltaTime);
if (transform.position == targetPoint.position)
{
currentPointIndex++;
}
}
}
private void MoveBarrelDownLadder()
{
// Move barrel down the ladder
Vector3 ladderExitPoint = ladderPoint.position + new Vector3(0, -1, 0); // Point where barrel exits the ladder
transform.position = Vector3.MoveTowards(transform.position, ladderExitPoint, moveSpeed * Time.deltaTime);
if (transform.position == ladderExitPoint)
{
currentPointIndex++;
}
}
}
make it so when a barrel collides with a BarrelChute game object (set to BarrelChute layer) it only moves down on the Y axis (velocity of 0) and can phase through 1 platform (set to the platform layer) and will reset when it hit the second platform
|
3ceb16a8faa87cc28c17be8a45db38b0
|
{
"intermediate": 0.3872467577457428,
"beginner": 0.5051113367080688,
"expert": 0.10764192044734955
}
|
30,427
|
Im creating a lisp to use in civil 3d 2022
|
05730c122c587627f8605495d5358212
|
{
"intermediate": 0.3051086962223053,
"beginner": 0.42657729983329773,
"expert": 0.268314003944397
}
|
30,428
|
public class BarrelController : MonoBehaviour
{
public Transform[] movePoints; // Points where barrel moves
public Transform ladderPoint; // Point where barrel goes down the ladder
public float moveSpeed = 3f; // Speed at which barrel moves
private int currentPointIndex = 0;
private void Update()
{
MoveBarrel();
}
private void MoveBarrel()
{
if (currentPointIndex >= movePoints.Length)
{
Destroy(gameObject); // Destroy barrel if it reaches the end
return;
}
if (movePoints[currentPointIndex] == ladderPoint)
{
// Handle ladder movement separately
MoveBarrelDownLadder();
}
else
{
// Move barrel to target point
Transform targetPoint = movePoints[currentPointIndex];
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, moveSpeed * Time.deltaTime);
if (transform.position == targetPoint.position)
{
currentPointIndex++;
}
}
}
private void MoveBarrelDownLadder()
{
// Move barrel down the ladder
Vector3 ladderExitPoint = ladderPoint.position + new Vector3(0, -1, 0); // Point where barrel exits the ladder
transform.position = Vector3.MoveTowards(transform.position, ladderExitPoint, moveSpeed * Time.deltaTime);
if (transform.position == ladderExitPoint)
{
currentPointIndex++;
}
}
} Make it so if the barrel collides with a ladder game object (set to ladder layer) it will go straight down the ladder
|
0d9e5beaedf0511bfcadb736b5e93a07
|
{
"intermediate": 0.4036547839641571,
"beginner": 0.28066450357437134,
"expert": 0.31568071246147156
}
|
30,429
|
consider this lua code:
|
94844e1d5e991ce85bf198b73d1845ee
|
{
"intermediate": 0.34807324409484863,
"beginner": 0.37102553248405457,
"expert": 0.2809012830257416
}
|
30,430
|
public class BarrelController : MonoBehaviour
{
public Transform[] movePoints; // Points where barrel moves
public Transform ladderPoint; // Point where barrel goes down the ladder
public float moveSpeed = 3f; // Speed at which barrel moves
private int currentPointIndex = 0;
private void Update()
{
MoveBarrel();
}
private void MoveBarrel()
{
if (currentPointIndex >= movePoints.Length)
{
Destroy(gameObject); // Destroy barrel if it reaches the end
return;
}
if (movePoints[currentPointIndex] == ladderPoint)
{
// Handle ladder movement separately
MoveBarrelDownLadder();
}
else
{
// Move barrel to target point
Transform targetPoint = movePoints[currentPointIndex];
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, moveSpeed * Time.deltaTime);
if (transform.position == targetPoint.position)
{
currentPointIndex++;
}
}
}
private void MoveBarrelDownLadder()
{
// Move barrel down the ladder
Vector3 ladderExitPoint = ladderPoint.position + new Vector3(0, -1, 0); // Point where barrel exits the ladder
transform.position = Vector3.MoveTowards(transform.position, ladderExitPoint, moveSpeed * Time.deltaTime);
if (transform.position == ladderExitPoint)
{
currentPointIndex++;
}
}
}
1. The Barrel has an OnTriggerEnter2D script that will be called when it enters any ladder.
2. If the BarrelLadder has a likelihood of 100%, then the Barrel will always want to go down it. Otherwise, the Barrel decides whether to go down the BarrelLadder.
3. If the Barrel DOES want to go down the BarrelLadder, it assigns that BarrelLadder to it's currentLadder field.
4. When the Barrel is aligned with the center of the ladder (in the X dimension), then:
- Set the X position of the Barrel to the same as the ladder
- Using movement over time, move the barrel down the ladder.
- When the Barrel gets to the bottom of the ladder, set currentLadder = null; Remodify this script so that the Barrels will go down the Ladder
|
3be7910aca6679f738f6993fe4899b46
|
{
"intermediate": 0.3767479956150055,
"beginner": 0.3416409492492676,
"expert": 0.28161102533340454
}
|
30,431
|
what is a synaxis to determine number of elements in an array
|
25f90e4952c512968262ce97ce8a8df2
|
{
"intermediate": 0.3154574930667877,
"beginner": 0.26780450344085693,
"expert": 0.41673800349235535
}
|
30,433
|
how to modify the code? thanks
REGEXP_REPLACE(REGEXP_REPLACE(IF(REGEXP_CONTAINS(url_2,"community"),(REGEXP_EXTRACT(url_3,"pi=(.+)&"),REGEXP_EXTRACT(url_3,"pi%3D(.+)%26")),
REGEXP_EXTRACT(url_3, r"^\D*(\d+)")),"%3D","="),"%26","&") AS content_id,
|
1275224ddaad98aaa0198281dad73c0a
|
{
"intermediate": 0.40635982155799866,
"beginner": 0.395931214094162,
"expert": 0.19770896434783936
}
|
30,434
|
create android menu class example code
|
8c60125751967aca757181fe0865d251
|
{
"intermediate": 0.3606759309768677,
"beginner": 0.37388843297958374,
"expert": 0.26543569564819336
}
|
30,435
|
give scenario with 3 set of questions of 10 marks in datatypes in c program with answers
|
13468eb9d202d6e7e04c4bad3197cee8
|
{
"intermediate": 0.21804502606391907,
"beginner": 0.477692186832428,
"expert": 0.30426278710365295
}
|
30,436
|
i need menu in android, create file res/menu as an example. there must be Settings, Open and Save options. give me a source code of activity and menu layout
|
c4bfd41765a581b0d1b3ac33cca8b73c
|
{
"intermediate": 0.4557720124721527,
"beginner": 0.23466362059116364,
"expert": 0.3095643222332001
}
|
30,438
|
Как мне с помощью static_cast преобразовать матрицу типа Eigen::SparseMatrix<size_t> к типу Eigen::SparseMatrix<double>?
|
c8a8db8eac1dc9bbdc7f72bb4d738cba
|
{
"intermediate": 0.4088633954524994,
"beginner": 0.28151047229766846,
"expert": 0.30962616205215454
}
|
30,439
|
android ListView with layout_height is wrap_content shows only 1 element, while I need it show me a list. elements of root list is also ListView elements
|
95b41953785deaf62896861574729e65
|
{
"intermediate": 0.5459727048873901,
"beginner": 0.17160050570964813,
"expert": 0.28242674469947815
}
|
30,440
|
i have one ListView in another ListView and it shows me only the first element of inner ListView
|
01e48f475f07d147f108ee3734b2ffdf
|
{
"intermediate": 0.4223174452781677,
"beginner": 0.27235594391822815,
"expert": 0.30532655119895935
}
|
30,441
|
how to draw list of ListView in another ListView java? i need just the xml files
|
9f58eafcdfad396117067beb5efdd898
|
{
"intermediate": 0.6403189301490784,
"beginner": 0.1990268975496292,
"expert": 0.1606542021036148
}
|
30,442
|
is there any function same Trim in VBA?
|
0a26424c1e78ec7a568faef48932cbb4
|
{
"intermediate": 0.15714643895626068,
"beginner": 0.48599258065223694,
"expert": 0.3568609356880188
}
|
30,443
|
请用更便捷的方法实现这段代码: for i, data in enumerate([Data_Find, Data_Min_1, Data_Max_1, Data_Min_2, Data_Max_2,Data_Min_3, Data_Max_3, Data_Min_4, Data_Max_4, Data_Price], start=20):
column_letter = chr(ord('A') + i) # 转换为列字母
column_range = f"{column_letter}1:{column_letter}{L}" # 列范围
values = data.values.flatten().tolist() # 将数据转为列表
for row_idx, value in enumerate(values, start=1):
cell = sheet.cell(row=row_idx, column=i) # 获取单元格
cell.value = value # 将值写入单元格
|
7d8b3732bb232ba0aa9bcca5ca605b8b
|
{
"intermediate": 0.33613744378089905,
"beginner": 0.4627790153026581,
"expert": 0.20108358561992645
}
|
30,445
|
create viewholder for this class:
package com.example.schedule;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import java.util.List;
public class TwoWeekLessonAdapter extends ArrayAdapter<TwoWeekLesson> {
private final LayoutInflater inflater;
private final int layout;
private final List<TwoWeekLesson> lessons;
public TwoWeekLessonAdapter(@NonNull Context context, int resource, @NonNull List<TwoWeekLesson> lessons) {
super(context, resource, lessons);
this.lessons = lessons;
this.layout = resource;
this.inflater = LayoutInflater.from(context);
}
@NonNull
public View getView(int position, View twlView, @NonNull ViewGroup parent)
{
twlView = inflater.inflate(this.layout, parent, false);
TwoWeekLesson twl = lessons.get(position);
TextView dateStart = twlView.findViewById(R.id.dateStart);
TextView dateEnd = twlView.findViewById(R.id.dateEnd);
TextView firstWeekDiscipline = twlView.findViewById(R.id.firstWeekDiscipline);
TextView firstWeekTeacher = twlView.findViewById(R.id.firstWeekTeacher);
TextView firstWeekAuditory = twlView.findViewById(R.id.firstWeekAuditory);
TextView secondWeekDiscipline = twlView.findViewById(R.id.secondWeekDiscipline);
TextView secondWeekTeacher = twlView.findViewById(R.id.secondWeekTeacher);
TextView secondWeekAuditory = twlView.findViewById(R.id.secondWeekAuditory);
dateStart.setText(twl.getDateStart());
dateEnd.setText(twl.getDateEnd());
firstWeekDiscipline.setText(twl.getFirstWeekDiscipline());
firstWeekTeacher.setText(twl.getFirstWeekTeacher());
firstWeekAuditory.setText(twl.getFirstWeekAuditory());
secondWeekDiscipline.setText(twl.getSecondWeekDiscipline());
secondWeekTeacher.setText(twl.getSecondWeekTeacher());
secondWeekAuditory.setText(twl.getSecondWeekAuditory());
return twlView;
}
}
|
3d59441e085e19c54efbf7a0e0896946
|
{
"intermediate": 0.42326459288597107,
"beginner": 0.308174729347229,
"expert": 0.26856064796447754
}
|
30,446
|
убери функцию сортировки
в графе имя файла , имя сделай ссылкой
import sqlite3
import tkinter as tk
from tkinter import ttk
import webbrowser
def get_files(sort_key):
conn = sqlite3.connect("files_info.db")
cursor = conn.cursor()
# Определяем ключ сортировки
if sort_key == "num_files":
sort_key_sql = "num_lines"
else:
sort_key_sql = "LENGTH(lines)"
# Получаем данные из базы данных
cursor.execute(f"SELECT file_name, creation_date, num_lines, lines FROM files ORDER BY {sort_key_sql}")
files = cursor.fetchall()
conn.close()
return files
def search_files(search_text):
conn = sqlite3.connect("files_info.db")
cursor = conn.cursor()
# Получаем данные из базы данных по условию LIKE
cursor.execute("SELECT file_name, creation_date, num_lines, lines FROM files WHERE lines LIKE ?", ('%'+search_text+'%',))
files = cursor.fetchall()
conn.close()
return files
def on_sort_change(event):
sort_key = sort_combobox.get()
files = get_files(sort_key)
update_table(files)
def on_search():
search_text = search_entry.get()
files = search_files(search_text)
update_table(files)
def update_table(files):
# Очищаем таблицу
for row in file_table.get_children():
file_table.delete(row)
# Заполняем таблицу новыми данными
for file in files:
file_name = file[0]
num_lines = file[2]
lines = file[3]
# Создаем ссылку на имя файла
file_name_link = f'ftp://{file_name[:-4]}'
file_table.insert("", "end", values=(file_name_link, num_lines, lines))
if __name__ == "__main__":
# Создаем графическое окно
window = tk.Tk()
window.title("File Info App")
#window.geometry("800x600")
# Создаем и размещаем элементы управления
sort_label = ttk.Label(window, text="Сортировка:")
sort_label.grid(row=0, column=0, padx=5, pady=5)
sort_combobox = ttk.Combobox(
window, values=["По количеству строк", "По размеру"], state="readonly")
sort_combobox.current(0)
sort_combobox.bind("<<ComboboxSelected>>", on_sort_change)
sort_combobox.grid(row=0, column=1, padx=5, pady=5)
search_label = ttk.Label(window, text="Поиск:")
search_label.grid(row=1, column=0, padx=5, pady=5)
search_entry = ttk.Entry(window)
search_entry.grid(row=1, column=1, padx=5, pady=5)
search_button = ttk.Button(window, text="Найти", command=on_search)
search_button.grid(row=1, column=2, padx=5, pady=5)
file_table = ttk.Treeview(window, columns=("file_name", "num_lines"), show="headings")
file_table.heading("file_name", text="Имя файла")
file_table.heading("num_lines", text="Количество строк")
file_table.grid(row=2, column=0, columnspan=3, padx=5, pady=5)
# Получаем данные из базы данных и обновляем таблицу
files = get_files(sort_combobox.get())
update_table(files)
window.mainloop()
|
8eb4ba5e3f5a625f8e23df558dc73d36
|
{
"intermediate": 0.30517521500587463,
"beginner": 0.521215558052063,
"expert": 0.17360928654670715
}
|
30,447
|
what is this representing?
|
ccacd743f3eaa87c41f13069267d588c
|
{
"intermediate": 0.3613232672214508,
"beginner": 0.3072035610675812,
"expert": 0.33147314190864563
}
|
30,448
|
check grammar "Nomination in late of Nov"
|
fb796c1efae926c2726149dcfc8d081e
|
{
"intermediate": 0.36907318234443665,
"beginner": 0.3064222037792206,
"expert": 0.3245046138763428
}
|
30,449
|
I have a table with columns Product and Month and three measures X1, X2, and X3. I placed Product and Month as Rows and X1, X2, and X3 as Values in matrix visualization in Power BI. I need a DAX measure that is calculated as X1*X2/X3 at the level of Month and as SUMPRODUCT(X1,X2)/X3 at the Product level. SUMPRODUCT is Excel function. I need something similar in DAX.
|
02ff328c497d6e12f7d1f6aa77309ba0
|
{
"intermediate": 0.3476226031780243,
"beginner": 0.3030812740325928,
"expert": 0.3492961525917053
}
|
30,450
|
excample of the best practice in order to switch 2 tables with diffirent column and data using Antd , Angular 13
when i click to button in column: 'view' in table a, it switch to table b
|
25c37b4662d281772f155816331a4f5a
|
{
"intermediate": 0.6834875345230103,
"beginner": 0.12223626673221588,
"expert": 0.19427618384361267
}
|
30,451
|
Private Sub CommandButton1_Click()
TextBox1.ControlSource = "Лист1!A2"
TextBox2.ControlSource = "Лист1!A3"
TextBox3.ControlSource = "Лист1!A4"
TextBox4.ControlSource = "Лист1!A5"
TextBox5.ControlSource = "Лист1!A6"
TextBox6.ControlSource = "Лист1!A7"
TextBox7.ControlSource = "Лист1!A8"
TextBox8.ControlSource = "Лист1!A9"
TextBox9.ControlSource = "Лист1!A10"
TextBox10.ControlSource = "Лист1!A11"
TextBox11.ControlSource = "Лист1!A12"
TextBox12.ControlSource = "Лист1!A13"
TextBox13.ControlSource = "Лист1!A14"
TextBox14.ControlSource = "Лист1!A15"
TextBox15.ControlSource = "Лист1!A16"
TextBox16.ControlSource = "Лист1!A17"
TextBox17.ControlSource = "Лист1!A18"
End Sub
Private Sub CommandButton2_Click()
Dim myRange As Range
Dim a As Single
Dim b As Single
Set myRange = Worksheets("Лист1").Range("A2:A18")
a = Application.WorksheetFunction.Max(myRange)
b = Application.WorksheetFunction.Min(myRange)
TextBox18.Text = Round(Application.WorksheetFunction.Average(myRange), 3)
TextBox19.Text = Round(Application.WorksheetFunction.StDev(myRange) / Sqr(17), 3)
TextBox20.Text = Round(Application.WorksheetFunction.Median(myRange), 3)
TextBox21.Text = Round(Application.WorksheetFunction.Mode(myRange), 3)
TextBox22.Text = Round(Application.WorksheetFunction.StDev(myRange), 3)
TextBox23.Text = Round(Application.WorksheetFunction.Var(myRange), 3)
TextBox24.Text = Round(Application.WorksheetFunction.Kurt(myRange), 3)
TextBox25.Text = Round(Application.WorksheetFunction.Skew(myRange), 3)
TextBox26.Text = a - b
TextBox27.Text = b
TextBox28.Text = a
TextBox29.Text = Round(Application.WorksheetFunction.Sum(myRange), 3)
TextBox30.Text = Round(Application.WorksheetFunction.Count(myRange), 3)
TextBox31.Text = 33
TextBox32.Text = 16
TextBox33.Text = 3.901
End Sub
что делает этот код
|
797bdb7b21ebd1e4c9561c2b128a7613
|
{
"intermediate": 0.38656550645828247,
"beginner": 0.2783774435520172,
"expert": 0.3350570499897003
}
|
30,452
|
java socket client
|
1f53ed72d4d8af0859bc445f6d3673ca
|
{
"intermediate": 0.43683135509490967,
"beginner": 0.28731831908226013,
"expert": 0.2758502960205078
}
|
30,453
|
let max=0
let min=100
let preavarage=0
const infoChemistry={firstname:"",
lastName:"",
grade:"",
courseName:""
}
for(let i=0;i<grades.length;i++){
while(grades[i].courseName=="Chemistry"){
infoChemistry.firstname=grades[i].firstName
infoChemistry.lastName=grades[i].lastName
infoChemistry.grade=grades[i].grade
infoChemistry.courseName=grades[i].courseName
if(max<grades[i].grade){
max=grades[i].grade
}
if(min>grades[i].grade){
min=grades[i].grade
}
preavarage+=grades[i].grade
}
}
console.table(infoChemistry)
console.log("Maximum grade is "+ max)
console.log("Minimum grade is "+min)
console.log("Average grade is "+preavarage/(grades.length))
|
5bc0fc303ca7da609a9296094ef8edd3
|
{
"intermediate": 0.3516552448272705,
"beginner": 0.3733874559402466,
"expert": 0.2749573290348053
}
|
30,454
|
в этом коде дата сохраняется как 2023-11-09 10:06:20.116866 мне нужно чтобы не сохранял после точки, чтобы было так 2023-11-09 10:06:20
import os
from datetime import datetime
# folder_path = "open_list"
folder_path = "full_list"
# Получение списка всех файлов и папок в указанной папке
files = os.listdir(folder_path)
# Список для хранения данных файлов
file_data = []
# Перебор файлов
for file in files:
# Полный путь к файлу
file_path = os.path.join(folder_path, file)
# Проверка, является ли объект файлом
if os.path.isfile(file_path):
# Получение информации о файле
file_name = os.path.splitext(file)[0]
file_size = os.path.getsize(file_path) # Размер файла в байтах
file_date = datetime.fromtimestamp(os.path.getctime(file_path))
# Получение количества строк в файле
with open(file_path, 'r', encoding="utf-8") as file_content:
line_count = len(file_content.readlines())
# Добавление данных в список
file_data.append((file_name, file_size, file_date, line_count))
# Создание таблицы в формате HTML
table_html = "<style>table {padding:0;text-align:center; font-family:monospace;font-size: 12px; border-collapse: collapse;width: 100%;} th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color: #ccc;}</style>\n"
table_html += "<table style='width: 100%;'>\n"
table_html += "<tr><th style='width: 30%;'>Имя файла</th><th style='width: 30%;'>Дата создания</th><th style='width: 20%;'>Размер (Байт)</th><th style='width: 20%;'>Количество строк</th></tr>\n"
for data in file_data:
file_name = data[0]
file_date = data[2]
file_size = data[1]
line_count = data[3]
file_link = "ftp://" + file_name
table_html += "<tr><td style='width: 30%;'><a href='{}'>{}</a></td><td style='width: 30%;'>{}</td><td style='width: 20%;'>{}</td><td style='width: 20%;'>{}</td></tr>\n".format(file_link, file_name, file_date, file_size, line_count)
table_html += "</table>"
# Сохранение таблицы в файл
with open("output.html", "w") as f:
f.write(table_html)
|
f86b4340f9e72ecb57708ce7de9c5893
|
{
"intermediate": 0.27050748467445374,
"beginner": 0.5717766880989075,
"expert": 0.1577158421278
}
|
30,455
|
Scenario: A supermarket wants to calculate the total bill for a customer's purchase. The supermarket offers a discount of 10% on the total bill if the customer's total purchase exceeds $100.
Write a C program that takes the quantity and price of each item purchased by a customer as input. Use a loop statement to calculate the total bill. If the total bill exceeds $100, apply a 10% discount and display the final bill amount.
Modify the previous program to include a loop that allows the cashier to keep entering items until the customer is done shopping. Use a sentinel value to indicate when the customer is done. Calculate and display the total bill, applying the discount if applicable. give additional question to this scenario
Enhance the program to keep track of the number of items purchased by the customer. Display the average price per item at the end of the transaction. Give additional questions related to loop
|
948c2d16e5b08c197c2d294ef848dd67
|
{
"intermediate": 0.1954042613506317,
"beginner": 0.6369253993034363,
"expert": 0.167670339345932
}
|
30,456
|
в сгенерированном файле не работает поиск и при нажатии на количество строк не выпадает список с этими строками , исправь
import os
from datetime import datetime
folder_path = "full_list"
# Получение списка всех файлов и папок в указанной папке
files = os.listdir(folder_path)
# Список для хранения данных файлов
file_data = []
# Перебор файлов
for file in files:
# Полный путь к файлу
file_path = os.path.join(folder_path, file)
# Проверка, является ли объект файлом
if os.path.isfile(file_path):
# Получение информации о файле
file_name = os.path.splitext(file)[0]
file_size = os.path.getsize(file_path) # Размер файла в байтах
# Получение количества строк в файле
with open(file_path, 'r', encoding="utf-8") as file_content:
lines = file_content.readlines()
line_count = len(lines)
# Добавление данных в список
file_data.append((file_name, line_count, lines))
# Создание таблицы в формате HTML
table_html = "<style>table {padding:0;text-align:center; font-family:monospace;font-size: 12px; border-collapse: collapse;width: 100%;} th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color: #ccc;}</style>\n"
table_html += "<input type='text' id='searchInput' onkeyup='searchTable()' placeholder='Поиск по файлам…'><br><br>"
table_html += "<table style='width: 100%;' id='fileTable'>\n"
table_html += "<tr><th style='width: 60%;'>Имя файла</th><th style='width: 40%;'>Количество строк</th></tr>\n"
for data in file_data:
file_name = data[0]
line_count = data[1]
lines = data[2]
file_link = "ftp://" + file_name
# Добавление данных в таблицу
table_html += "<tr><td style='width: 60%;'><a href='{}'>{}</a></td><td style='width: 40%;'><button onclick='showLines(this)' data-lines='{}'>{}</button></td></tr>\n".format(file_link, file_name, ';'.join(lines), line_count)
table_html += "</table>"
# JavaScript функция для поиска в таблице и отображения строк файла
search_script = """
<script>
function searchTable() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
table = document.getElementById("fileTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
function showLines(button) {
var lines = button.getAttribute('data-lines').split(';');
var linesList = "";
for (var i = 0; i < lines.length; i++) {
linesList += '<li>' + lines[i] + '</li>';
}
document.getElementById("linesList").innerHTML = linesList;
}
</script>
"""
# Сохранение таблицы и скрипта в файл
with open("output.html", "w", encoding="utf-8") as f:
f.write(table_html + search_script)
|
bfbda10cf9a5a2d9ac8b7e10dd528adc
|
{
"intermediate": 0.35303428769111633,
"beginner": 0.5000661015510559,
"expert": 0.1468995362520218
}
|
30,457
|
there is a competitors_min dataframe in which the columns price, place (categorical) have 5 unique values, product(categorical) have 3 unique values,
I need to translate the numerical value of price, on a combination of two categorical columns, there should be 15 numeric columns, which are called by place product
|
eaf4291d7826fa7e84e848f6a685ed6c
|
{
"intermediate": 0.42995065450668335,
"beginner": 0.2547433078289032,
"expert": 0.31530603766441345
}
|
30,458
|
в этом коде нужно исправить, отображение списка файлов должно быть только по клику по цыфре с количеством этих файлов и должно отображаться с новой строки
поиск по списками должен отобразить только те строки в которых были совпадения
import os
from datetime import datetime
folder_path = "full_list"
# Получение списка всех файлов и папок в указанной папке
files = os.listdir(folder_path)
# Список для хранения данных файлов
file_data = []
# Перебор файлов
for file in files:
# Полный путь к файлу
file_path = os.path.join(folder_path, file)
# Проверка, является ли объект файлом
if os.path.isfile(file_path):
# Получение информации о файле
file_name = os.path.splitext(file)[0]
file_size = os.path.getsize(file_path) # Размер файла в байтах
# Получение содержимого файла
with open(file_path, 'r', encoding="utf-8") as file_content:
content = file_content.read()
# Добавление данных в список
file_data.append((file_name, content))
# Создание таблицы в формате HTML
table_html = "<style>table {padding:0;text-align:center; font-family:monospace;font-size: 12px; border-collapse: collapse;width: 100%;} th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color: #ccc;}</style>\n"
table_html += "<input type='text' id='searchInput' onkeyup='searchTable()' placeholder='Поиск в содержимом файлов…'><br><br>"
table_html += "<table style='width: 100%;' id='fileTable'>\n"
table_html += "<tr><th style='width: 60%;'>Имя файла</th><th style='width: 40%;'>Содержимое файла</th></tr>\n"
for data in file_data:
file_name = data[0]
content = data[1]
file_link = "ftp://" + file_name
# Добавление данных в таблицу
table_html += "<tr><td style='width: 60%;'><a href='{}'>{}</a></td><td style='width: 40%;'>{}</td></tr>\n".format(
file_link, file_name, content)
table_html += "</table>"
# JavaScript функция для поиска в таблице
search_script = """
<script>
function searchTable() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
table = document.getElementById("fileTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
"""
# Сохранение таблицы и скрипта в файл
with open("output.html", "w", encoding="utf-8") as f:
f.write(table_html + search_script)
|
73b70fe34408bef865f89176994d56e0
|
{
"intermediate": 0.3048829734325409,
"beginner": 0.4025662839412689,
"expert": 0.2925507426261902
}
|
30,459
|
Write a melody, like, the actual keys, to a sci fi video game
|
03ecf762804d2ce06ecec932c9e965ce
|
{
"intermediate": 0.3856426179409027,
"beginner": 0.2925901412963867,
"expert": 0.3217672109603882
}
|
30,460
|
этот код не работает
import os
from datetime import datetime
folder_path = "full_list"
# Получение списка всех файлов и папок в указанной папке
files = os.listdir(folder_path)
# Список для хранения данных файлов
file_data = []
# Перебор файлов
for file in files:
# Полный путь к файлу
file_path = os.path.join(folder_path, file)
# Проверка, является ли объект файлом
if os.path.isfile(file_path):
# Получение информации о файле
file_name = os.path.splitext(file)[0]
file_size = os.path.getsize(file_path) # Размер файла в байтах
# Получение содержимого файла
with open(file_path, 'r', encoding="utf-8") as file_content:
content = file_content.read()
# Добавление данных в список
file_data.append((file_name, content))
table_html = "<style>table {padding:0;text-align:center; font-family:monospace;font-size: 12px; border-collapse: collapse;width: 100%;} th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color: #ccc;}</style>\n"
table_html += "<input type='text' id='searchInput' onkeyup='searchTable()' placeholder='Поиск в содержимом файлов…'><br><br>"
table_html += "<table style='width: 100%;' id='fileTable'>\n"
table_html += "<tr><th style='width: 60%;'>Имя файла</th><th style='width: 40%;'>Содержимое файла</th></tr>\n"
file_count = len(file_data)
table_html += "<tr><td colspan='2'>Количество файлов: <span id='fileCount'>{}</span></td></tr>\n".format(file_count)
table_html += "</table>"
# Добавление данных в таблицу
if content.upper().find(filter) > -1:
table_html += "<tr><td style='width: 60%;'><a href='{}'>{}</a></td><td style='width: 40%;'>{}</td></tr>\n".format(
file_link, file_name, content)
else:
table_html += "<tr style='display: none;'><td style='width: 60%;'><a href='{}'>{}</a></td><td style='width: 40%;'>{}</td></tr>\n".format(
file_link, file_name, content)
# JavaScript функция для отображения списка файлов
list_script = """
<script>
function showFileList() {
var fileTable = document.getElementById("fileTable");
var fileCount = document.getElementById("fileCount");
fileTable.innerHTML = "<tr><th style='width: 60%;'>Имя файла</th><th style='width: 40%;'>Содержимое файла</th></tr>";
if (fileCount.innerText === "0") {
return;
}
{% for data in file_data %}
var file_name = "{{ data[0] }}";
var content = "{{ data[1] }}";
var file_link = "ftp://" + file_name;
var row = fileTable.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<a href='" + file_link + "'>" + file_name + "</a>";
cell2.innerHTML = content;
{% endfor %}
}
document.getElementById("fileCount").addEventListener("click", showFileList);
</script>
"""
# Сохранение таблицы и скрипта в файл
with open("output.html", "w", encoding="utf-8") as f:
f.write(table_html + list_script + search_script)
|
de9f2c036df52dd1c98694639271aeb4
|
{
"intermediate": 0.3235338032245636,
"beginner": 0.565597653388977,
"expert": 0.11086859554052353
}
|
30,461
|
how to implement the binned info above into a existing pmml file with python
|
86f1b76c2a78161e20dcb872ff0183a3
|
{
"intermediate": 0.35952243208885193,
"beginner": 0.24093244969844818,
"expert": 0.3995451033115387
}
|
30,462
|
give me a ue5 script of taming pets like game in ark survival
|
b78847a22bb287edd3abcfaf6c072f38
|
{
"intermediate": 0.335339218378067,
"beginner": 0.3967757523059845,
"expert": 0.2678849995136261
}
|
30,463
|
You are working as a teacher at a school, and you want to identify the student with the highest
average marks percentage among a group of students. You need to create a program in to help
you do this. The program should take the following inputs from the user: the number of students,
each student's name, roll number, and marks for five subjects.give structure and union based 3 questions for this
|
7e249cf17748de91fb0a3c5ff9ded1de
|
{
"intermediate": 0.34598031640052795,
"beginner": 0.33250951766967773,
"expert": 0.3215101957321167
}
|
30,464
|
how do you select and format all removable drives to ntfs on windows 10 with powershell
|
7db0759a5877725c1b18153749148a7f
|
{
"intermediate": 0.44681012630462646,
"beginner": 0.2914504408836365,
"expert": 0.26173943281173706
}
|
30,465
|
Define array of objects in Postgres schema
|
d5e22cdd1d6ba217bb6cfbcf95e79755
|
{
"intermediate": 0.3771347105503082,
"beginner": 0.4052881896495819,
"expert": 0.21757718920707703
}
|
30,466
|
in uipath studio, i would like to save the lotus notes email in pdf file, how to achieve this. another problem is it is found that the lotus notes email content is encoded by base 64.
|
9e57539ec534c1bec08cb9bac6a05898
|
{
"intermediate": 0.4088633954524994,
"beginner": 0.2292965203523636,
"expert": 0.3618401288986206
}
|
30,467
|
analyze the following algorithm by:
1) indicate the input size of the algorithm,
2) Identify the basic operation
3)Set up a sum form of the number of times the basic operation is executed
4) Establish an order of growth for the algorithm.
The algorithm:
For i←0 to n-1 do
For j←0 to b-1
StudentPoints←StudentPoints+student[i].grades[j]
Student[i].GPA←StudentPoints/j
If Student[i].GPA> collegeRequirement
Admit student
n is the length of the student array
b is the length of the grade array in the student array
|
57b424fe431490991df1cd86d8f71a48
|
{
"intermediate": 0.17177826166152954,
"beginner": 0.11351846158504486,
"expert": 0.7147032618522644
}
|
30,468
|
напиши код python
в папке folder_path = "full_list" лежат текстовые файлы
необходимо создать html файл с таблицей 2 колонки
первая колонка это имя файла без расширения в виде ссылки file_link = "ftp://" + file_name;
вторая колонка это цыфра количество строк в этом файле , по клику на эту цыфру должен выпадать ранее скрытый список всех строк этого файлы построчно
при помощи javascript добавить поле ввода для поиска по части введенного слова во всех строках в созданном html файле и при нахождении показать только найденные строки
|
48af970d5e1fef7f9a6e42778cdbb411
|
{
"intermediate": 0.32678866386413574,
"beginner": 0.47399747371673584,
"expert": 0.19921380281448364
}
|
30,469
|
вот мой код:
print ('x y z w')
for x in range(2):
for y in range(2):
for z in range(2):
for w in range(2):
if ((x and y) <= (z == x)):
print(x, y, z, w)
и вот ошибка:
File "C:/Users/ученик/Documents/untitled-1.py", line 2, in <module>
for x in range(2):
builtins.IndentationError: unexpected indent (x-wingide-python-shell://89053104/2, line 2)
|
69affe5add2d9b90f38831f2742e4426
|
{
"intermediate": 0.2629590630531311,
"beginner": 0.5502891540527344,
"expert": 0.18675170838832855
}
|
30,470
|
can you generate me a systemd unit, in order to start a java JAR command ?
|
e66e6affbf1f05b6e57febb111745def
|
{
"intermediate": 0.674483060836792,
"beginner": 0.16844163835048676,
"expert": 0.15707536041736603
}
|
30,471
|
Loaded as API: https://magaer13-mplug-owl.hf.space ✔
Client.predict() Usage Info
---------------------------
Named API endpoints: 0
Unnamed API endpoints: 9
- predict(fn_index=0) -> (value_6, value_24)
Parameters:
- None
Returns:
- [Image] value_6: str (filepath or URL to image)
- [Textbox] value_24: str
- predict(fn_index=1) -> (value_24, value_29, value_30, value_31)
Parameters:
- None
Returns:
- [Textbox] value_24: str
- [Button] value_29: str
- [Button] value_30: str
- [Button] value_31: str
- predict(fn_index=2) -> (value_24, value_29, value_30, value_31)
Parameters:
...
- [Chatbot] value_21: str (filepath to JSON file)
- [Textbox] value_24: str
- [Button] value_27: str
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Loaded as API: https://abidlabs-en2fr.hf.space ✔
{for i in range(10)}
The translated result is: {x}
Loaded as API: https://abidlabs-en2fr.hf.space ✔
hello
'Bonjour.'
Loaded as API: https://gradio-calculator.hf.space ✔
StatusUpdate(code=<Status.STARTING: 'STARTING'>, rank=None, queue_size=None, eta=None, success=None, time=datetime.datetime(2023, 11, 9, 11, 23, 22, 482961), progress_data=None)
Loaded as API: https://gradio-count-generator.hf.space ✔
Client.predict() Usage Info
---------------------------
Named API endpoints: 2
- predict(parameter_2, api_name="/count") -> value_8
Parameters:
- [Number] parameter_2: float
Returns:
- [Textbox] value_8: str
- predict(parameter_2, api_name="/show") -> value_8
Parameters:
- [Number] parameter_2: float
Returns:
- [Textbox] value_8: str
Unnamed API endpoints: 0
Loaded as API: https://abidlabs-test-yield.hf.space ✔
True
Loaded as API: https://law.vmaig.com/ ✔
Client.predict() Usage Info
---------------------------
Named API endpoints: 1
- predict(message, api_name="/chat") -> message
Parameters:
- [Textbox] message: str
Returns:
- [Textbox] message: str
Unnamed API endpoints: 2
- predict(fn_index=8) ->
Parameters:
- None
Returns:
- None
- predict(fn_index=15) ->
Parameters:
- None
Returns:
- None
Loaded as API: https://law.vmaig.com/ ✔
---------------------------------------------------------------------------
InvalidStatusCode Traceback (most recent call last)
c:\Users\30388\Desktop\python\pythontest\gradio_client2.ipynb Cell 7 line 6
3 client = Client("https://law.vmaig.com", auth=("username", "password"))
5 # client.view_api(all_endpoints=True)
----> 6 client.predict("杀人了",api_name="/chat")
File d:\python\lib\site-packages\gradio_client\client.py:305, in Client.predict(self, api_name, fn_index, *args)
301 if self.endpoints[inferred_fn_index].is_continuous:
302 raise ValueError(
303 "Cannot call predict on this function as it may run forever. Use submit instead."
304 )
--> 305 return self.submit(*args, api_name=api_name, fn_index=fn_index).result()
File d:\python\lib\site-packages\gradio_client\client.py:1456, in Job.result(self, timeout)
1441 def result(self, timeout: float | None = None) -> Any:
1442 """
1443 Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised.
1444
ref='d:\python\lib\site-packages\gradio_client\client.py:1'>1</a>;32m (...)
1454 >> 9
1455 """
-> 1456 return super().result(timeout=timeout)
File d:\python\lib\concurrent\futures\_base.py:458, in Future.result(self, timeout)
...
333 self.extensions = self.process_extensions(
334 response_headers, available_extensions
335 )
InvalidStatusCode: server rejected WebSocket connection: HTTP 403
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Loaded as API: http://127.0.0.1:7861/ ✔
Client.predict() Usage Info
---------------------------
Named API endpoints: 1
- predict(wuhu, api_name="/predict") -> output
Parameters:
- [Textbox] wuhu: str
Returns:
- [Textbox] output: str
Unnamed API endpoints: 0
Hello WorldHello!!
Loaded as API: https://abidlabs-music-separation.hf.space/--replicas/zlsmw/ ✔
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
c:\Users\30388\Desktop\python\pythontest\gradio_client2.ipynb Cell 12 line 4
1 from gradio_client import Client
3 client = Client("https://abidlabs-music-separation.hf.space/--replicas/zlsmw/")
----> 4 result = client.predict(
5 "audio_sample.wav",
6 api_name="/predict"
7 )
8 # client.view_api(all_endpoints=True)
9 print(result)
File d:\python\lib\site-packages\gradio_client\client.py:305, in Client.predict(self, api_name, fn_index, *args)
301 if self.endpoints[inferred_fn_index].is_continuous:
302 raise ValueError(
303 "Cannot call predict on this function as it may run forever. Use submit instead."
304 )
--> 305 return self.submit(*args, api_name=api_name, fn_index=fn_index).result()
File d:\python\lib\site-packages\gradio_client\client.py:1456, in Job.result(self, timeout)
1441 def result(self, timeout: float | None = None) -> Any:
1442 """
1443 Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised.
1444
ref='d:\python\lib\site-packages\gradio_client\client.py:1'>1</a>;32m (...)
...
1158 response = requests.post(
1159 self.client.api_url, headers=self.client.headers, data=data
1160 )
ValueError: None
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Loaded as API: https://yuntian-deng-chatgpt4turbo.hf.space ✔
Client.predict() Usage Info
---------------------------
Named API endpoints: 0
Unnamed API endpoints: 5
- predict(fn_index=1) ->
Parameters:
- None
Returns:
- None
- predict(fn_index=2) -> (type_an_input_and_press_enter, value_9)
Parameters:
- None
Returns:
- [Textbox] type_an_input_and_press_enter: str
- [Button] value_9: str
- predict(type_an_input_and_press_enter, topp_nucleus_sampling, temperature, parameter_16, parameter_4, fn_index=3) -> (value_4, value_16, status_code_from_openai_server, type_an_input_and_press_enter, value_9)
Parameters:
- [Textbox] type_an_input_and_press_enter: str
- [Slider] topp_nucleus_sampling: int | float
- [Slider] temperature: int | float
...
- [Textbox] status_code_from_openai_server: str
- [Textbox] type_an_input_and_press_enter: str
- [Button] value_9: str
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Loaded as API: https://abidlabs-music-separation.hf.space/--replicas/zlsmw/ ✔
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
c:\Users\30388\Desktop\python\pythontest\gradio_client2.ipynb Cell 12 line 4
1 from gradio_client import Client
3 client = Client("https://abidlabs-music-separation.hf.space/--replicas/zlsmw/")
----> 4 result = client.predict(
5 "audio_sample.wav",
6 api_name="/predict"
7 )
8 # client.view_api(all_endpoints=True)
9 print(result)
File d:\python\lib\site-packages\gradio_client\client.py:305, in Client.predict(self, api_name, fn_index, *args)
301 if self.endpoints[inferred_fn_index].is_continuous:
302 raise ValueError(
303 "Cannot call predict on this function as it may run forever. Use submit instead."
304 )
--> 305 return self.submit(*args, api_name=api_name, fn_index=fn_index).result()
File d:\python\lib\site-packages\gradio_client\client.py:1456, in Job.result(self, timeout)
1441 def result(self, timeout: float | None = None) -> Any:
1442 """
1443 Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised.
1444
ref='d:\python\lib\site-packages\gradio_client\client.py:1'>1</a>;32m (...)
...
1158 response = requests.post(
1159 self.client.api_url, headers=self.client.headers, data=data
1160 )
ValueError: None
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Loaded as API: https://yuntian-deng-chatgpt4turbo.hf.space ✔
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
c:\Users\30388\Desktop\python\pythontest\gradio_client2.ipynb Cell 14 line 4
1 from gradio_client import Client
3 client = Client("yuntian-deng/ChatGPT4Turbo")
----> 4 client.predict("你的知识截止日期是什么时候?",1,0.5,"1","1", fn_index=3)
File d:\python\lib\site-packages\gradio_client\client.py:305, in Client.predict(self, api_name, fn_index, *args)
301 if self.endpoints[inferred_fn_index].is_continuous:
302 raise ValueError(
303 "Cannot call predict on this function as it may run forever. Use submit instead."
304 )
--> 305 return self.submit(*args, api_name=api_name, fn_index=fn_index).result()
File d:\python\lib\site-packages\gradio_client\client.py:1456, in Job.result(self, timeout)
1441 def result(self, timeout: float | None = None) -> Any:
1442 """
1443 Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised.
1444
ref='d:\python\lib\site-packages\gradio_client\client.py:1'>1</a>;32m (...)
1454 >> 9
1455 """
-> 1456 return super().result(timeout=timeout)
File d:\python\lib\concurrent\futures\_base.py:458, in Future.result(self, timeout)
...
614 def file_to_json(file_path: str | Path) -> dict | list:
--> 615 with open(file_path) as f:
616 return json.load(f)
FileNotFoundError: [Errno 2] No such file or directory: '1'
|
59a46e592770f15787e2b001a28d077c
|
{
"intermediate": 0.2736254632472992,
"beginner": 0.38710200786590576,
"expert": 0.33927255868911743
}
|
30,472
|
<div id="banner">
<ul class="imges">
<li class="img" style="background-image: url(./imags/20231109quanguoxiaofanganquanriwzv2.png);"></li>
<li class="img" style="background-image: url(./imags/20231108lidong.jpg);"></li>
<li class="img" style="background-image: url(./imags/2023421zhutijiaoyu.jpg);"></li>
<li class="img" style="background-image:url(./imags/20221006ershida.jpg)"></li>
<li class="img" style="background-image:url(./imags/20221112ershida.png)"></li>
<li class="img" style="background-image:url(./imags/2023xsh.jpg)"></li>
<li class="img" style="background-image:url(./imags/jianzhuyuyishuxueyuan.png)"></li>
</ul>
<ul class="dots">
<li class="dot"></li>
<li class="dot"></li>
<li class="dot"></li>
<li class="dot"></li>
<li class="dot"></li>
<li class="dot"></li>
<li clsss="dot"></li>
</ul>
</div>#banner{
width:100%;
height:300px;
overflow: hidden;
background-color: red;
}
.images{
width:700%;
height: 100%;
display: flex;
position: absolute;
left: 0;
flex-direction: row;
}
.img{
/* list-style: none; */
width: 100%;
height: 100%;
background-size: cover;
}
在如上代码的实现中,为什么我的图片并不是按照水平方向摆放的,仍然按照列表形式呈现
|
5093719636be7ef01762f427034a8dad
|
{
"intermediate": 0.27944278717041016,
"beginner": 0.42313525080680847,
"expert": 0.29742202162742615
}
|
30,473
|
как ограничить время сканирования для айпи адреса 10 секундами в этом скрипте, то есть не более 10 секунд на опрос одного сервера не дожидаясь получения списка всех файлов в папках
from ftplib import FTP
import time
import os
from os import path
def ftp_recursive_listing(ftp, path='', file=None):
if file is None:
file = open('full_list/' + ftp.host + '.txt', 'w', encoding='utf-8')
ftp.cwd(path)
listing = []
ftp.retrlines('LIST', listing.append)
for line in listing:
parts = line.split(maxsplit=8)
if len(parts) >= 9:
permissions = parts[0]
size = int(parts[4])
file_date = " ".join(parts[5:8])
filename = parts[-1]
if filename == '.' or filename == '…':
continue
full_path_txt = 'ftp://' + ftp.host + path + '/' + filename
full_path = path + '/' + filename
size_mb = size / (1024 * 1024) # Перевод размера в мегабайты
#file.write(f"{full_path} {size_mb:.2f} МБ {file_date}\n")
file.write(f"{full_path_txt}\n")
if permissions.startswith('d'):
ftp_recursive_listing(ftp, full_path, file)
#time.sleep(0.1)
#file.close()
full = os.listdir('full_list/')
ip_open = os.listdir('open_list/')
new = []
for ip in ip_open:
ip_address = os.path.splitext(ip)[0]
if ip_address + '.txt' not in full:
new.append(ip)
for ip in new:
ipa = path.splitext(ip)
ip_address = ipa[0]
print(ip_address)
try:
ftp = FTP(ip_address, timeout=3)
ftp.login()
ftp_recursive_listing(ftp)
ftp.quit()
#time.sleep(0.5)
except Exception as e:
print(f"Ошибка при подключении к FTP-серверу {ip_address}: {e}")
|
9f20aa75c59163efa6f5a81befaf4b47
|
{
"intermediate": 0.31644731760025024,
"beginner": 0.4920382499694824,
"expert": 0.19151443243026733
}
|
30,474
|
Hi, nice to meet you
|
fe58edd6bcab36e9d774b48a3b579a3c
|
{
"intermediate": 0.3540348708629608,
"beginner": 0.2567550837993622,
"expert": 0.389210045337677
}
|
30,475
|
write an autorun file, to execute watchdog.exe when disk is loaded
|
712ffac8758c88788f793c0d62658ebe
|
{
"intermediate": 0.38630810379981995,
"beginner": 0.2518046200275421,
"expert": 0.36188724637031555
}
|
30,476
|
检查下面代码的错误——/*
* 通过分页数据封装类
* Created by macro on Nov.2nd,2023*/
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Page;
import java.util.List;
public class CommonPage<T> {
/*当前页码*/
private Integer pageNum;
/*每页数量*/
private Integer pageSize;
/*总页数*/
private Integer totalPage;
/*总条数*/
private Long total;
/*分页数据*/
private List<T> list;
/*将PageHelper分页后的list转为分页信息
* */
public static <T> CommonPage<T> restPage(List<T>list){
CommonPage<T>result =new CommonPage<T>();
PageInfo<T> pageInfo=new PageInfo<T>(list);
result.setTotalPage(pageInfo.getPages());
result.setPageNum(pageInfo.getPageNum());
result.getPageSize(pageInfo.getPageSize());
return result;
}
public static <T> CommonPage<T> restPage(Page<T>pageInfo) {
CommonPage<T> result = new CommonPage<T>();
result.setTotalPage(pageInfo.getTotalPages());
result.setPageNum(pageInfo.getNumber());
result.getPageSize(pageInfo.getSize());
return result;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public Integer getTotalPage() {
return totalPage;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public Integer getPageNum() {
return pageNum;
}
}
|
b2d8e233145e2c7405700bdf2880ed26
|
{
"intermediate": 0.2985571324825287,
"beginner": 0.3959055542945862,
"expert": 0.30553731322288513
}
|
30,477
|
create c# console menu with choices AddItem, DeleteById, PrintAll and Exit
|
622a479d32faee097442a8bfa642aab3
|
{
"intermediate": 0.39982232451438904,
"beginner": 0.32779785990715027,
"expert": 0.2723798453807831
}
|
30,478
|
Frontend (User Interface)
Dashboard: To provide a quick glance at financial summaries like expenses, income, savings, investments, debts, etc.
Transaction Management: Allows users to add, modify, categorize, or delete transactions.
Budget Management: Lets users set up monthly/weekly budgets for various categories.
Investment Tracker: Track stocks, mutual funds, or other investments.
Debt Manager: Helps users track their debts and loans.
Reports and Analytics: Graphical representation of expenses, income trends, category- wise spends, etc.
Notifications: Alerts for overspending, bill due dates, budget limits, etc.
Backend (Server)
User Management Service: Handle user registration, login, password resets, and profile management.
Transaction Service: Manage all transaction-related operations and ensure data integrity.
Budget Service: Handle budget setting, updating, and validation.
Analytics Engine: Process and analyze the data to generate insights, trends, and reports.
Notification Service: Sends out reminders, alerts, or suggestions to users.
Database
User Data: Stores user profile, login credentials (hashed and salted), settings, etc.
Transactions: All income, expense, and transfer transactions.
Budgets: Defined budgets for various categories and periods.
Investments and Debts: Information about user investments and loans.
External Integrations
Banking APIs: To automatically fetch transaction data from various banks or financial institutions.
Stock Market APIs: For tracking real-time stock or mutual fund data.
Currency Conversion APIs: If the app supports multiple currencies.
Payment Gateways: If the app supports bill payments or transfers.
Security
Data Encryption: Ensuring data at rest and in transit is encrypted.
Authentication and Authorization: Ensuring only legitimate users can access their data.
Regular Audits and Monitoring: Continuously monitor for any suspicious activities.
Secure APIs: Making sure that the APIs (especially banking ones) are secure, authenticated, and cannot be misused.
Additional Features
AI-based Recommendations: Suggesting financial tips, investment opportunities, or savings tips based on user behaviour.
Tax Planning: Helping users plan and save on taxes based on their income and spending.
Savings Goals: Allow users to set saving goals like buying a house, car, or going on a vacation. This is a broad overview of what a PFM system might entail. Depending on the target audience, region (due to financial regulations), and platform (web, mobile, or both), the specifics can vary. It's also vital to ensure regular feedback loops with potential users to iterate and improve upon the design
make me a UML package diagram for the above info and add to each class more attribute and add methods to each class and make it via plantuml
|
7e46beb5f862f66046352ae58be4baf3
|
{
"intermediate": 0.33496594429016113,
"beginner": 0.32646873593330383,
"expert": 0.3385653495788574
}
|
30,479
|
Hi, we are gonna write C code. Implement a datastructure capable of holding 128 binary values (booleans). We will use bitwise operations to manipulate the data within that structure.
|
3eef44b48a5f4dbcfac07d0eafdae9ec
|
{
"intermediate": 0.32538041472435,
"beginner": 0.18305200338363647,
"expert": 0.49156761169433594
}
|
30,480
|
как запустить браузер в headless режиме с помощью selenium
|
591922f5786027bd64080a6270d16b39
|
{
"intermediate": 0.30885782837867737,
"beginner": 0.2741626501083374,
"expert": 0.4169795513153076
}
|
30,481
|
измени код так чтобы он не пытался сканировать папки . и ..
from ftplib import FTP
import time
import os
from os import path
import threading
def ftp_recursive_listing(ftp, path='', file=None):
if file is None:
file = open('full_list/' + ftp.host + '.txt', 'w', encoding='utf-8')
def retrieve_listing():
ftp.cwd(path)
listing = []
ftp.retrlines('LIST', listing.append)
for line in listing:
parts = line.split(maxsplit=8)
if len(parts) >= 9:
permissions = parts[0]
size = int(parts[4])
file_date = " ".join(parts[5:8])
filename = parts[-1]
if filename == '.' or filename == '…':
continue
full_path_txt = 'ftp://' + ftp.host + path + '/' + filename
full_path = path + '/' + filename
size_mb = size / (1024 * 1024) # Перевод размера в мегабайты
#file.write(f"{full_path} {size_mb:.2f} МБ {file_date}\n")
file.write(f"{full_path_txt}\n")
if permissions.startswith('d'):
ftp_recursive_listing(ftp, full_path, file)
file.close()
retrieve_thread = threading.Thread(target=retrieve_listing)
retrieve_thread.start()
retrieve_thread.join(timeout=10) # Ограничение времени выполнения до 10 секунд
full = os.listdir('full_list/')
ip_open = os.listdir('open_list/')
new = []
for ip in ip_open:
ip_address = os.path.splitext(ip)[0]
if ip_address + '.txt' not in full:
new.append(ip)
for ip in new:
ipa = path.splitext(ip)
ip_address = ipa[0]
print(ip_address)
try:
ftp = FTP(ip_address, timeout=3)
ftp.login()
ftp_recursive_listing(ftp)
ftp.quit()
except Exception as e:
print(f"Ошибка при подключении к FTP-серверу {ip_address}: {e}")
|
a063dcb866e031e15dfa38ecc7296f39
|
{
"intermediate": 0.2788405418395996,
"beginner": 0.5251303911209106,
"expert": 0.19602903723716736
}
|
30,482
|
CASE
WHEN fcd.FCDModifiedDLRValue = 0 OR fcd.FCDModifiedDLRValue IS NULL THEN fcd.FCDInvoiceDLRValue
ELSE fcd.FCDModifiedDLRValue
END AS value, (FCDModifiedDLRValue-fcd.FCDInvoiceDLRValue)- FCDModifiedDLRValue/100 AS contribution_percentage, i want it one code
|
c9ba015fad0a01aea19d0e54e2f0021f
|
{
"intermediate": 0.3147629499435425,
"beginner": 0.4406324326992035,
"expert": 0.24460460245609283
}
|
30,483
|
Can you write me a code for a library management
|
80f2adc185a827ae8a23dfc5b403fcef
|
{
"intermediate": 0.7193499207496643,
"beginner": 0.17311470210552216,
"expert": 0.10753540694713593
}
|
30,484
|
can you use Generics instead of Union Types in this piece of code?
import * as React from 'react'
import { Box, BoxProps, Icon, RichText, RichTextProps, TextLink, TextPreset } from '../..'
import type { LinkHtmlProps } from '../../../definition/HTMLAttributes'
import type { WithChildren } from '../../../definition/ReactElementChildren'
import type { IconographyProps } from '../../iconography/Iconography'
import * as styles from './Faq.css'
type FaqsDesignProps =
| {
_tag: 'default'
isOpen?: boolean
onOpen?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void
onClose?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void
}
| {
_tag: 'unCollapsible'
}
export interface FaqProps extends WithChildren {
element: React.ReactNode
titleComponent?: BoxProps['component']
link?: LinkHtmlProps
icon?: React.ReactElement<IconographyProps>
children: RichTextProps['children']
design?: FaqsDesignProps
}
export const Faq: React.FC<FaqProps> = ({
element,
titleComponent = 'h3',
icon,
link,
children,
design = { _tag: 'default' },
}) => {
const [open, setOpen] = React.useState((design._tag === 'default' && design.isOpen) ?? false)
// eslint-disable-next-line no-nested-ternary
const boxShadow = design._tag === 'unCollapsible' ? undefined : open ? 'drop-2' : 'drop-1'
const maxHeight = design._tag === 'default' && open ? '800px' : '0'
return (
<Box
borderRadius="xs"
backgroundColor="white"
overflow={design._tag === 'default' ? 'hidden' : undefined}
boxShadow={boxShadow}
>
<Box
onClick={
design._tag === 'unCollapsible'
? undefined
: e => {
const s = !open
setOpen(s)
if (s) {
design.onOpen && design.onOpen(e)
} else {
design.onClose && design.onClose(e)
}
}
}
paddingRight="m"
cursor={design._tag === 'default' ? 'pointer' : undefined}
display="flex"
justifyContent="spaceBetween"
alignItems="center"
>
<Box
padding="s"
border="primary300-m-left"
className={styles.titleBorder}
display="inlineFlex"
alignItems="flexStart"
>
{icon && React.cloneElement(icon, { scale: 1.5, fontColor: 'primary300' })}
<TextPreset
component={titleComponent}
preset="title-xs"
fontWeight="bold"
marginLeft={icon ? 'xs' : undefined}
>
{link ? <TextLink {...link}>{element}</TextLink> : element}
</TextPreset>
</Box>
{design._tag === 'default' && (
<Box flexShrink={0}>
<Icon name="chevronSmall" direction={open ? 'up' : 'down'} fontColor="grey300" scale={1.5} />
</Box>
)}
</Box>
<Box transition="medium" style={{ maxHeight: design._tag === 'default' && !open ? maxHeight : undefined }}>
<RichText
component="p"
className={styles.faqContent}
border={design._tag === 'default' ? 'neutralWarm300-s-all' : undefined}
paddingX="m"
paddingY={design._tag === 'default' ? 'm' : 'xxs'}
fontColor="grey500"
>
{children}
</RichText>
</Box>
</Box>
)
}
|
0962da8270a8c14d982c4de398b504cf
|
{
"intermediate": 0.4115172326564789,
"beginner": 0.4404626786708832,
"expert": 0.14802011847496033
}
|
30,485
|
Transcribe the python code below into C: import numpy as np
# Read and preprocess the input data
data = open('input.txt', 'r').read()
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print(f'Data has {data_size} characters, {vocab_size} unique.')
char_to_ix = {ch: i for i, ch in enumerate(chars)}
ix_to_char = {i: ch for i, ch in enumerate(chars)}
# Hyperparameters
hidden_size = 200
seq_length = 50
learning_rate = 1e-1
# Model parameters
Wxh = np.random.randn(hidden_size, vocab_size) * 0.01
Whh = np.random.randn(hidden_size, hidden_size) * 0.01
Why = np.random.randn(vocab_size, hidden_size) * 0.01
bh = np.zeros((hidden_size, 1))
by = np.zeros((vocab_size, 1))
def forwardPass(inputs, targets, hprev):
xs, hs, ys, ps = {}, {}, {}, {}
hs[-1] = np.copy(hprev)
loss = 0
for t in range(len(inputs)):
xs[t] = np.zeros((vocab_size, 1))
xs[t][inputs[t]] = 1
hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh)
ys[t] = np.dot(Why, hs[t]) + by
ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t]))
loss += -np.log(ps[t][targets[t], 0])
return xs, hs, ys, ps, loss
def backwardPass(xs, hs, ps, targets):
dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
dbh, dby = np.zeros_like(bh), np.zeros_like(by)
dhnext = np.zeros_like(hs[0])
for t in reversed(range(len(xs))):
dy = np.copy(ps[t])
dy[targets[t]] -= 1
dWhy += np.dot(dy, hs[t].T)
dby += dy
dh = np.dot(Why.T, dy) + dhnext
dhraw = (1 - hs[t] * hs[t]) * dh
dbh += dhraw
dWxh += np.dot(dhraw, xs[t].T)
dWhh += np.dot(dhraw, hs[t-1].T)
dhnext = np.dot(Whh.T, dhraw)
for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
np.clip(dparam, -5, 5, out=dparam)
return dWxh, dWhh, dWhy, dbh, dby
def sample(h, seed_ix, n):
x = np.zeros((vocab_size, 1))
x[seed_ix] = 1
ixes = []
for t in range(n):
h = np.tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh)
y = np.dot(Why, h) + by
p = np.exp(y) / np.sum(np.exp(y))
ix = np.random.choice(range(vocab_size), p=p.ravel())
x = np.zeros((vocab_size, 1))
x[ix] = 1
ixes.append(ix)
return ixes
def train():
n, p = 0, 0
mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by)
smooth_loss = -np.log(1.0/vocab_size) * seq_length
while True:
if p + seq_length + 1 >= len(data) or n == 0:
hprev = np.zeros((hidden_size, 1))
p = 0
inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]]
targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]]
if n % 100 == 0:
sample_ix = sample(hprev, inputs[0], seq_length)
txt = ''.join(ix_to_char[ix] for ix in sample_ix)
inpt = ''.join(ix_to_char[ix] for ix in inputs)
print(f'Epoch {n}, loss: {smooth_loss}\n')
print ("Input: " + inpt)
print ("Output: " + txt)
print ('\n----\n')
xs, hs, ys, ps, loss = forwardPass(inputs, targets, hprev)
smooth_loss = smooth_loss * 0.999 + loss * 0.001
dWxh, dWhh, dWhy, dbh, dby = backwardPass(xs, hs, ps, targets)
for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]):
mem += dparam * dparam
param += -learning_rate * dparam / np.sqrt(mem + 1e-8)
p += seq_length
n += 1
# Call the training function to start training
train()
|
a2ef58ee05a0f3dd97bd9f0695c5eec6
|
{
"intermediate": 0.2124457061290741,
"beginner": 0.44828033447265625,
"expert": 0.33927395939826965
}
|
30,486
|
how to create a simple function in Excel vba
|
579059cff3b7a32747093099b39c3d56
|
{
"intermediate": 0.26829594373703003,
"beginner": 0.6016709208488464,
"expert": 0.13003310561180115
}
|
30,487
|
apply Universal Sentence Encoder (USE) on Quora them use BILSTM-GRN
|
144ab51a5aa75406ce0c20de4cee275c
|
{
"intermediate": 0.3128644824028015,
"beginner": 0.13855721056461334,
"expert": 0.5485783219337463
}
|
30,488
|
import React from 'react';
import { inject, observer } from 'mobx-react';
import Loadable from 'react-loadable';
import EmergencyNotification from 'components/common/EmergencyNotification';
import PlaybackControls from 'components/PlaybackControls';
import RouteEditingBar from 'components/RouteEditingBar';
import Scene from 'components/Scene';
import StatusBar from 'components/StatusBar';
import SensorCamera from 'components/Tasks/SensorCamera';
const Navigation = Loadable({
loader: () => import('components/Navigation'),
loading() {
return <div className="navigation-view">Loading...</div>;
},
});
@inject('store') @observer
class SceneView extends React.Component {
render() {
const {
dimension, meters, monitor,
hmi, options, trafficSignal,
} = this.props.store;
return (
<React.Fragment>
<Scene
width={dimension.scene.width}
height={dimension.scene.height}
options={options}
shouldDisplayOnRight={dimension.shouldDivideSceneAndMapSpace}
/>
{monitor.isSirenOn &&
<EmergencyNotification msg="Emergency Siren Detected" />}
{options.showRouteEditingBar
? <RouteEditingBar />
: (options.showTasks ||
<StatusBar
meters={meters}
trafficSignal={trafficSignal}
showNotification={!options.showTasks}
showPlanningRSSInfo={options.showPlanningRSSInfo}
monitor={monitor}
/>
)}
{OFFLINE_PLAYBACK && <PlaybackControls />}
{hmi.shouldDisplayNavigationMap
&& (
<Navigation
onResize={() => dimension.toggleNavigationSize()}
hasRoutingControls={hmi.inNavigationMode}
{...dimension.navigation}
/>
)}
</React.Fragment>
);
}
}
@inject('store') @observer
class LoadSensorCamera extends React.Component {
render() {
const { options } = this.props;
return (
<React.Fragment>
{(options.showVideo && !options.showPNCMonitor)
&& <SensorCamera />}
</React.Fragment>
);
}
}
@inject('store') @observer
export default class MainView extends React.Component {
render() {
const { isInitialized, dimension } = this.props.store;
const height = dimension.main.height;
return (
<div className="main-view" style={{ height }}>
{(!isInitialized && !OFFLINE_PLAYBACK) ? <LoadSensorCamera /> : <SceneView />}
</div>
);
}
}
LoadSensorCamera有问题,该如何修改能正常显示<LoadSensorCamera />
|
59439df6c8d70eef717ef80d5f80e483
|
{
"intermediate": 0.3994932472705841,
"beginner": 0.4845307469367981,
"expert": 0.1159759908914566
}
|
30,489
|
this html javascript function code does not remove a label of an input element properly, please fix
function display2()
{
var checkboxes = document.querySelectorAll("input");
var label = document.querySelectorAll("label");
var br = document.querySelectorAll("br");
for(var i = 0; i <= checkboxes.length; i++)
{
var attr = checkboxes[i].getAttribute("type");
if(checkboxes[i].checked==true && attr=="checkbox")
{
var elem4 = document.getElementById('box1');
elem4.removeChild(br[i]);
elem4.removeChild(checkboxes[i]);
elem4.removeChild(label[i]);
}
}
|
a475f167abf795a95d456b4057fc05d9
|
{
"intermediate": 0.4160742163658142,
"beginner": 0.3327096402645111,
"expert": 0.2512161433696747
}
|
30,490
|
Design a web page that contains two paragraphs (p1, p2) with 12pt font size.
The font size increases by 1pt each time the user clicks on paragraph p1.
The font size goes back to 12pt when the user clicks on the p2 paragraph.
|
2114e8fd1fbfd0a5ea11b32f95bb70fc
|
{
"intermediate": 0.35352444648742676,
"beginner": 0.3194178342819214,
"expert": 0.32705771923065186
}
|
30,491
|
get paretns and his parents with recurcive cte in sqlalchemy
|
a3d23681e5d6971026412b1a7aa4a176
|
{
"intermediate": 0.32595348358154297,
"beginner": 0.35560736060142517,
"expert": 0.3184391260147095
}
|
30,492
|
请为以下api后端构建一个react前端:
# from flask import Flask, request, jsonify, render_template, url_for
# from gradio_client import Client
# app = Flask(__name__)
# # 创建 Gradio 客户端
# client = Client("stabilityai/stable-diffusion")
# @app.route('/')
# def index():
# # 返回前端HTML页面
# return render_template('index.html')
# @app.route('/generate-image', methods=['POST'])
# # def generate_image():
# # # 从前端获取参数
# # description = request.form['description']
# # style = request.form['style']
# # level = request.form['level']
# # # 调用 Gradio API,fn_index=1 可能需要根据实际API进行调整
# # image_path = client.predict(description, style, level, fn_index=1)
# # # 返回图片路径
# # return jsonify({'image_path': image_path})
# @app.route("/generate-image", methods=["POST"])
# def generate_image():
# # 从前端获取参数
# description = request.form['description']
# style = request.form['style']
# level = request.form['level']
# # 调用 Gradio API
# image_path = client.predict(description, style, level, fn_index=1)
# # 这假设返回的是一个本地文件路径
# # 把本地路径转换成在服务器上的URL
# image_url = url_for('static', filename=image_path.split('/')[-1])
# return jsonify({'image_path': image_url})
# if __name__ == '__main__':
# app.run(debug=True)
from flask import Flask, request, jsonify, render_template, send_from_directory
import os
from gradio_client import Client
app = Flask(__name__) # 创建 Flask 应用
# 创建 Gradio 客户端
client = Client("stabilityai/stable-diffusion")
# 主页路由
@app.route('/')
def index():
return render_template('index.html') # 渲染主页模板
# 生成图像的路由
@app.route('/generate-image', methods=['POST'])
def generate_image():
description = request.form['description'] # 从表单获取描述
style = request.form['style'] # 从表单获取风格
level = request.form['level'] # 从表单获取质量
image_path = client.predict(description, style, level, fn_index=1) # 使用 Gradio 客户端生成图像
return jsonify({'image_path': image_path}) # 返回图像路径
# 获取图像的路由
@app.route('/image/<path:filename>')
def get_image(filename):
temp_folder = os.path.join(os.getenv('APPDATA'), 'Local', 'Temp', 'gradio') # 临时文件夹路径
return send_from_directory(temp_folder, filename) # 从临时文件夹发送图像
if __name__ == '__main__':
app.run(debug=True) # 运行 Flask 应用,开启调试模式
|
4a6578867c14e33e0bfb8a809ed3b2d8
|
{
"intermediate": 0.35941818356513977,
"beginner": 0.537997305393219,
"expert": 0.1025845929980278
}
|
30,493
|
apply USE on Quora dataset then apply BiLSTM-GRN
|
9ebed016aadf00e9e3f9abf4d85881c1
|
{
"intermediate": 0.2567375898361206,
"beginner": 0.16971006989479065,
"expert": 0.5735523104667664
}
|
30,494
|
Clean the text data by removing special characters, HTML tags, and irrelevant elements using regular expressions or built-in functions.
|
033a8b73ce6d6a20c93f8dd8fb0fba79
|
{
"intermediate": 0.4669475853443146,
"beginner": 0.23320063948631287,
"expert": 0.29985177516937256
}
|
30,495
|
Rewrite using Python “F(2) + F(10)/F(1) * F(4)” to “2 + 10/1 * 4)
|
242503e001061aa593db85091000a5c3
|
{
"intermediate": 0.28645458817481995,
"beginner": 0.4703731834888458,
"expert": 0.24317224323749542
}
|
30,496
|
Please write code of CNN for video stabilization using pytorch lightning, python and opencv.
|
df370e7f3bbd0b0b4437d299af73cc96
|
{
"intermediate": 0.20623211562633514,
"beginner": 0.04264088347554207,
"expert": 0.7511270046234131
}
|
30,497
|
bitrix
(new ReferenceField(
'CREDIT_ACTIVITY',
'Patio\Credit\Entity\CreditActivityTable',
[
'=this.CREDIT_ACT_XML_ID' => 'ref.XML_ID',
'<=ref.CREDIT_DATE' => 'NOW()',
],
['join_type' => 'LEFT']
))
как еще добавить условие, что ref.CREDIT_DATE должно брать максимальное из найденных
|
910ec9617729f66d330ee389b373701f
|
{
"intermediate": 0.39302343130111694,
"beginner": 0.3163825273513794,
"expert": 0.2905940115451813
}
|
30,498
|
ValueError Traceback (most recent call last)
<ipython-input-219-ef39090235d0> in <cell line: 41>()
39
40 image = cv2.imread("0.0/01.pgm")
---> 41 triangle_vertices = find_triangle_vertices(image)
42 print(triangle_vertices)
<ipython-input-219-ef39090235d0> in find_triangle_vertices(image)
22 neighbors.append(blurred_image[y + 1, x])
23
---> 24 if len(neighbors) == 4 and pixel_value > max(neighbors) and pixel_value > 100:
25 triangle_vertices.append((x, y))
26 if len(triangle_vertices) == 3:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
|
2d7d05efb3e277a2554c968cf60b49f1
|
{
"intermediate": 0.35845041275024414,
"beginner": 0.4098272919654846,
"expert": 0.23172229528427124
}
|
30,499
|
email how to do follow up on email I already sent on the battery issue with admin team
|
cbcc334152fef57448685c370d34ec84
|
{
"intermediate": 0.3673268258571625,
"beginner": 0.32857826352119446,
"expert": 0.3040948808193207
}
|
30,500
|
change this table so that the row A is centred vertically: \usepackage{multirow}
\begin{table}[]
\begin{tabular}{llllll}
& & \multicolumn{2}{c}{B} & & \\
& & \multicolumn{1}{c}{1} & 2 & & \\ \cline{3-4}
\multirow{2}{*}{A} & \multicolumn{1}{r|}{1} & \multicolumn{1}{l|}{-2,2} & \multicolumn{1}{l|}{3,-3} & & \\ \cline{3-4}
& \multicolumn{1}{l|}{2} & \multicolumn{1}{l|}{3,-3} & \multicolumn{1}{l|}{4,-4} & & \\ \cline{3-4}
& & & & &
\end{tabular}
\end{table}
|
7bdf05b2b4489ea285509458e227f3be
|
{
"intermediate": 0.3852662742137909,
"beginner": 0.3662762939929962,
"expert": 0.24845749139785767
}
|
30,501
|
act as a professional front end developer and update the code for containing the sudoku puzzle inside a translucent glass frame without changing any existing functionality -
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="description"
content="Sudoku Wizard helps in solving Sudoku puzzles and visualizing how these puzzles are solved."
/>
<meta
name="keywords"
content="sudoku wizard, sudoku game, sudoku solver, solve sudoku, sudoku puzzle, puzzle games, brain games"
/>
<meta
property="og:description"
content="Get your Sudoku Puzzle solved with zero effort!"
/>
<meta
property="og:image"
content="https://sudoku-wizard.shibamsaha.dev/logo.ico"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sudoku Wizard</title>
<link rel="icon" type="image/x-icon" href="./logo.ico" />
</head>
<!-- Body Starts -->
<body
id="body"
class="m-0 p-0 min-h-screen hidden bg-gray-100 text-black font-poppins grid-rows-[50px_1fr_50px] sm:grid-rows-[70px_1fr_70px] place-items-center animate-reveal"
>
<!-- Navigation Bar Starts -->
<nav
class="px-3 sm:px-10 h-full flex items-center justify-between w-full bg-black/10"
>
<!-- Logo Starts -->
<img
src="./logo.ico"
alt="Logo Image"
class="w-8 sm:w-14 cursor-pointer drop-shadow-md"
id="logo"
/>
<!-- Logo Ends -->
<!-- Site Name Starts -->
<p class="text-2xl sm:text-4xl font-extrabold tracking-wider select-none">
<span class="text-[#75327C]"> MIND </span>
<span class="text-[#7373E2]"> MATRIX </span>
</p>
<!-- Site Name Ends -->
<!-- What is Sudoku? Starts -->
<button id="open-modal">
<img
src="./question.png"
alt="How To play?"
id="how-to-play"
data-tooltip-target="tooltip-how-to-play"
data-tooltip-trigger="hover"
data-tooltip-placement="bottom"
class="w-8 sm:w-14 cursor-pointer drop-shadow-md"
/>
</button>
<div
id="tooltip-how-to-play"
role="tooltip"
class="tooltip absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-black bg-amber-400 rounded-lg shadow-sm opacity-0 transition-opacity delay-500"
>
How to play?
</div>
<!-- What is Sudoku? Ends -->
</nav>
<!-- Navigation Bar Ends -->
<!-- Container Starts -->
<div
class="container max-w-full flex justify-center items-center gap-3 flex-col lg:flex-row"
>
<!-- Left Container Parts Starts -->
<div class="flex flex-col gap-3 justify-center items-center">
<!-- Sudoku Board/Grid Starts -->
<div
class="sudoku-board mt-12 mx-8 h-[300px] sm:h-[500px] w-[300px] sm:w-[500px] flex flex-wrap"
>
<!-- Sudoku Cells (Injected by JavaScript)-->
</div>
<!-- Sudoku Board/Grid Ends -->
<!-- Visualization Toggle Button Starts -->
<label class="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
id="slow-visualization"
class="sr-only peer"
checked
/>
<div
class="w-11 h-6 bg-gray-400 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-400 peer-disabled:opacity-50 peer-disabled:cursor-not-allowed"
></div>
<span class="ml-3 text-base font-medium text-gray-900"
>Slow Visualization</span
>
</label>
<!-- Visualization Toggle Button Ends -->
</div>
<!-- Left Container Parts Ends -->
<!-- Sudoku Controls Starts -->
<div class="control-panel flex flex-col justify-center items-center">
<!-- Sudoku Status Starts -->
<div
id="sudoku-status"
class="sudoku-status text-2xl sm:text-4xl font-bold"
>
<!-- Sudoku Status Displayed Here -->
</div>
<!-- Sudoku Status Ends -->
<!-- Sudoku Input Option Starts -->
<div
class="number-plate mx-8 my-4 grid grid-cols-5 content-center items-center gap-2"
>
<!-- Number Buttons (Injected by JavaScript)-->
</div>
<!-- Sudoku Input Option Ends -->
<!-- Sudoku Action Option Starts -->
<div
class="action-option mt-2 grid grid-cols-3 content-center items-center gap-1"
>
<button
data-tooltip-target="tooltip-start"
data-tooltip-trigger="hover"
data-tooltip-placement="bottom"
type="button"
class="action-button"
id="start"
>
<svg
class="w-4 sm:w-6"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 384 512"
>
<path
d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"
/>
</svg>
</button>
<div
id="tooltip-start"
role="tooltip"
class="tooltip absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-black bg-amber-400 rounded-lg shadow-sm opacity-0 transition-opacity delay-700"
>
Solve Puzzle!
<div class="tooltip-arrow" data-popper-arrow></div>
</div>
<button
data-tooltip-target="tooltip-reset"
data-tooltip-trigger="hover"
data-tooltip-placement="bottom"
type="button"
class="action-button"
id="reset"
>
<svg
class="w-6 sm:w-8"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
>
<path
d="M463.5 224H472c13.3 0 24-10.7 24-24V72c0-9.7-5.8-18.5-14.8-22.2s-19.3-1.7-26.2 5.2L413.4 96.6c-87.6-86.5-228.7-86.2-315.8 1c-87.5 87.5-87.5 229.3 0 316.8s229.3 87.5 316.8 0c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0c-62.5 62.5-163.8 62.5-226.3 0s-62.5-163.8 0-226.3c62.2-62.2 162.7-62.5 225.3-1L327 183c-6.9 6.9-8.9 17.2-5.2 26.2s12.5 14.8 22.2 14.8H463.5z"
/>
</svg>
</button>
<div
id="tooltip-reset"
role="tooltip"
class="tooltip absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-black bg-amber-400 rounded-lg shadow-sm opacity-0 transition-opacity delay-700"
>
Reset Puzzle!
<div class="tooltip-arrow" data-popper-arrow></div>
</div>
<button
data-tooltip-target="tooltip-random"
data-tooltip-trigger="hover"
data-tooltip-placement="bottom"
type="button"
class="action-button"
id="random"
>
<svg
class="w-6 sm:w-8"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
>
<path
d="M403.8 34.4c12-5 25.7-2.2 34.9 6.9l64 64c6 6 9.4 14.1 9.4 22.6s-3.4 16.6-9.4 22.6l-64 64c-9.2 9.2-22.9 11.9-34.9 6.9s-19.8-16.6-19.8-29.6V160H352c-10.1 0-19.6 4.7-25.6 12.8L284 229.3 244 176l31.2-41.6C293.3 110.2 321.8 96 352 96h32V64c0-12.9 7.8-24.6 19.8-29.6zM164 282.7L204 336l-31.2 41.6C154.7 401.8 126.2 416 96 416H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H96c10.1 0 19.6-4.7 25.6-12.8L164 282.7zm274.6 188c-9.2 9.2-22.9 11.9-34.9 6.9s-19.8-16.6-19.8-29.6V416H352c-30.2 0-58.7-14.2-76.8-38.4L121.6 172.8c-6-8.1-15.5-12.8-25.6-12.8H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H96c30.2 0 58.7 14.2 76.8 38.4L326.4 339.2c6 8.1 15.5 12.8 25.6 12.8h32V320c0-12.9 7.8-24.6 19.8-29.6s25.7-2.2 34.9 6.9l64 64c6 6 9.4 14.1 9.4 22.6s-3.4 16.6-9.4 22.6l-64 64z"
/>
</svg>
</button>
<div
id="tooltip-random"
role="tooltip"
class="tooltip absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-black bg-amber-400 rounded-lg shadow-sm opacity-0 transition-opacity delay-700"
>
Random Puzzle!
<div class="tooltip-arrow" data-popper-arrow></div>
</div>
</div>
<!-- Sudoku Action Option Ends -->
</div>
<!-- Sudoku Controls Ends -->
</div>
<!-- Container Ends -->
<!-- Footer Starts -->
<footer
class="flex flex-col mt-auto mb-2 items-center justify-center text-xs xl:text-sm text-black"
>
<div>
For Code Visit -
<a
href="https://github.com/s4shibam/sudoku-wizard"
class="hover:underline"
target="_blank"
>GitHub</a
>
</div>
</footer>
<!-- Footer Ends -->
<!-- Modal Starts -->
<div id="modal-bg" class="fixed z-10 inset-0 overflow-y-auto hidden">
<div class="flex items-center justify-center min-h-screen bg-black/50">
<div
class="modal-container bg-white w-[90%] max-w-5xl aspect-video mx-auto rounded-lg shadow-lg p-4"
>
<!-- Video Player with Autoplay -->
<div class="relative overflow-hidden rounded-lg">
<video
id="modal-video"
class="w-full aspect-video"
controls
poster="./poster.png"
>
<source src="./sudoku-wizard-tutorial.mp4" type="video/mp4" />
Your browser does not support the video format.
</video>
</div>
</div>
</div>
</div>
<!-- Modal Ends -->
<script type="module" src="/main.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/1.6.2/flowbite.min.js"></script>
</body>
<!-- Body Ends -->
</html>
|
d81a4b8366f8bb8651eb504ce81ac073
|
{
"intermediate": 0.38076770305633545,
"beginner": 0.4091032147407532,
"expert": 0.21012908220291138
}
|
30,502
|
how to add another html page to another html page. how to link opening page to as button
|
d4902c9a10518c494da01303460b56cd
|
{
"intermediate": 0.4564637243747711,
"beginner": 0.244014710187912,
"expert": 0.2995215952396393
}
|
30,503
|
(new ReferenceField(
'CREDIT_ACTIVITY',
'Patio\Credit\Entity\CreditActivityTable',
[
'=this.CREDIT_ACT_XML_ID' => 'ref.XML_ID',
'=ref.CREDIT_DATE' => (new ExpressionField(
'MAX_CREDIT_DATE',
'(SELECT MAX(date) FROM patio_credit_credit_activity WHERE CREDIT_ACT_XML_ID=this.CREDIT_ACT_XML_ID and CREDIT_DATE <= NOW() )'))
],
['join_type' => 'LEFT']
))
отдает ошибку Object of class Bitrix\Main\Entity\ExpressionField could not be converted to string
|
a8a7474d10d63a446f9a0e79493dbac8
|
{
"intermediate": 0.3200374245643616,
"beginner": 0.3598648011684418,
"expert": 0.32009777426719666
}
|
30,504
|
Following code throws an error
CREATE TYPE value_link_obj AS (
link VARCHAR(1023),
);
CREATE TYPE video_data_call_to_action AS (
type VARCHAR(255),
value value_link_obj
);
|
b04d8492a34c9484ae9b6e6123813133
|
{
"intermediate": 0.4018532931804657,
"beginner": 0.3708769977092743,
"expert": 0.22726970911026
}
|
30,505
|
How to add currency symbol in the column title as per selection of country and if the country is not selected then not currency is visible in power bi report
|
fd80c8bce8e27ccd331060489aaaf192
|
{
"intermediate": 0.24513228237628937,
"beginner": 0.20462344586849213,
"expert": 0.5502442717552185
}
|
30,506
|
dates = []
dt = datetime.datetime.strptime('2023-01-18 15:11:00.123', "%Y-%m-%d %H:%M:%S.%f")
year.append(dt.year)
month.append(dt.month)
day.append(dt.day)
hour.append(dt.hour)
minute.append(dt.minute)
second.append(dt.second)
start_date = datetime.datetime(int(dt.year), int(dt.month), int(dt.day), int(dt.hour), int(dt.minute), int(dt.second)) # (5,24) (5,25) august
dates.append(start_date)
dt = datetime.datetime.strptime('2023-01-19 15:11:00.123', "%Y-%m-%d %H:%M:%S.%f")
year.append(dt.year)
month.append(dt.month)
day.append(dt.day)
hour.append(dt.hour)
minute.append(dt.minute)
second.append(dt.second)
start_date = datetime.datetime(int(dt.year), int(dt.month), int(dt.day), int(dt.hour), int(dt.minute), int(dt.second)) # (5,24) (5,25) august
dates.append(start_date)
Как на Python узнать разницу в минутах и часах между двумя датами в dates?
|
bfb610cfd48b472ed08dcc3b206c251b
|
{
"intermediate": 0.4050140678882599,
"beginner": 0.3422435522079468,
"expert": 0.25274237990379333
}
|
30,507
|
How to use the Landweber iteration method for inverse source problem of parabolic equation, give me the python code
|
827f2b2155955a97388530ae491ba9ec
|
{
"intermediate": 0.1653032749891281,
"beginner": 0.11995188891887665,
"expert": 0.7147448062896729
}
|
30,508
|
#include <iostream>
#include <fstream>
using namespace std;
long long n,i,ans,a[10],k,x,y;
int main()
{
ifstream cin("input.txt");
ofstream cout("output.txt");
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cin>>x>>y;
k=0;
for(i=0;i<n-1;i++)
{
css
Copy code
if(a[i]==x)
{
k=1+i;
break;
}
}
if(k)cout<<k;
else cout<<"No";
kotlin
Copy code
return 0;
}
Прочитайте из первой строки число n, n ≤ 10, со второй строки – n элементов ai, с третьей
строки – числа x и y, x ≤ y.
В первой строке файла выведите в порядке следования те элементы ai, которые находятся на
интервале x..y: x ≤ ai ≤ y.
input.txt
6
0 70 40 10 50 40
20 60
output.txt
40 50 40 обясни мне мои ошибки а код не скидывай
|
5614da138b7f3721a6368786e78cf98c
|
{
"intermediate": 0.3485080301761627,
"beginner": 0.3790935277938843,
"expert": 0.2723984122276306
}
|
30,509
|
hi can you help me write a autolsp script?
|
f3017f0b14f32bbf79f5bd7a7058568b
|
{
"intermediate": 0.2975040078163147,
"beginner": 0.17527838051319122,
"expert": 0.5272175669670105
}
|
30,510
|
import { redirect } from "react-router-dom"
export function requieAuth({ request }) {
const q = new URL(request.url).searchParams.get('q')
//if there are more query in the url,i have to repeat this pattern
//how to preserve the previous query and append something to it before redirect
const isloggin = false
if (!isloggin) {
return redirect(`/login?message=you-must-login-first&q=${q}`)
}
return null
}
|
51866ea0ec1d5d851a466f3db4b15108
|
{
"intermediate": 0.48054996132850647,
"beginner": 0.35681456327438354,
"expert": 0.1626354455947876
}
|
30,511
|
How to add user defined data type for postgres in typeorm entity?
|
d697fd6c3de2274a56cee4e6540812c1
|
{
"intermediate": 0.528874397277832,
"beginner": 0.23936419188976288,
"expert": 0.2317614108324051
}
|
30,512
|
这是我的代码,可以让lstm用gpu运行吗,如果不行,如何调用全部的cpu
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import datetime
from datetime import timedelta
# Define the tickers
tickers = ['AAPL', 'TSLA', 'NVDA']
# Define start and end date for fetching data
start_date = datetime.datetime.now() - timedelta(days=10*365)
end_date = datetime.datetime.now()
# Function to create a dataset suitable for LSTM
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
v = X.iloc[i:(i + time_steps)].values
Xs.append(v)
ys.append(y.iloc[i + time_steps])
return np.array(Xs), np.array(ys)
# LSTM model definition
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(loss='mean_squared_error', optimizer='adam')
return model
# Dictionary to store models for each ticker
lstm_models = {}
scalers = {}
for ticker in tickers:
# Fetch the data
data = yf.download(ticker, start=start_date, end=end_date)
# Fill any NaNs
data = data.dropna()
# Preprocess the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data[['Open', 'High', 'Low', 'Close', 'Volume']].values)
# Store the fitted scaler in the dictionary
scalers[ticker] = scaler
# Create the dataset
time_steps = 50 # Number of time steps you want to look back
X, y = create_dataset(pd.DataFrame(scaled_data), pd.DataFrame(scaled_data[:,3]), time_steps)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)
# Reshape the data to fit the model input
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 5))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 5))
# Define the LSTM model
model = create_lstm_model((X_train.shape[1], 5))
# Train the model
model.fit(X_train, y_train, epochs=100, batch_size=64, verbose=1)
# Save model in the dictionary
lstm_models[ticker] = model
# Making predictions
predictions = model.predict(X_test)
# Inverse transform to get actual values
predictions = scaler.inverse_transform(np.concatenate((X_test[:, -1, :3], predictions, X_test[:, -1, 4:]), axis=1))[:, 3]
actual_prices = scaler.inverse_transform(np.concatenate((y_test, y_test, y_test, y_test, y_test), axis=1))[:, 0]
# Calculate MSE
mse = np.mean(np.square(predictions - actual_prices))
print(f'{ticker} MSE: {mse}')
|
69189f0169bbfce0a3797f26b02a69af
|
{
"intermediate": 0.42560842633247375,
"beginner": 0.319890558719635,
"expert": 0.2545010447502136
}
|
30,513
|
Отрефактори и оптимизируй этот код (и напиши полностью отрефактореный и оптимизированный вариант код, ВАЖНО, ЧТОБЫ ТЫ ПОЛНОСТЬЮ НАПИСАЛ ОБНОВЛЁННЫЙ КОД):
<Window x:Class="EmailSoftWare.AuthWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:EmailSoftWare"
mc:Ignorable="d"
Height="459" Width="744"
WindowStyle="None" ResizeMode="NoResize"
Background="Transparent" AllowsTransparency="True"
Title="AuthWindow"
Loaded="AuthWindow_Loaded">
<!--Костыль, чтобы рамка не заходила за края дисплея-->
<Grid x:Name="Compensator" Margin="10">
<Grid.BitmapEffect>
<DropShadowBitmapEffect ShadowDepth="1.5" Softness="500" Opacity="0.5"/>
</Grid.BitmapEffect>
<Border BorderThickness="1"
CornerRadius="5"
Background="{DynamicResource Gradient.Window.Background}"
BorderBrush="{DynamicResource Gradient.Window.BorderBrush.Colored}"
ClipToBounds="True">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Background="{DynamicResource Logo.FullImage}"
BorderBrush="{DynamicResource Gradient.Panel.BorderBrush.Colorless}"
CornerRadius="4.5,0,0,4.5"
BorderThickness="0,0,1,0"
MouseLeftButtonDown="TitleBar_OnMouseLeftButtonDown">
<Grid Margin="10">
<TextBlock Style="{DynamicResource TextBlock.Big}"
Text="{DynamicResource Application.TextBlock.Name}"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
Margin="0,0,0,90"/>
<TextBlock Style="{DynamicResource TextBlock.Small}"
Text="{DynamicResource Application.TextBlock.Version}"
HorizontalAlignment="Left"
VerticalAlignment="Bottom">
<TextBlock.Foreground>
<SolidColorBrush Color="{DynamicResource Text.Basic}"/>
</TextBlock.Foreground>
</TextBlock>
<TextBlock Style="{DynamicResource TextBlock.Small}"
Text="{DynamicResource Application.TextBlock.Developer}"
HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock.Foreground>
<SolidColorBrush Color="{DynamicResource Text.Basic}"/>
</TextBlock.Foreground>
</TextBlock>
</Grid>
</Border>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Background="{DynamicResource Gradient.Panel.Background}"
CornerRadius="0,4.5,0,0"
BorderThickness="0"
MouseLeftButtonDown="TitleBar_OnMouseLeftButtonDown">
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Margin="0,0,1.5,0">
<ComboBox Margin="0,0,178,0" Height="26"
x:Name="ComboBox_Languages"
SelectionChanged="ComboBox_Language_OnSelectionChanged">
<ComboBoxItem Content="English"/>
<ComboBoxItem Content="Русский"/>
</ComboBox>
<Button Style="{DynamicResource IconButton.Window.Minimize}" Cursor="Hand"
Click="Button_MinimizeWindow_OnClick"/>
<Button Style="{DynamicResource IconButton.Window.Close}"
Click="Button_CloseApplication_OnClick"/>
</StackPanel>
</Border>
<Grid Grid.Row="1" Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Style="{DynamicResource TextBlock.Big}"
Text="{DynamicResource AuthWindow.TextBlock.Title.Authorization}"
HorizontalAlignment="Center"
Margin="0,30,0,0"/>
<Grid Grid.Row="1">
<TextBox x:Name="TextBox_Authorization_UserName"
ToolTip="{DynamicResource AuthWindow.ToolTip.TextBox.Username}"
GotFocus="TextBox_Watermark_OnGotFocus"
LostFocus="TextBox_Watermark_OnLostFocus"
Loaded="TextBox_Watermark_Loaded"/>
<TextBlock x:Name="Watermark_Authorization_UserName"
Text="{DynamicResource AuthWindow.TextBlock.Watermark.UserName}"
Style="{StaticResource Watermark}"
HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="2">
<TextBox x:Name="TextBox_Authorization_Hwid"
ToolTip="{DynamicResource AuthWindow.ToolTip.TextBox.Hwid}"
IsReadOnly="True"
MouseDoubleClick="TextBox_Authorization_HWID_OnMouseDoubleClick"
Loaded="TextBox_Watermark_Loaded"/>
<TextBlock x:Name="Watermark_Authorization_Hwid"
Text="{DynamicResource AuthWindow.TextBlock.Watermark.HWID}"
Style="{StaticResource Watermark}"
HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="3">
<TextBox x:Name="TextBox_Authorization_PersonalKey"
ToolTip="{DynamicResource AuthWindow.ToolTip.TextBox.PersonalKey}"
GotFocus="TextBox_Watermark_OnGotFocus"
LostFocus="TextBox_Watermark_OnLostFocus"
Loaded="TextBox_Watermark_Loaded"/>
<TextBlock x:Name="Watermark_Authorization_PersonalKey"
Text="{DynamicResource AuthWindow.TextBlock.Watermark.PersonalKey}"
Style="{StaticResource Watermark}"
HorizontalAlignment="Center"/>
</Grid>
<Button Grid.Row="4"
Style="{DynamicResource IconTextButton.Auth.LogIn}"
Click="Button_LogIn_OnClick"/>
</Grid>
</Grid>
</Grid>
</Border>
</Grid>
</Window>
|
e2bdde78203f3b4276236882e05cc8ba
|
{
"intermediate": 0.32634279131889343,
"beginner": 0.5460820198059082,
"expert": 0.12757524847984314
}
|
30,514
|
Отрефактори и оптимизируй код C# код:
using HelperSharp;
using EmailSoftWare.Models.Connections;
using static EmailSoftWare.Models.Connections.SQLite;
using static EmailSoftWare.Models.Connections.ServerResponseParser;
using EmailSoftWare.Models.Extensions.Enums;
using EmailSoftWare.Views.Windows;
using Microsoft.Data.Sqlite;
using System;
namespace EmailSoftWare.Models.UserData
{
public class Account
{
public string Type { get; set; }
public string FullData { get; private set; }
public string Email { get; private set; }
public string Password { get; private set; }
public string Domain { get; private set; }
public int Errors { get; set; }
public Result Result { get; set; }
public string Server { get; set; }
public int Port { get; set; }
public Account(string fullData)
{
var dataParts = fullData.Split(":");
FullData = fullData;
Email = dataParts[0];
Password = dataParts[1];
Errors = 0;
Result = Result.ToCheck;
}
public bool SetServer()
{
string domain = Email.Split("@")[1];
Domain = domain;
try
{
string md5 = MD5Helper.Encrypt(domain + "985B5C1D89379FBD141A86AE97169D63").ToUpper();
if (RetrieveServerSettings(md5, "IMAP") || RetrieveServerSettings(md5, "POP3"))
{
return true;
}
ViewManager.MainWindow.DomainsForSearchSettings.Add(domain);
return false;
}
catch
{
ViewManager.MainWindow.DomainsForSearchSettings.Add(domain);
return false;
}
}
private bool RetrieveServerSettings(string md5, string serverType)
{
SqliteCommand sqLiteCommand = new SqliteCommand($"SELECT Server, Port, Socket FROM '{md5[0]}' WHERE Domain = '{md5}'",
serverType == "IMAP" ? sqLiteConnectionImap : sqLiteConnectionPop3);
using (SqliteDataReader sqLiteDataReader = sqLiteCommand.ExecuteReader())
{
if (!sqLiteDataReader.Read()) return false;
Type = serverType;
Server = sqLiteDataReader.GetString(0);
Port = sqLiteDataReader.GetInt32(1);
return true;
}
}
}
}
|
27c32bb54eb6607d48123a7f136e265f
|
{
"intermediate": 0.3384098708629608,
"beginner": 0.4076915681362152,
"expert": 0.25389862060546875
}
|
30,515
|
Отрефактори и оптимизируй код C# код:
using HelperSharp;
using EmailSoftWare.Models.Connections;
using static EmailSoftWare.Models.Connections.SQLite;
using static EmailSoftWare.Models.Connections.ServerResponseParser;
using EmailSoftWare.Models.Extensions.Enums;
using EmailSoftWare.Views.Windows;
using Microsoft.Data.Sqlite;
using System;
namespace EmailSoftWare.Models.UserData
{
public class Account
{
public string Type { get; set; }
public string FullData { get; private set; }
public string Email { get; private set; }
public string Password { get; private set; }
public string Domain { get; private set; }
public int Errors { get; set; }
public Result Result { get; set; }
public string Server { get; set; }
public int Port { get; set; }
public Account(string fullData)
{
var dataParts = fullData.Split(":");
FullData = fullData;
Email = dataParts[0];
Password = dataParts[1];
Errors = 0;
Result = Result.ToCheck;
}
public bool SetServer()
{
string domain = Email.Split("@")[1];
Domain = domain;
try
{
string md5 = MD5Helper.Encrypt(domain + "985B5C1D89379FBD141A86AE97169D63").ToUpper();
if (RetrieveServerSettings(md5, "IMAP") || RetrieveServerSettings(md5, "POP3"))
{
return true;
}
ViewManager.MainWindow.DomainsForSearchSettings.Add(domain);
return false;
}
catch
{
ViewManager.MainWindow.DomainsForSearchSettings.Add(domain);
return false;
}
}
private bool RetrieveServerSettings(string md5, string serverType)
{
SqliteCommand sqLiteCommand = new SqliteCommand($"SELECT Server, Port, Socket FROM '{md5[0]}' WHERE Domain = '{md5}'",
serverType == "IMAP" ? sqLiteConnectionImap : sqLiteConnectionPop3);
using (SqliteDataReader sqLiteDataReader = sqLiteCommand.ExecuteReader())
{
if (!sqLiteDataReader.Read()) return false;
Type = serverType;
Server = sqLiteDataReader.GetString(0);
Port = sqLiteDataReader.GetInt32(1);
return true;
}
}
}
}
|
8780fb4bd6540d7faa4d2da316fb26c5
|
{
"intermediate": 0.3384098708629608,
"beginner": 0.4076915681362152,
"expert": 0.25389862060546875
}
|
30,516
|
Отрефактори и оптимизируй код C# код:
using HelperSharp;
using EmailSoftWare.Models.Connections;
using static EmailSoftWare.Models.Connections.SQLite;
using static EmailSoftWare.Models.Connections.ServerResponseParser;
using EmailSoftWare.Models.Extensions.Enums;
using EmailSoftWare.Views.Windows;
using Microsoft.Data.Sqlite;
using System;
namespace EmailSoftWare.Models.UserData
{
public class Account
{
public string Type { get; set; }
public string FullData { get; private set; }
public string Email { get; private set; }
public string Password { get; private set; }
public string Domain { get; private set; }
public int Errors { get; set; }
public Result Result { get; set; }
public string Server { get; set; }
public int Port { get; set; }
public Account(string fullData)
{
var dataParts = fullData.Split(":");
FullData = fullData;
Email = dataParts[0];
Password = dataParts[1];
Errors = 0;
Result = Result.ToCheck;
}
public bool SetServer()
{
string domain = Email.Split("@")[1];
Domain = domain;
try
{
string md5 = MD5Helper.Encrypt(domain + "985B5C1D89379FBD141A86AE97169D63").ToUpper();
if (RetrieveServerSettings(md5, "IMAP") || RetrieveServerSettings(md5, "POP3"))
{
return true;
}
ViewManager.MainWindow.DomainsForSearchSettings.Add(domain);
return false;
}
catch
{
ViewManager.MainWindow.DomainsForSearchSettings.Add(domain);
return false;
}
}
private bool RetrieveServerSettings(string md5, string serverType)
{
SqliteCommand sqLiteCommand = new SqliteCommand($"SELECT Server, Port, Socket FROM '{md5[0]}' WHERE Domain = '{md5}'",
serverType == "IMAP" ? sqLiteConnectionImap : sqLiteConnectionPop3);
using (SqliteDataReader sqLiteDataReader = sqLiteCommand.ExecuteReader())
{
if (!sqLiteDataReader.Read()) return false;
Type = serverType;
Server = sqLiteDataReader.GetString(0);
Port = sqLiteDataReader.GetInt32(1);
return true;
}
}
}
}
|
5f85f0315fe95200adb761fb896d927a
|
{
"intermediate": 0.3384098708629608,
"beginner": 0.4076915681362152,
"expert": 0.25389862060546875
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.