row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
46,184
|
Fix
// Importing necessary modules
console.log('Importing necessary modules');
const { chromium } = require('playwright-extra');
const stealth = require('puppeteer-extra-plugin-stealth')();
// Adding stealth plugin to the chromium browser
console.log('Adding stealth plugin to the chromium browser');
chromium.use(stealth);
(async () => {
const browser = await chromium.launchPersistentContext('browser_data', { headless: false });
// Create a new page
console.log('Create a new page');
const page = await browser.newPage();
// Navigate to test page
console.log('Navigate to test page');
await page.goto('http://127.0.0.1:3000/');
async function getGameData(page, gameSelector) {
// Get game eleement
console.log('Get game eleement');
const game = await page.locator(gameSelector);
// Get circles of game
console.log('Get circles of game');
const circles = await game.locator('[data-type="coordinates"]').all();
// Initalize variables
console.log('Initalize variables');
let lastColumn = 0;
let streakStart = 0;
let streakLength = 0;
// Loop through circles
console.log('Loop through circles');
for (let index = 0; index < circles.count(); index++) {
// Circle element in each iteration
console.log('Circle element in each iteration');
const circle = circles[index];
// Extract data from circle element
console.log('Extract data from circle element');
let column = parseInt(await circle.getAttribute('data-x'), 10);
let row = parseInt(await circle.getAttribute('data-y'), 10);
// Calculate last column and index of start of streak
console.log('Calculate last column and index of start of streak');
if (column > lastColumn && row === 0) {
lastColumn = column;
streakStart = index;
}
}
// Slice circles array at streak start then count streak length
console.log('Slice circles array at streak start then count streak length');
circles.slice(streakStart).forEach(() => {
streakLength += 1;
});
// Return game data
console.log('Return game data');
return { lastColumn, streakLength };
}
// Dynamic selector for game container
console.log('Dynamic selector for game container ');
const gameSelector = '[class*="bigRoadContainer--"]';
const game = await page.locator(gameSelector).first();
console.log(game);
// Loop forever
console.log('Loop forever');
while (true) {
console.log('Delay between loops');
await page.waitForTimeout(1000);
// If game is present
console.log('If game is present');
page.addLocatorHandler(page.locator(gameSelector),
// Then run this function
async() => {
// Get all games
console.log('Get all games');
let games = await page.locator(gameSelector).all();
// Loop through each game
console.log('Loop through each game');
for (let index = 0; index < games.length; index++) {
// Get game in each iteration
console.log('Get game in each iteration');
let game = await games.nth(index);
// Get game data
console.log('Get game data');
let data = await getGameData(page, game);
// Log data of game
console.log('Log data of game');
console.log(`Container ${index + 1} Last Column: ${data.lastColumn} Streak Length: ${data.streakLength}`);
}
}
);
// Delay between loops
}
// Close browser when done
console.log('Close browser when done');
await browser.close();
})();
|
2ff0004a07e740bb66a899cd2f088215
|
{
"intermediate": 0.40100857615470886,
"beginner": 0.425624817609787,
"expert": 0.17336659133434296
}
|
46,185
|
On this line 'PerformCopyAndClear Columns("E2:E20"), Columns("F2:F20"), Columns("AE2:AE20")' in the VBA code below, I am getting an error - application defined or object defined.
Sub DueDates()
Me.Unprotect Password:="edit" ' Unlock the sheet
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim currentMonth As Long
currentMonth = Month(Date)
If currentMonth >= 9 And currentMonth <= 12 Then ' Sep to Dec
Range("AE1").Value = "Sep - Dec"
If Range("I1").Value > 0 Then
PerformCopyAndClear Columns("E2:E20"), Columns("F2:F20")
End If
If Range("J1").Value > 0 Then
PerformCopyAndClear Columns("G2:G20"), Columns("B2:B20"), Columns("AE2:AE20")
End If
ElseIf currentMonth >= 1 And currentMonth <= 3 Then ' Jan to Mar
Range("AE1").Value = "Jan - Mar"
If Range("J1").Value > 0 Then
PerformCopyAndClear Columns("G2:G20"), Columns("B2:B20")
End If
If Range("H1").Value > 0 Then
PerformCopyAndClear Columns("C2:C20"), Columns("D2:D20"), Columns("AE2:AE20")
End If
ElseIf currentMonth >= 4 And currentMonth <= 8 Then ' Apr to Aug
Range("AE1").Value = "Apr - Aug"
If Range("H1").Value > 0 Then
PerformCopyAndClear Columns("C2:C20"), Columns("D2:D20")
End If
If Range("I1").Value > 0 Then
PerformCopyAndClear Columns("E2:E20"), Columns("F2:F20"), Columns("AE2:AE20")
End If
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
Me.Protect Password:="edit"
End Sub
Private Sub PerformCopyAndClear(sourceRange As Range, ParamArray destinationRanges() As Variant)
Me.Unprotect Password:="edit"
Application.EnableEvents = False
sourceRange.Copy
Dim destinationRange As Variant
For Each destinationRange In destinationRanges
destinationRange.PasteSpecial xlPasteValues
Next destinationRange
sourceRange.ClearContents
Application.CutCopyMode = False
Application.EnableEvents = True
Me.Protect Password:="edit"
End Sub
|
ed6b450a08a39734e90456f70149c9fb
|
{
"intermediate": 0.3257125914096832,
"beginner": 0.32917577028274536,
"expert": 0.345111608505249
}
|
46,186
|
hello
|
7572d3cc95471b7f987edb6be01de0ad
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
46,187
|
what is arc coverage in gtest and how to implement it
|
48cd40171492049b1d90973b6fb5e19f
|
{
"intermediate": 0.31381139159202576,
"beginner": 0.25058645009994507,
"expert": 0.4356021285057068
}
|
46,188
|
import java.io.*;
import java.util.Scanner;
import java.util.LinkedList;
public class floyd {
private static int[][] adjMatrix;
private static int[][] pMatrix;
private static final String OUTPUT_FILE = "output.txt";
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java Floyd <graph-file>");
return;
}
try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) {
createFile();
int problemCount = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("Problem")) {
problemCount++;
int n = extractNumberOfVertices(line);
if (n < 5 || n > 10) {
throw new IllegalArgumentException("Invalid number of vertices.");
}
// Read adjacency matrix for the current problem
initializeMatrices(n, scanner);
// Compute shortest paths and print results
calculateShortestPaths();
printResult(problemCount, n);
}
}
}
}
private static void createFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter(OUTPUT_FILE);
writer.close();
}
private static int extractNumberOfVertices(String line) {
// Extracts the number of vertices from the line
String[] parts = line.split("n = ");
return Integer.parseInt(parts[1].trim());
}
private static void initializeMatrices(int n, Scanner scanner) {
adjMatrix = new int[n][n];
pMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
String[] values = scanner.nextLine().trim().split("\\s+");
for (int j = 0; j < n; j++) {
int weight;
if (values[j].equals("INF")) {
weight = Integer.MAX_VALUE;
} else {
weight = Integer.parseInt(values[j]);
}
adjMatrix[i][j] = weight;
pMatrix[i][j] = i; // Initialize predecessor matrix
if (i == j) {
adjMatrix[i][j] = 0; // Distance from a node to itself is 0
}
}
}
}
private static void calculateShortestPaths() {
int n = adjMatrix.length;
// Initialize pMatrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (adjMatrix[i][j] == Integer.MAX_VALUE || i == j) {
pMatrix[i][j] = -1; // No path or self-loop
} else {
pMatrix[i][j] = i; // Predecessor initially set to source node
}
}
}
// Calculate shortest paths and update pMatrix
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (adjMatrix[i][k] != Integer.MAX_VALUE && adjMatrix[k][j] != Integer.MAX_VALUE) {
int newDistance = adjMatrix[i][k] + adjMatrix[k][j];
if (newDistance < adjMatrix[i][j]) {
adjMatrix[i][j] = newDistance;
// Update pMatrix to store the predecessor node in the path
pMatrix[i][j] = pMatrix[k][j];
}
}
}
}
}
}
private static void printResult(int problemCount, int n) throws FileNotFoundException {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) {
out.println("Problem" + problemCount + ": n = " + n);
out.println("Pmatrix:");
// Output the Pmatrix for the problem
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(String.format("%2d ", pMatrix[i][j]));
}
out.println();
}
out.println();
// Output shortest paths for each city to all other cities
for (int source = 0; source < n; source++) {
out.println("V" + (source + 1) + "-Vj: shortest path and length");
for (int dest = 0; dest < n; dest++) {
// Get the shortest path and distance between the source and destination
String path = getShortestPath(source, dest);
int distance = adjMatrix[source][dest];
out.println(path + ": " + distance);
}
out.println();
}
out.println(); // Separate problems visually
} catch (IOException ex) {
System.err.println("An error occurred while writing to the file: " + ex.getMessage());
}
}
private static String getShortestPath(int source, int dest) {
if (adjMatrix[source][dest] == Integer.MAX_VALUE) {
return "No path";
}
// Use a list to construct the path in reverse
LinkedList<String> pathList = new LinkedList<>();
int currentNode = dest;
while (currentNode != source) {
pathList.addFirst("V" + (currentNode + 1));
currentNode = pMatrix[source][currentNode];
}
// Add the source node at the beginning
pathList.addFirst("V" + (source + 1));
// Join the path list with spaces
return String.join(" ", pathList);
}
private static void appendToFile(String output) throws FileNotFoundException {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) {
out.print(output);
} catch (IOException ex) {
System.err.println("An error occurred while writing to the file: " + ex.getMessage());
}
}
}
The program is giving Pmatrix in the output as Problem1: n = 7
Pmatrix:
-1 0 0 0 0 0 0
1 -1 1 1 1 1 1
2 2 -1 2 2 2 2
3 3 3 -1 3 3 3
4 4 4 4 -1 4 4
5 5 5 5 5 -1 5
6 6 6 6 6 6 -1 but the correct and expected Pmatrix that the program should give is Problem1: n = 7
Pmatrix:
0 0 0 6 3 0 6
0 0 5 0 0 4 0
0 5 0 0 0 0 5
6 0 0 0 3 0 6
3 0 0 3 0 3 0
0 4 0 0 3 0 0
6 0 5 6 0 0 0 Understand the logic for the Pmatrix for the expected output and make necessary changes to the code
|
0b48f2b5f7a677298b58e7cca1500639
|
{
"intermediate": 0.35980793833732605,
"beginner": 0.4979517459869385,
"expert": 0.14224033057689667
}
|
46,189
|
when use itterput in arduino what happend when receive two message sencond message before job of interput function handel done?
|
1acc095125853d76ddfc093d41d4d9bb
|
{
"intermediate": 0.5315592885017395,
"beginner": 0.15066660940647125,
"expert": 0.31777411699295044
}
|
46,190
|
tell me about this code. LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF);
|
449b6edfb817abfb4e446dfbecc90509
|
{
"intermediate": 0.30617547035217285,
"beginner": 0.46039482951164246,
"expert": 0.2334297001361847
}
|
46,191
|
How can I undo the changes made by this SQL?
ALTER TABLE job ADD COLUMN create_ts TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN created_by UUID REFERENCES organisation_link(id);
UPDATE job
SET create_ts = update_ts,
created_by = updated_by;
ALTER TABLE job ALTER COLUMN created_by SET NOT NULL;
|
0560776f172bb20bd3bd4a5217970483
|
{
"intermediate": 0.5325359106063843,
"beginner": 0.23410527408123016,
"expert": 0.2333587259054184
}
|
46,192
|
We'll be making sql queries
|
06ad83022110523362fc1e58ca61944e
|
{
"intermediate": 0.2695522606372833,
"beginner": 0.39508146047592163,
"expert": 0.3353663384914398
}
|
46,193
|
WARNING: No NVIDIA/AMD GPU detected. Ollama will run in CPU-only mode in wsl. but i would like to use my amd gpus
|
635a71884db83de7d053784a703503e8
|
{
"intermediate": 0.335790753364563,
"beginner": 0.3017210364341736,
"expert": 0.36248812079429626
}
|
46,194
|
I am trying to write ACL on glide list type field but it is not working as expected.
Can someone please help me
answer = gs.getUser().isMemberOf(current.field_name);
|
81f00d2a92c368607dd5313a8e07dd9e
|
{
"intermediate": 0.4034806191921234,
"beginner": 0.22117608785629272,
"expert": 0.3753432631492615
}
|
46,195
|
BackgroundService asp net core 6
|
23d74786a5b3644b45953eced07e5e8e
|
{
"intermediate": 0.35088804364204407,
"beginner": 0.24002216756343842,
"expert": 0.4090897738933563
}
|
46,196
|
Hi All,
with the help of HTML, Server Script and Client Controller (below script) I can add the field type of "html". In the same way I want to add the field types as "String", "Date/Time", "Choice", "Boolean" in to Idea Portal.
Please see the below script, you cam see the type field as "html", in the same way please suggest for different field types.
|
c46d1259775dd1e6685678fdd3c29175
|
{
"intermediate": 0.45289865136146545,
"beginner": 0.2396075427532196,
"expert": 0.3074938654899597
}
|
46,197
|
when i use srtcat in c++ do i need to worry if there is space in destination string
|
7d12607a3ebba34d0bc8382323ad60f5
|
{
"intermediate": 0.5326973795890808,
"beginner": 0.1772872358560562,
"expert": 0.2900153696537018
}
|
46,198
|
Where is the error with this sql query
SELECT * , AS Count_1a_psg
FROM pass_in_trip
WHERE PLACE LIKE '1a%';
|
a015ab13ebda581eb2ec7a0c266b3b57
|
{
"intermediate": 0.3246563673019409,
"beginner": 0.44015270471572876,
"expert": 0.23519088327884674
}
|
46,199
|
What is linear algebra
|
39b9636c11c6ab2d70c259ecf9d2e00f
|
{
"intermediate": 0.3886714279651642,
"beginner": 0.4339570105075836,
"expert": 0.1773715317249298
}
|
46,200
|
I am trying to create tiling-interface for my custom mlir operation using the existing TilingInterface provided by MLIR
Implement the tiling-interface for mini.matmul and mini.add.
Can you give me the code and exact steps to follow to make changes to the ODS Framework in MLIR and please give me the code in cpp
|
79d718b4a63b55e3f87ac7f95e06b499
|
{
"intermediate": 0.8188042044639587,
"beginner": 0.09777865558862686,
"expert": 0.08341711014509201
}
|
46,201
|
This is my code :
SELECT NAME
From Passenger
WHERE NAME LIKE '% %-%' OR '% % %';
This is the error im getting:
Error starting at line : 1 in command -
SELECT NAME
From Passenger
WHERE NAME LIKE '% %-%' OR '% % %'
Error at Command Line : 3 Column : 34
Error report -
SQL Error: ORA-00920: invalid relational operator
00920. 00000 - "invalid relational operator"
*Cause:
*Action:
|
f7260f751ef39feb503a0cbc79d62992
|
{
"intermediate": 0.39824578166007996,
"beginner": 0.24240264296531677,
"expert": 0.35935157537460327
}
|
46,202
|
Hi there, please be a senior sapui5 developer and answer my following questions with working code examples.
|
ff5fe6c52d19e27ff050aebe899d6744
|
{
"intermediate": 0.42116406559944153,
"beginner": 0.2712341248989105,
"expert": 0.3076017498970032
}
|
46,203
|
We will be building querries in SQL devoper using the following database:
CREATE TABLE Company (
ID_comp int NOT NULL ,
name char (10) NOT NULL
);
CREATE TABLE Pass_in_trip (
trip_no int NOT NULL ,
date datetime NOT NULL ,
ID_psg int NOT NULL ,
place char (10) NOT NULL
);
CREATE TABLE Passenger (
ID_psg int NOT NULL ,
name char (20) NOT NULL
);
CREATE TABLE Trip (
trip_no int NOT NULL ,
ID_comp int NOT NULL ,
plane char (10) NOT NULL ,
town_from char (25) NOT NULL ,
town_to char (25) NOT NULL ,
time_out datetime NOT NULL ,
time_in datetime NOT NULL
);
ALTER TABLE Company ADD
CONSTRAINT PK2 PRIMARY KEY
(
ID_comp
);
ALTER TABLE Pass_in_trip ADD
CONSTRAINT PK_pt PRIMARY KEY CLUSTERED
(
trip_no,
date,
ID_psg
);
ALTER TABLE Passenger ADD
CONSTRAINT PK_psg PRIMARY KEY CLUSTERED
(
ID_psg
);
ALTER TABLE Trip ADD
CONSTRAINT PK_t PRIMARY KEY CLUSTERED
(
trip_no
);
ALTER TABLE Pass_in_trip ADD
CONSTRAINT FK_Pass_in_trip_Passenger FOREIGN KEY
(
ID_psg
) REFERENCES Passenger (
ID_psg
);
ALTER TABLE Pass_in_trip ADD
CONSTRAINT FK_Pass_in_trip_Trip FOREIGN KEY
(
trip_no
) REFERENCES Trip (
trip_no
);
ALTER TABLE Trip ADD
CONSTRAINT FK_Trip_Company FOREIGN KEY
(
ID_comp
) REFERENCES Company (
ID_comp
);
/*----Company------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */
insert into Company values(1,'Don_avia ');
insert into Company values(2,'Aeroflot ');
insert into Company values(3,'Dale_avia ');
insert into Company values(4,'air_France');
insert into Company values(5,'British_AW');
/*----Passenger------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */
insert into Passenger values(1,'Bruce Willis ');
insert into Passenger values(2,'George Clooney ');
insert into Passenger values(3,'Kevin Costner ');
insert into Passenger values(4,'Donald Sutherland ');
insert into Passenger values(5,'Jennifer Lopez ');
insert into Passenger values(6,'Ray Liotta ');
insert into Passenger values(7,'Samuel L. Jackson ');
insert into Passenger values(8,'Nikole Kidman ');
insert into Passenger values(9,'Alan Rickman ');
insert into Passenger values(10,'Kurt Russell ');
insert into Passenger values(11,'Harrison Ford ');
insert into Passenger values(12,'Russell Crowe ');
insert into Passenger values(13,'Steve Martin ');
insert into Passenger values(14,'Michael Caine ');
insert into Passenger values(15,'Angelina Jolie ');
insert into Passenger values(16,'Mel Gibson ');
insert into Passenger values(17,'Michael Douglas ');
insert into Passenger values(18,'John Travolta ');
insert into Passenger values(19,'Sylvester Stallone ');
insert into Passenger values(20,'Tommy Lee Jones ');
insert into Passenger values(21,'Catherine Zeta-Jones');
insert into Passenger values(22,'Antonio Banderas ');
insert into Passenger values(23,'Kim Basinger ');
insert into Passenger values(24,'Sam Neill ');
insert into Passenger values(25,'Gary Oldman ');
insert into Passenger values(26,'Clint Eastwood ');
insert into Passenger values(27,'Brad Pitt ');
insert into Passenger values(28,'Johnny Depp ');
insert into Passenger values(29,'Pierce Brosnan ');
insert into Passenger values(30,'Sean Connery ');
insert into Passenger values(31,'Bruce Willis ');
insert into Passenger values(37,'Mullah Omar ');
/*----Trip------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */
insert into Trip values(1100,4,'Boeing ','Rostov ','Paris ','1900-01-01 14:30:00','1900-01-01 17:50:00');
insert into Trip values(1101,4,'Boeing ','Paris ','Rostov ','1900-01-01 08:12:00','1900-01-01 11:45:00');
insert into Trip values(1123,3,'TU-154 ','Rostov ','Vladivostok ','1900-01-01 16:20:00','1900-01-01 03:40:00');
insert into Trip values(1124,3,'TU-154 ','Vladivostok ','Rostov ','1900-01-01 09:00:00','1900-01-01 19:50:00');
insert into Trip values(1145,2,'IL-86 ','Moscow ','Rostov ','1900-01-01 09:35:00','1900-01-01 11:23:00');
insert into Trip values(1146,2,'IL-86 ','Rostov ','Moscow ','1900-01-01 17:55:00','1900-01-01 20:01:00');
insert into Trip values(1181,1,'TU-134 ','Rostov ','Moscow ','1900-01-01 06:12:00','1900-01-01 08:01:00');
insert into Trip values(1182,1,'TU-134 ','Moscow ','Rostov ','1900-01-01 12:35:00','1900-01-01 14:30:00');
insert into Trip values(1187,1,'TU-134 ','Rostov ','Moscow ','1900-01-01 15:42:00','1900-01-01 17:39:00');
insert into Trip values(1188,1,'TU-134 ','Moscow ','Rostov ','1900-01-01 22:50:00','1900-01-01 00:48:00');
insert into Trip values(1195,1,'TU-154 ','Rostov ','Moscow ','1900-01-01 23:30:00','1900-01-01 01:11:00');
insert into Trip values(1196,1,'TU-154 ','Moscow ','Rostov ','1900-01-01 04:00:00','1900-01-01 05:45:00');
insert into Trip values(7771,5,'Boeing ','London ','Singapore ','1900-01-01 01:00:00','1900-01-01 11:00:00');
insert into Trip values(7772,5,'Boeing ','Singapore ','London ','1900-01-01 12:00:00','1900-01-01 02:00:00');
insert into Trip values(7773,5,'Boeing ','London ','Singapore ','1900-01-01 03:00:00','1900-01-01 13:00:00');
insert into Trip values(7774,5,'Boeing ','Singapore ','London ','1900-01-01 14:00:00','1900-01-01 06:00:00');
insert into Trip values(7775,5,'Boeing ','London ','Singapore ','1900-01-01 09:00:00','1900-01-01 20:00:00');
insert into Trip values(7776,5,'Boeing ','Singapore ','London ','1900-01-01 18:00:00','1900-01-01 08:00:00');
insert into Trip values(7777,5,'Boeing ','London ','Singapore ','1900-01-01 18:00:00','1900-01-01 06:00:00');
insert into Trip values(7778,5,'Boeing ','Singapore ','London ','1900-01-01 22:00:00','1900-01-01 12:00:00');
insert into Trip values(8881,5,'Boeing ','London ','Paris ','1900-01-01 03:00:00','1900-01-01 04:00:00');
insert into Trip values(8882,5,'Boeing ','Paris ','London ','1900-01-01 22:00:00','1900-01-01 23:00:00');
/*----Pass_in_trip------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */
insert into Pass_in_trip values(1100,'2003-04-29 00:00:00',1,'1a ');
insert into Pass_in_trip values(1123,'2003-04-05 00:00:00',3,'2a ');
insert into Pass_in_trip values(1123,'2003-04-08 00:00:00',1,'4c ');
insert into Pass_in_trip values(1123,'2003-04-08 00:00:00',6,'4b ');
insert into Pass_in_trip values(1124,'2003-04-02 00:00:00',2,'2d ');
insert into Pass_in_trip values(1145,'2003-04-05 00:00:00',3,'2c ');
insert into Pass_in_trip values(1181,'2003-04-01 00:00:00',1,'1a ');
insert into Pass_in_trip values(1181,'2003-04-01 00:00:00',6,'1b ');
insert into Pass_in_trip values(1181,'2003-04-01 00:00:00',8,'3c ');
insert into Pass_in_trip values(1181,'2003-04-13 00:00:00',5,'1b ');
insert into Pass_in_trip values(1182,'2003-04-13 00:00:00',5,'4b ');
insert into Pass_in_trip values(1187,'2003-04-14 00:00:00',8,'3a ');
insert into Pass_in_trip values(1188,'2003-04-01 00:00:00',8,'3a ');
insert into Pass_in_trip values(1182,'2003-04-13 00:00:00',9,'6d ');
insert into Pass_in_trip values(1145,'2003-04-25 00:00:00',5,'1d ');
insert into Pass_in_trip values(1187,'2003-04-14 00:00:00',10,'3d ');
insert into Pass_in_trip values(8882,'2005-11-06 00:00:00',37,'1a ');
insert into Pass_in_trip values(7771,'2005-11-07 00:00:00',37,'1c ');
insert into Pass_in_trip values(7772,'2005-11-07 00:00:00',37,'1a ');
insert into Pass_in_trip values(8881,'2005-11-08 00:00:00',37,'1d ');
insert into Pass_in_trip values(7778,'2005-11-05 00:00:00',10,'2a ');
insert into Pass_in_trip values(7772,'2005-11-29 00:00:00',10,'3a ');
insert into Pass_in_trip values(7771,'2005-11-04 00:00:00',11,'4a ');
insert into Pass_in_trip values(7771,'2005-11-07 00:00:00',11,'1b ');
insert into Pass_in_trip values(7771,'2005-11-09 00:00:00',11,'5a ');
insert into Pass_in_trip values(7772,'2005-11-07 00:00:00',12,'1d ');
insert into Pass_in_trip values(7773,'2005-11-07 00:00:00',13,'2d ');
insert into Pass_in_trip values(7772,'2005-11-29 00:00:00',13,'1b ');
insert into Pass_in_trip values(8882,'2005-11-13 00:00:00',14,'3d ');
insert into Pass_in_trip values(7771,'2005-11-14 00:00:00',14,'4d ');
insert into Pass_in_trip values(7771,'2005-11-16 00:00:00',14,'5d ');
insert into Pass_in_trip values(7772,'2005-11-29 00:00:00',14,'1c ');
|
de106737c9d89fb7f78e4fcecdcde884
|
{
"intermediate": 0.3629550337791443,
"beginner": 0.3488968312740326,
"expert": 0.28814810514450073
}
|
46,204
|
Trying to implement mini.matmul operation using TIling Interface provided by MLIR
Implement the tiling-interface for mini.matmul and mini.add. Make sure to read the docs for
interfaces and toy chapter about interfaces for an example.
Can you give me the cpp code and changes that i have to make to the ODS framework
|
1c1faab26419f1271df4602159f49371
|
{
"intermediate": 0.6850162148475647,
"beginner": 0.1538769155740738,
"expert": 0.1611068993806839
}
|
46,205
|
class Str {
public:
/**
* Default constructor should create a string
* equal to ""
*/
Str();
define this function folllow the direction provided
|
6ec585875f94653ee40e3d6f06e30b50
|
{
"intermediate": 0.3310447037220001,
"beginner": 0.4879629909992218,
"expert": 0.18099229037761688
}
|
46,206
|
can you speak chinese
|
c368f3d466ab3e6b0757567e4d6f240b
|
{
"intermediate": 0.34837108850479126,
"beginner": 0.401405394077301,
"expert": 0.2502234876155853
}
|
46,207
|
how to view the arc-coverage report from index.html
|
9c289933df07340f889e907781298625
|
{
"intermediate": 0.30559489130973816,
"beginner": 0.2827005684375763,
"expert": 0.41170454025268555
}
|
46,208
|
I will type messages I want you to remove everything before the # on each row including #
|
f6ea4e5f60e8f2810c199a306f09dc9b
|
{
"intermediate": 0.309334933757782,
"beginner": 0.3695797026157379,
"expert": 0.3210853934288025
}
|
46,209
|
std::istream& operator>>(std::istream& istr, Str& s)
{
std::string stemp;
istr >> stemp;
s = stemp.c_str();
return istr;
}
std::ostream&operator<<(std::ostream& ostr, const Str& s)
|
0c74d7000722cee11d5ab4786432dc4f
|
{
"intermediate": 0.3043535649776459,
"beginner": 0.5253406763076782,
"expert": 0.17030569911003113
}
|
46,210
|
i want javascript which will move div with id top-bar-container right after opening <body> tag
|
28c2f2c0aa32f6dcfefb2947f7ed7bca
|
{
"intermediate": 0.4418620467185974,
"beginner": 0.24369701743125916,
"expert": 0.31444090604782104
}
|
46,211
|
If I have a bunch of dice, of any side and any amount. What's the way of calculating the chances of every number being rolled
|
b20c379cd9681ab0a4239fd85743bafc
|
{
"intermediate": 0.3714427351951599,
"beginner": 0.2671282887458801,
"expert": 0.36142897605895996
}
|
46,212
|
pdftotext IS UNRECOGNIZIBILE
|
7ff69f1039a6d951c18aa86405e6d1e8
|
{
"intermediate": 0.3984079957008362,
"beginner": 0.2486930936574936,
"expert": 0.3528989851474762
}
|
46,213
|
Write me a chrome extension that will filter Airbnbs with speed greater thatn 20 Mbps
|
c85b58e9eae93a6f9a1201178de976b1
|
{
"intermediate": 0.3260314166545868,
"beginner": 0.17699198424816132,
"expert": 0.4969766438007355
}
|
46,214
|
Using python itertools create all possible str with 10 digits then count how much of them contain at least 3 same digit
|
e691120f6ca39862e0a9cdef6f7bf37a
|
{
"intermediate": 0.4440729320049286,
"beginner": 0.16041532158851624,
"expert": 0.3955116868019104
}
|
46,215
|
Using itertools python create all possible 6-digit strings then count how much of them contain al least 3 same digit
|
24cb5aff77fe31f63ef97ec462dcebfa
|
{
"intermediate": 0.4500887095928192,
"beginner": 0.16021612286567688,
"expert": 0.3896951675415039
}
|
46,216
|
У меня в dll есть функция, которая патчит байты по адресу:
uintptr_t engine_base = reinterpret_cast<uintptr_t>(engine_module_handle);
uintptr_t skillgrp_address = engine_base + 0x59A4A2;
BYTE skillgrp_patch[5] = { 0x32, 0x00, 0x32, 0x00, 0x38};
DWORD old_protect;
VirtualProtect(reinterpret_cast<LPVOID>(skillgrp_address), sizeof(skillgrp_patch), PAGE_EXECUTE_READWRITE, &old_protect);
if (!WriteProcessMemory(current_process, reinterpret_cast<LPVOID>(skillgrp_address), skillgrp_patch, sizeof(skillgrp_patch), nullptr)) {
MessageBoxA(nullptr, "Ошибка при применении skillgrp_patch. Зоннер пидарас.", "Ошибка", MB_OK | MB_ICONERROR);
}
VirtualProtect(reinterpret_cast<LPVOID>(skillgrp_address), sizeof(skillgrp_patch), old_protect, nullptr);
Все замечательно, однако я хочу написать новую функцию, которая так же патчит байты, но уже не в 1 адресе, а в 6.
uintptr_t interface_first_address = nwindow_base + 0x235FA2;
uintptr_t interface_second_address = nwindow_base + 0x245A42;
uintptr_t interface_third_address = nwindow_base + 0x258E4A;
uintptr_t interface_fourth_address = nwindow_base + 0x25B92A;
uintptr_t interface_fifth_address = nwindow_base + 0x25BBA6;
uintptr_t interface_sixth_address = nwindow_base + 0x25BDC2;
BYTE interface_patch[7] = { 0x61, 0x00, 0x6E, 0x00, 0x75, 0x00, 0x73 };
Наверное стоит использовать цикл? Реши эту задачу и не забудь, что нам нужно использовать VirtualProtect для изменения прав на запись, как в примере ранее.
|
1e102ddfec5f6b4c77fb026624858148
|
{
"intermediate": 0.3279667794704437,
"beginner": 0.5163224339485168,
"expert": 0.1557108610868454
}
|
46,217
|
write an vba to list all files on colums A of Sheet1 active folder where excel file are
|
89095cbea489b463c296b9383e5d814d
|
{
"intermediate": 0.44158586859703064,
"beginner": 0.20013217628002167,
"expert": 0.3582819402217865
}
|
46,218
|
if (!passwordPattern.test(password)) {
passwordValidationError.textContent = 'Password must:\nBe at least 7 characters long\nInclude at least 1 uppercase letter\nInclude at least 1 lowercase letter\nInclude at least 1 number\nInclude at least 1 symbol.';
How do i make these print on a newline? \n doesnt work.
|
73c53d12f421f36ae13c0d900169b0cd
|
{
"intermediate": 0.31271374225616455,
"beginner": 0.5177910923957825,
"expert": 0.16949515044689178
}
|
46,219
|
FATAL: role "root" does not exist в docker compose не запускается контейнер с пострегс
|
ac6878aa5ccf83242340f0d07f437530
|
{
"intermediate": 0.36154842376708984,
"beginner": 0.29146549105644226,
"expert": 0.3469861149787903
}
|
46,220
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему?
public class PdfFilesUI : MonoBehaviour
{
private const string PathName = "/StreamingAssets/PDF/Training";
private const string FileExtension = "*.pdf";
private const string PathConverter = "/../Converter/pdf2img.exe";
private const string PathImage = " pageRight.png ";
private const string PathImageFull = "/../pageRight.png";
[SerializeField]
private Transform _contentButton;
[SerializeField]
private Transform _contentImage;
[SerializeField]
private PDFbutton _buttonPrefab;
[SerializeField]
private Image _imagePrefab;
[SerializeField]
private ScrollRect _scrollRect;
private string pdfConverterPath;
private string folderPath; // Внесите переменную сюда
private string dataApplicationPath;
private Dictionary<Button, Image[]> buttonToImagesMapping = new Dictionary<Button, Image[]>();
private List<Image[]> allImageGroups = new List<Image[]>();
public async void Initialize()
{
dataApplicationPath = Application.dataPath;
pdfConverterPath = Application.dataPath + PathConverter;
folderPath = Application.dataPath + PathName; // Ее значение инициализируется здесь
await FindPdfFilesAsync();
}
private async Task FindPdfFilesAsync()
{
var folderPath = Application.dataPath + PathName;
var pdfFiles = Directory.GetFiles(folderPath, FileExtension, SearchOption.AllDirectories);
List<Task> tasks = new List<Task>();
foreach (string file in pdfFiles)
{
tasks.Add(ProcessPdfFileAsync(file));
}
await Task.WhenAll(tasks);
}
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
//var localPath = dataApplicationPath; // Локальная переменная для использования в лямбда выражении
var pageTask = Task.Run(() =>
{
// Вместо прямого создания текстуры, возвращаем путь к изображению
CallExternalProcess(pdfConverterPath, file + PathImage + (pageNumber).ToString());
return dataApplicationPath + PathImageFull; // Просто возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
//private void FindPdfFiles()
//{
// var folderPath = Application.dataPath + PathName;
// var pdfFiles = Directory.GetFiles(folderPath, FileExtension, SearchOption.AllDirectories);
// foreach (string file in pdfFiles)
// {
// var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
// var button = Instantiate(_buttonPrefab, _contentButton);
// button.Initialized(fileNameWithoutExtension, file);
// var pageCount = 0;
// using (PdfReader reader = new PdfReader(file))
// {
// pageCount = reader.NumberOfPages;
// }
// var imageGroup = new Image[pageCount];
// for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
// {
// CallExternalProcess(pdfConverterPath, file + PathImage + (pageNumber).ToString());
// var image = ApplyTextureToUI(Application.dataPath + PathImageFull);
// imageGroup[pageNumber] = image;
// }
// allImageGroups.Add(imageGroup);
// button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
// buttonToImagesMapping[button.Button] = imageGroup;
// }
// AllImagesOff();
//}
public void AllImagesOff()
{
if (allImageGroups == null) return; // Добавить эту проверку
foreach (Image[] images in allImageGroups)
{
foreach (var image in images)
{
if (image != null && image.gameObject != null) // Добавить эту проверку
{
image.gameObject.SetActive(false);
}
}
}
}
public void AllImagesOn(Image[] imageGroup)
{
AllImagesOff();
if (imageGroup == null) return; // Добавить эту проверку
foreach (Image image in imageGroup)
{
if (image != null && image.gameObject != null) // Добавить эту проверку
{
image.gameObject.SetActive(true);
}
}
_scrollRect.verticalNormalizedPosition = 1;
}
public Texture2D LoadPNG(string filePath)
{
Texture2D texture = null;
if (File.Exists(filePath))
{
var fileData = File.ReadAllBytes(filePath);
texture = new Texture2D(2, 2);
texture.LoadImage(fileData);
}
return texture;
}
public Image ApplyTextureToUI(string filePath)
{
var texture = LoadPNG(filePath);
if (texture != null)
{
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);
var image = Instantiate(_imagePrefab, _contentImage);
image.sprite = sprite;
return image;
}
return null;
}
public void CallExternalProcess(string processPath, string arguments)
{
var myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = processPath;
myProcess.StartInfo.Arguments = arguments;
myProcess.EnableRaisingEvents = true;
try
{
myProcess.Start();
}
catch (InvalidOperationException ex)
{
UnityEngine.Debug.LogError(ex);
}
myProcess.WaitForExit();
var ExitCode = myProcess.ExitCode;
}
}
|
6909c7eb65500b39fa16935b29590479
|
{
"intermediate": 0.4130893051624298,
"beginner": 0.4872780740261078,
"expert": 0.09963267296552658
}
|
46,221
|
I have a react app and my page makes request for the current status from react-effector store on load through event that is trighered using React.useEffect at the start. It works fine, however if I am on the other page and press on the button to navigate to my page with a mouse wheel it opens the page in the new tab but doesn't invoke the event. Why is it so and what can I do to trigger it?
|
1a926f029cbe63592a031bf49c528e7f
|
{
"intermediate": 0.6800499558448792,
"beginner": 0.19128964841365814,
"expert": 0.12866036593914032
}
|
46,222
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему?
public class PdfFilesUI : MonoBehaviour
{
private const string PathName = "/StreamingAssets/PDF/Training";
private const string FileExtension = "*.pdf";
private const string PathConverter = "/../Converter/pdf2img.exe";
private const string PathImage = " pageRight.png ";
private const string PathImageFull = "/../pageRight.png";
[SerializeField]
private Transform _contentButton;
[SerializeField]
private Transform _contentImage;
[SerializeField]
private PDFbutton _buttonPrefab;
[SerializeField]
private Image _imagePrefab;
[SerializeField]
private ScrollRect _scrollRect;
private string pdfConverterPath;
private string folderPath; // Внесите переменную сюда
private string dataApplicationPath;
private Dictionary<Button, Image[]> buttonToImagesMapping = new Dictionary<Button, Image[]>();
private List<Image[]> allImageGroups = new List<Image[]>();
public async void Initialize()
{
dataApplicationPath = Application.dataPath;
pdfConverterPath = Application.dataPath + PathConverter;
folderPath = Application.dataPath + PathName; // Ее значение инициализируется здесь
await FindPdfFilesAsync();
}
private async Task FindPdfFilesAsync()
{
var folderPath = Application.dataPath + PathName;
var pdfFiles = Directory.GetFiles(folderPath, FileExtension, SearchOption.AllDirectories);
List<Task> tasks = new List<Task>();
foreach (string file in pdfFiles)
{
tasks.Add(ProcessPdfFileAsync(file));
}
await Task.WhenAll(tasks);
}
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
//var localPath = dataApplicationPath; // Локальная переменная для использования в лямбда выражении
var pageTask = Task.Run(() =>
{
// Вместо прямого создания текстуры, возвращаем путь к изображению
CallExternalProcess(pdfConverterPath, file + PathImage + (pageNumber).ToString());
return dataApplicationPath + PathImageFull; // Просто возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
public void AllImagesOff()
{
if (allImageGroups == null) return; // Добавить эту проверку
foreach (Image[] images in allImageGroups)
{
foreach (var image in images)
{
if (image != null && image.gameObject != null) // Добавить эту проверку
{
image.gameObject.SetActive(false);
}
}
}
}
public void AllImagesOn(Image[] imageGroup)
{
AllImagesOff();
if (imageGroup == null) return; // Добавить эту проверку
foreach (Image image in imageGroup)
{
if (image != null && image.gameObject != null) // Добавить эту проверку
{
image.gameObject.SetActive(true);
}
}
_scrollRect.verticalNormalizedPosition = 1;
}
public Texture2D LoadPNG(string filePath)
{
Texture2D texture = null;
if (File.Exists(filePath))
{
var fileData = File.ReadAllBytes(filePath);
texture = new Texture2D(2, 2);
texture.LoadImage(fileData);
}
return texture;
}
public Image ApplyTextureToUI(string filePath)
{
var texture = LoadPNG(filePath);
if (texture != null)
{
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);
var image = Instantiate(_imagePrefab, _contentImage);
image.sprite = sprite;
return image;
}
return null;
}
public void CallExternalProcess(string processPath, string arguments)
{
var myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = processPath;
myProcess.StartInfo.Arguments = arguments;
myProcess.EnableRaisingEvents = true;
try
{
myProcess.Start();
}
catch (InvalidOperationException ex)
{
UnityEngine.Debug.LogError(ex);
}
myProcess.WaitForExit();
var ExitCode = myProcess.ExitCode;
}
}
|
4d1adade9810d173c8f1b235b7b63ee9
|
{
"intermediate": 0.4573393166065216,
"beginner": 0.4376453161239624,
"expert": 0.10501544177532196
}
|
46,223
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему?
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
//var localPath = dataApplicationPath; // Локальная переменная для использования в лямбда выражении
var pageTask = Task.Run(() =>
{
// Вместо прямого создания текстуры, возвращаем путь к изображению
CallExternalProcess(pdfConverterPath, file + PathImage + (pageNumber).ToString());
return dataApplicationPath + PathImageFull; // Просто возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
|
c879c874746f90efdee6e407caa27dec
|
{
"intermediate": 0.3908824622631073,
"beginner": 0.4777669310569763,
"expert": 0.13135060667991638
}
|
46,224
|
for %i in (*.pdf) do gswin64c -q -dNOPAUSE -sDEVICE=txtwrite -sOutputFile=“%~ni.txt” -dFirstPage=1 -dLastPage=1 “%i” -c quit for this command i want to create a file that double cliked to run with power shell
|
690f0c20f5efd121e5b5773777c41f0b
|
{
"intermediate": 0.43145501613616943,
"beginner": 0.2930241525173187,
"expert": 0.27552086114883423
}
|
46,225
|
for %i in (*.pdf) do gswin64c -q -dNOPAUSE -sDEVICE=txtwrite -sOutputFile=“%~ni.txt” -dFirstPage=1 -dLastPage=1 “%i” -c quit for this command i want to create a file that double cliked to run with power shell
|
d45d67a0968bcd15224e2c49497bed61
|
{
"intermediate": 0.4182282090187073,
"beginner": 0.3081000745296478,
"expert": 0.2736717462539673
}
|
46,226
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему?
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
var localPageNumber = pageNumber; // Локальная переменная для каждой итерации цикла
var pageTask = Task.Run(() =>
{
// Использование localPageNumber вместо pageNumber
CallExternalProcess(pdfConverterPath, file + PathImage + localPageNumber.ToString());
return dataApplicationPath + PathImageFull; // Возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
|
b2dd01a46806e7ff75b784cde7a70ca9
|
{
"intermediate": 0.3172365128993988,
"beginner": 0.5180768966674805,
"expert": 0.16468654572963715
}
|
46,227
|
how to resolve
Non-resolvable parent POM for com.hht.cp:DefectFactorAnalysis:0.0.1-SNAPSHOT: The following artifacts could not be resolved: org.springframework.boot:spring-boot-starter-parent:pom:2.2.7.RELEASE (absent):
|
95e64c6d977fc7281d400e101e0e2164
|
{
"intermediate": 0.5594162940979004,
"beginner": 0.26270121335983276,
"expert": 0.17788249254226685
}
|
46,228
|
i nedd an vba code to do this : inside an folder are 2 excel files one with extension .xlsx and one named MARKER-REPORT.xlsm and i want this : first copy data from .xlsx file in MARKER-REPORT.xlsm then save file MARKER-REPORT.xlsm with the name of .xlsx but with extension .xlsm
|
83ec6d4b80b4010dda6802661b0bd071
|
{
"intermediate": 0.39480993151664734,
"beginner": 0.2529359459877014,
"expert": 0.35225412249565125
}
|
46,229
|
in this javascript can you remove all the code inside the 'buybutton' event listener - 'var money = 100000;
var numberOfCarriages = 1;
var speed = 60;
var dailybonus = 0;
const map = L.map("map").setView([54.2231637, -1.9381623], 6);
// Add custom zoom control to the map with position set to ‘topright’
const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map);
// Remove the default zoom control from the map
map.removeControl(map.zoomControl);
let clickedPoints = [];
let isLineDrawn = false;
let marker; // Declare the marker variable
let progress = 0;
const increaseSpeed = () => {
const speedIncrease = 20;
speed += speedIncrease;
};
// Function to create circle markers with click functionality
function createCircleMarkers(geojson) {
return L.geoJSON(geojson, {
pointToLayer: function (feature, latlng) {
const circleMarker = L.circleMarker(latlng, {
radius: 4,
fillColor: "#ff7800",
color: "#000",
weight: 0.2,
opacity: 1,
fillOpacity: 0.8,
});
// Attach the feature to the circle marker
circleMarker.feature = feature;
circleMarker.on("mouseover", function () {
this.bindPopup(feature.properties.city).openPopup();
});
circleMarker.on("click", function (e) {
if (!isLineDrawn) {
clickedPoints.push(e.target); // Push the circle marker with attached feature
if (clickedPoints.length === 2) {
const firstCityCoords =
clickedPoints[0].feature.geometry.coordinates;
const secondCityCoords =
clickedPoints[1].feature.geometry.coordinates;
const polyline = L.polyline(
clickedPoints.map((p) => p.getLatLng())
).addTo(map);
const firstCity = clickedPoints[0].feature.properties.city;
const secondCity = clickedPoints[1].feature.properties.city;
clickedPoints = [];
isLineDrawn = true;
// Remove click event listener after a line has been drawn
map.off("click");
// Set the map bounds to show the area with the polyline
map.fitBounds(polyline.getBounds());
money = money - 50000; // Subtract 50000 from money
const moneyDisplay = document.getElementById("moneydisplay");
const moneyString = `£${money}`; // Assuming money is a number
moneyDisplay.textContent = moneyString;
const instructionsElement = document.getElementById("instructions");
// Clear any existing content in the instructions element:
instructionsElement.innerHTML = "";
// Create separate paragraph elements:
const congratulationsParagraph = document.createElement("p");
congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`;
const costsParagraph = document.createElement("p");
costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`;
const buyTrainParagraph = document.createElement("p");
buyTrainParagraph.textContent = "You now need to buy a train.";
const newTrainParagraph = document.createElement("p");
newTrainParagraph.textContent =
"At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers";
const traincost = document.createElement("p");
traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`;
// Append paragraphs to the instructions element:
instructionsElement.appendChild(congratulationsParagraph);
instructionsElement.appendChild(costsParagraph);
instructionsElement.appendChild(buyTrainParagraph);
instructionsElement.appendChild(newTrainParagraph);
instructionsElement.appendChild(traincost);
// Add button element:
const buyButton = document.createElement("button");
buyButton.id = "buybutton";
buyButton.textContent = "Buy Train";
// Append the button element to the instructions element:
instructionsElement.appendChild(buyButton);
// Add click event listener to the Buy Train button
document
.getElementById("buybutton")
.addEventListener("click", function () {
money = money - 30000; // Subtract 30000 from money
const moneyDisplay = document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
// Update instructions content after successful purchase
instructionsElement.innerHTML = ""; // Clear previous content
const successMessage = document.createElement("p");
successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`;
instructionsElement.appendChild(successMessage);
// Add button element:
const trainButton = document.createElement("button");
trainButton.id = "trainbutton";
trainButton.textContent = "Start Train";
// Append the button element to the instructions element:
instructionsElement.appendChild(trainButton);
// trainButton click event listener:
trainButton.addEventListener("click", function () {
// Clear any existing content in the instructions element:
instructionsElement.innerHTML = "";
const networkMessage = document.createElement("p");
networkMessage.textContent = `The ${firstCity} to ${secondCity} Rail Company is in operation!`;
const scoreMessage = document.createElement("p");
scoreMessage.textContent = `You will now earn money every time your train arrives at a station (depending on the number of passengers on board). You do not need to worry about scheduling. Your train will now automatically run between your two stations.`;
const updatesMessage = document.createElement("p");
updatesMessage.textContent = `As you earn money you can invest in improving the ${firstCity} to ${secondCity} Rail Company. At the moment your train only has one passenger carriage. Why not increase how much money you make by buying more carriages? Each carriage will cost £20,000.`;
instructionsElement.appendChild(networkMessage);
instructionsElement.appendChild(scoreMessage);
instructionsElement.appendChild(updatesMessage);
// Get a reference to the div element with id "menu"
const menuDiv = document.getElementById("menu");
// Create a new image element
const image = new Image();
// Set the image source URL
image.src =
"https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/carriage.png?v=1712498925908";
// Optionally set the image alt text (for accessibility)
image.alt = "add carriages";
// Set image size using inline styles
image.style.width = "60px";
image.style.height = "60px";
// Append the image element to the div
menuDiv.appendChild(image);
// Attach a mouseover event listener to the image
image.addEventListener("mouseover", () => {
image.style.cursor = "pointer";
});
// Attach a click event listener to the image
image.addEventListener("click", () => {
console.log("Image clicked!");
// Check if enough money is available
if (money >= 20000) {
// Check if maximum number of carriages reached
if (numberOfCarriages < 4) {
numberOfCarriages++;
money -= 20000; // Subtract 20000 from money
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
// Update instructions content after successful purchase
instructionsElement.innerHTML = ""; // Clear previous content
const newcarriageMessage = document.createElement("p");
newcarriageMessage.textContent = `Congratualtions you have bought a new passenger carriage. You now have ${numberOfCarriages} passenger carriages.`;
instructionsElement.appendChild(newcarriageMessage);
// Create a new image element for the train
const newTrainImage = new Image();
newTrainImage.src =
"https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/train.png?v=1712498933227";
newTrainImage.alt = "Train Carriage";
newTrainImage.style.width = "60px"; // Adjust size as needed
newTrainImage.style.height = "60px"; // Adjust size as needed
// Attach a click event listener to the newTrainImage
newTrainImage.addEventListener("click", () => {
console.log("Train icon clicked!");
instructionsElement.innerHTML = ""; // Clear previous content
//add station one cafe button
const stationOneMessage = document.createElement("p");
stationOneMessage.textContent = `Open a cafe in ${firstCity} Station for £2,500.`;
instructionsElement.appendChild(stationOneMessage);
// Add button element:
const cafeOneButton =
document.createElement("button");
cafeOneButton.id = "trainbutton";
cafeOneButton.textContent = "Buy Cafe";
// Append the button element to the instructions element:
instructionsElement.appendChild(cafeOneButton);
//cafeonelogic
cafeOneButton.addEventListener("click", () => {
if (money >= 2500) {
// add a random number between 2000 and 7000 to dailbonus
const randomNumber =
Math.floor(Math.random() * (7000 - 2000)) +
2000;
dailybonus += randomNumber;
console.log("Cafe one bought");
money -= 2500;
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
instructionsElement.removeChild(cafeOneButton);
} else {
instructionsElement.innerHTML = ""; // Clear previous content
// ... insufficient funds logic ...
const fundsMessage = document.createElement("p");
fundsMessage.textContent = `Insufficient funds!`;
instructionsElement.appendChild(fundsMessage);
}
});
//add station two cafe buttons
const stationTwoMessage = document.createElement("p");
stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`;
instructionsElement.appendChild(stationTwoMessage);
// Add button element:
const cafeTwoButton =
document.createElement("button");
cafeTwoButton.id = "trainbutton";
cafeTwoButton.textContent = "Buy Cafe";
// Append the button element to the instructions element:
instructionsElement.appendChild(cafeTwoButton);
//cafetwologic
cafeTwoButton.addEventListener("click", () => {
if (money >= 2500) {
// Generate a random number between 2000 (inclusive) and 7000 (exclusive)
const randomNumber =
Math.floor(Math.random() * (7000 - 2000)) +
2000;
// Add the random number to dailybonus
dailybonus += randomNumber;
console.log("Cafe two bought");
money -= 2500;
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
instructionsElement.removeChild(cafeTwoButton);
} else {
instructionsElement.innerHTML = ""; // Clear previous content
// ... insufficient funds logic ...
const fundsMessage = document.createElement("p");
fundsMessage.textContent = `Insufficient funds!`;
instructionsElement.appendChild(fundsMessage);
}
});
});
newTrainImage.addEventListener("mouseover", () => {
newTrainImage.style.cursor = "pointer";
});
// Append the new train image to the menu element
const menuDiv = document.getElementById("menu");
menuDiv.appendChild(newTrainImage);
} else {
console.log(
"Maximum number of carriages reached! You can't buy more."
);
instructionsElement.innerHTML = ""; // Clear previous content
const maxCarriageMessage = document.createElement("p");
maxCarriageMessage.textContent =
"You already have the maximum number of carriages (4).";
instructionsElement.appendChild(maxCarriageMessage);
}
} else {
console.log(
"Insufficient funds! You need £20,000 to buy a carriage."
// ... insufficient funds logic ...
);
instructionsElement.innerHTML = ""; // Clear previous content
// ... insufficient funds logic ...
const nomoneyMessage = document.createElement("p");
nomoneyMessage.textContent = `Insufficient funds! You need £20,000 to buy a carriage.`;
instructionsElement.appendChild(nomoneyMessage);
}
});
const firstPoint = L.latLng(
firstCityCoords[1],
firstCityCoords[0]
);
const secondPoint = L.latLng(
secondCityCoords[1],
secondCityCoords[0]
);
const intervalDuration = 10; // milliseconds per frame
const distance = firstPoint.distanceTo(secondPoint);
const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour
const latStep = (secondPoint.lat - firstPoint.lat) / steps;
const lngStep = (secondPoint.lng - firstPoint.lng) / steps;
// Create the marker and set its initial position
marker = L.marker(firstPoint).addTo(map);
const moveMarker = (speed) => {
if (progress < steps) {
const newLat = firstPoint.lat + latStep * progress;
const newLng = firstPoint.lng + lngStep * progress;
const newLatLng = L.latLng(newLat, newLng);
marker.setLatLng(newLatLng); // Update the marker's position
progress++;
setTimeout(function () {
moveMarker(speed);
}, intervalDuration);
} else {
// Marker reaches the second point, update money
money +=
Math.floor(Math.random() * (2000 - 1000 + 1)) +
1000 * numberOfCarriages;
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
// Wait two seconds before animating back and call moveBackMarker recursively
setTimeout(() => {
moveBackMarker(speed);
}, 2000); // Wait for 2 seconds (2000 milliseconds)
}
};
const moveBackMarker = (speed) => {
// Corrected calculation for animating back from second point to first
if (progress > 0) {
const newLat =
secondPoint.lat - latStep * (steps - progress);
const newLng =
secondPoint.lng - lngStep * (steps - progress);
const newLatLng = L.latLng(newLat, newLng);
marker.setLatLng(newLatLng); // Update the marker's position
progress--;
setTimeout(function () {
moveBackMarker(speed);
}, intervalDuration);
} else {
console.log("Reached starting point again.");
// Add random number to money and update display
money +=
Math.floor(Math.random() * (2000 - 1000 + 1)) +
1000 * numberOfCarriages;
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
// Reset progress for next round trip
progress = 0;
// Recursively call moveMarker to start next animation cycle
moveMarker(speed);
}
};
moveMarker(speed); // Start the animation
});
});
}
}
});
return circleMarker;
},
});
}
fetch("gb.geojson")
.then((response) => response.json())
.then((geojson) => {
L.geoJSON(geojson, {
fillColor: "none", // Style for polygon (empty fill)
weight: 1,
color: "#000",
opacity: 1,
fillOpacity: 0,
}).addTo(map);
})
.catch((error) => {
console.error("Error loading GeoJSON:", error);
});
fetch("cities.geojson")
.then((response) => response.json())
.then((geojson) => {
createCircleMarkers(geojson).addTo(map);
})
.catch((error) => {
console.error("Error loading GeoJSON:", error);
});
//24 hour clock display
const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds
// Function to format time in 24-hour format with leading zeros
function formatTime(hours, minutes) {
// Handle the case where minutes reach 60 (should display the next hour)
if (minutes === 60) {
hours++;
minutes = 0;
}
return `${hours.toString().padStart(2, "0")}:${minutes
.toString()
.padStart(2, "0")}`;
}
// Function to update the clock display and handle daily bonus
function updateClock() {
const currentTime = new Date();
// Simulate game time by multiplying actual time with multiplier
const gameTime = new Date(currentTime.getTime() * TIME_MULTIPLIER);
// Get hours and minutes in 24-hour format
let hours = gameTime.getHours();
// Get minutes and force them to the nearest multiple of 10 (ending in 0)
let minutes = Math.floor(gameTime.getMinutes() / 10) * 10;
// Format the time string with fixed minute handling
const formattedTime = formatTime(hours, minutes);
// Update the content of the div with the formatted time
document.getElementById("timedisplay").textContent = formattedTime;
// Check if it's midnight (00:00)
if (hours === 0 && minutes === 0) {
// Generate random daily bonus (modify as needed)
const dailyBonus = Math.floor(Math.random() * (7000 - 2000)) + 2000;
money += dailyBonus;
const moneyDisplay = document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
console.log(`Daily bonus of ${dailyBonus} added! Total money: ${money}`); // You can replace console.log with your desired action
}
}
// Call the updateClock function initially
updateClock();
// Update the clock every second to simulate smooth time progression
setInterval(updateClock, 1000);
'
|
212434b6fc24b295b1a05c50a8dcc401
|
{
"intermediate": 0.38782408833503723,
"beginner": 0.4067903757095337,
"expert": 0.2053854912519455
}
|
46,230
|
untar a mysql dump directly into a db in one line of bash
|
e37beef69f8a92f3de2fa18aa13c0274
|
{
"intermediate": 0.4988730549812317,
"beginner": 0.2175893932580948,
"expert": 0.28353753685951233
}
|
46,231
|
Using this python scrip I get the the correct output of + 100500;NET
dataString = "wei.mdf.A:RAW:+ 20617;1;ST;GS;GRO:+ 100500;NET:+ 0.000; TAR:+ 0.000;5e"
datavalue = dataString.split(':')[3]
print (datavalue)
but if i have the "wei.mdf.A:RAW:+ 20617;1;ST;GS;GRO:+ 100500;NET:+ 0.000; TAR:+ 0.000;5e" in a variable and pass as below
data = "wei.mdf.A:RAW:+ 20617;1;ST;GS;GRO:+ 100500;NET:+ 0.000; TAR:+ 0.000;5e"
dataString = (data)
datavalue = dataString.split(':')[3]
print (datavalue)
I get the following error
datavalue = dataString.split(':')[3]
IndexError: list index out of rangewhy is this and how do i correct
|
848d8db343a7c01e7131ecca44aeccb7
|
{
"intermediate": 0.2952970266342163,
"beginner": 0.5653303861618042,
"expert": 0.1393725872039795
}
|
46,232
|
Sub CopyDataAndRenameAutomatically()
Dim folderPath As String
Dim xlsxFile As String, xlsmFile As String
Dim wbSource As Workbook, wbDestination As Workbook
Dim wsSource As Worksheet, wsDestination As Worksheet
Dim lastRow As Long, lastColumn As Long
Dim newName As String
' Automatically getting the folder where this workbook is saved
folderPath = ThisWorkbook.Path
' Ensure folderPath ends with a backslash
If Right(folderPath, 1) <> "" Then folderPath = folderPath & ""
'Finding the files in the folder
xlsxFile = Dir(folderPath & "*.xlsx")
xlsmFile = "MARKER-REPORT.xlsm"
'Exiting the Sub if the .xlsx file is not found
If xlsxFile = "" Then
MsgBox "No .xlsx file found in the directory.", vbExclamation
Exit Sub
End If
'Opening both workbooks
Set wbSource = Workbooks.Open(folderPath & xlsxFile)
Set wbDestination = Workbooks.Open(folderPath & xlsmFile)
'Setting up the source and destination worksheets
Set wsSource = wbSource.Sheets(1)
Set wsDestination = wbDestination.Sheets(1)
'Finding the last row and column with data in the source sheet
lastRow = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row
lastColumn = wsSource.Cells(1, wsSource.Columns.Count).End(xlToLeft).Column
'Copying all data from the source sheet to destination sheet
wsSource.Range(wsSource.Cells(1, 1), wsSource.Cells(lastRow, lastColumn)).Copy
wsDestination.Cells(1, 1).PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False ' To clear clipboard and remove marching ants
' Close the source workbook without saving changes
wbSource.Close SaveChanges:=False
' Save the destination workbook with the new name
newName = Replace(xlsxFile, ".xlsx", ".xlsm") 'Creating the new name based on the .xlsx filename
wbDestination.SaveAs Filename:=folderPath & newName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
' Close the destination workbook
wbDestination.Close SaveChanges:=False
MsgBox "Data copied and file renamed to " & newName, vbInformation
End Sub
no.xslx file found
|
1d83b4cfe4b2e65ac5863b86bc998a90
|
{
"intermediate": 0.30187681317329407,
"beginner": 0.5133987665176392,
"expert": 0.184724360704422
}
|
46,233
|
Ritm getting generate but Variable section not getting attach in Ritm and workflow also not getting . Pls let me know how to map variable section or workflow.
Please verify below code.
var ritmGR = new GlideRecord('sc_req_item');
ritmGR.initialize();
ritmGR.variable = idsArray[x];
//ritmGr.cat_item = currentContext.cat_item;
ritmGR.short_description = 'User - User Id :'+ idsArray;
ritmGR.opened_by =currentContext.requested_for;
ritmGR.due_date = currentContext.due_date;
ritmGR.description= 'User ID' + ' : ' + idsArray +'\n' + ' Requested By' + ':' + currentContext.requested_for + '\n' ;
ritmGR.request = currentContext.request;
ritmGR.insert();
});
},
|
e58f37e939f5d65606ae2e3c5625f282
|
{
"intermediate": 0.4935913383960724,
"beginner": 0.3243231475353241,
"expert": 0.1820855289697647
}
|
46,234
|
how to get all images in directory python
|
afb0c0fff20f0b3138e58c8a3f105439
|
{
"intermediate": 0.36013996601104736,
"beginner": 0.26113319396972656,
"expert": 0.3787268400192261
}
|
46,235
|
Модифицируй мой код и добавь туда построение графика для data на каждом шаге цикла. Графики изобрази в виде матрицы, у которой будет три столбца и нужное количество строк. Используй matplotlib. Вот код:
def calc_experience(df, experience_column, stab_features, smooth=True, sigma=2, draw_graph=True):
df_experience = pd.DataFrame()
for feature in stab_features:
if smooth:
raw = df[feature]
data = gaussian_filter1d(raw, sigma)
else:
data = df[feature]
feature_experience = elbow_point(df[experience_column].values, data)
tmp = pd.DataFrame([feature_experience], columns=['experience', 'metric_value'])
tmp['metric'] = feature
df_experience = pd.concat([df_experience, tmp])
if draw_graph:
figure, axis = plt.subplots(int(np.ceil(len(stab_features) / 3)), 3)
axis[]
return df_experience
|
54440f53ea078502eab694952307fa42
|
{
"intermediate": 0.4834514558315277,
"beginner": 0.3331526219844818,
"expert": 0.18339592218399048
}
|
46,236
|
compose a guide step by step how to create a telegram bot that receives message from the user and replies a message with id and user name of the sender, bot has a button that when clicked returns the number of clicks of whole time
|
880b709c62952abdb0181824bc8342a5
|
{
"intermediate": 0.2886412739753723,
"beginner": 0.27885448932647705,
"expert": 0.432504266500473
}
|
46,237
|
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[4], line 7
4 from accelerate import dispatch_model
6 device_map = auto_configure_device_map(2)
----> 7 model = dispatch_model(model, device_map=device_map)
9 tokenizer = AutoTokenizer.from_pretrained('internlm/internlm-xcomposer2-vl-7b', trust_remote_code=True)
11 text = '<ImageHere>Please describe this image in detail.'
File /opt/conda/lib/python3.10/site-packages/accelerate/big_modeling.py:419, in dispatch_model(model, device_map, main_device, state_dict, offload_dir, offload_index, offload_buffers, skip_keys, preload_module_classes, force_hooks)
414 tied_params_map[data_ptr] = {}
416 # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer,
417 # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
--> 419 attach_align_device_hook_on_blocks(
420 model,
421 execution_device=execution_device,
422 offload=offload,
423 offload_buffers=offload_buffers,
424 weights_map=weights_map,
425 skip_keys=skip_keys,
426 preload_module_classes=preload_module_classes,
427 tied_params_map=tied_params_map,
428 )
430 # warn if there is any params on the meta device
431 offloaded_devices_str = " and ".join(
432 [device for device in set(device_map.values()) if device in ("cpu", "disk")]
433 )
File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:648, in attach_align_device_hook_on_blocks(module, execution_device, offload, weights_map, offload_buffers, module_name, skip_keys, preload_module_classes, tied_params_map)
646 for child_name, child in module.named_children():
647 child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
--> 648 attach_align_device_hook_on_blocks(
649 child,
650 execution_device=execution_device,
651 offload=offload,
652 weights_map=weights_map,
653 offload_buffers=offload_buffers,
654 module_name=child_name,
655 preload_module_classes=preload_module_classes,
656 skip_keys=skip_keys,
657 tied_params_map=tied_params_map,
658 )
File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:648, in attach_align_device_hook_on_blocks(module, execution_device, offload, weights_map, offload_buffers, module_name, skip_keys, preload_module_classes, tied_params_map)
646 for child_name, child in module.named_children():
647 child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
--> 648 attach_align_device_hook_on_blocks(
649 child,
650 execution_device=execution_device,
651 offload=offload,
652 weights_map=weights_map,
653 offload_buffers=offload_buffers,
654 module_name=child_name,
655 preload_module_classes=preload_module_classes,
656 skip_keys=skip_keys,
657 tied_params_map=tied_params_map,
658 )
File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:648, in attach_align_device_hook_on_blocks(module, execution_device, offload, weights_map, offload_buffers, module_name, skip_keys, preload_module_classes, tied_params_map)
646 for child_name, child in module.named_children():
647 child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
--> 648 attach_align_device_hook_on_blocks(
649 child,
650 execution_device=execution_device,
651 offload=offload,
652 weights_map=weights_map,
653 offload_buffers=offload_buffers,
654 module_name=child_name,
655 preload_module_classes=preload_module_classes,
656 skip_keys=skip_keys,
657 tied_params_map=tied_params_map,
658 )
File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:608, in attach_align_device_hook_on_blocks(module, execution_device, offload, weights_map, offload_buffers, module_name, skip_keys, preload_module_classes, tied_params_map)
599 if module_name in execution_device and module_name in offload and not offload[module_name]:
600 hook = AlignDevicesHook(
601 execution_device=execution_device[module_name],
602 offload_buffers=offload_buffers,
(...)
606 tied_params_map=tied_params_map,
607 )
--> 608 add_hook_to_module(module, hook)
609 attach_execution_device_hook(module, execution_device[module_name], tied_params_map=tied_params_map)
610 elif module_name in execution_device and module_name in offload:
File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:157, in add_hook_to_module(module, hook, append)
154 old_forward = module.forward
155 module._old_forward = old_forward
--> 157 module = hook.init_hook(module)
158 module._hf_hook = hook
160 def new_forward(module, *args, **kwargs):
File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:275, in AlignDevicesHook.init_hook(self, module)
273 if not self.offload and self.execution_device is not None:
274 for name, _ in named_module_tensors(module, recurse=self.place_submodules):
--> 275 set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map)
276 elif self.offload:
277 self.original_devices = {
278 name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules)
279 }
File /opt/conda/lib/python3.10/site-packages/accelerate/utils/modeling.py:457, in set_module_tensor_to_device(module, tensor_name, device, value, dtype, fp16_statistics, tied_params_map)
455 torch.xpu.empty_cache()
456 else:
--> 457 torch.cuda.empty_cache()
459 # When handling tied weights, we update tied_params_map to keep track of the tied weights that have already been allocated on the device in
460 # order to avoid duplicating memory, see above.
461 if (
462 tied_params_map is not None
463 and old_value.data_ptr() in tied_params_map
464 and device not in tied_params_map[old_value.data_ptr()]
465 ):
File /opt/conda/lib/python3.10/site-packages/torch/cuda/memory.py:159, in empty_cache()
148 r"""Releases all unoccupied cached memory currently held by the caching
149 allocator so that those can be used in other GPU application and visible in
150 `nvidia-smi`.
(...)
156 more details about GPU memory management.
157 """
158 if is_initialized():
--> 159 torch._C._cuda_emptyCache()
RuntimeError: CUDA error: unspecified launch failure
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions
|
ca4e1d84881e4a836dcb17d7fb3f4fac
|
{
"intermediate": 0.34426581859588623,
"beginner": 0.4588947594165802,
"expert": 0.19683942198753357
}
|
46,238
|
Compose instructions step by step how to create a Telegram bot that interacts with users by replying to their messages with their ID, username, and tracks button clicks with code in laravel. for thas use Telegram Bot SDK and middleware
|
798c167cd8ecf5353abc12f1940aed70
|
{
"intermediate": 0.4129845201969147,
"beginner": 0.23128020763397217,
"expert": 0.35573524236679077
}
|
46,239
|
Compose instructions step by step how to create a Telegram bot that interacts with users by replying to their messages with their ID, username, and tracks button clicks with code in laravel. for thas use Telegram Bot SDK and middleware
|
e2257f6e79b423ada9b4da158b9266b7
|
{
"intermediate": 0.4129845201969147,
"beginner": 0.23128020763397217,
"expert": 0.35573524236679077
}
|
46,240
|
i use arduino nano. is good running log period jobs in ISR? if not how can do with
|
413ca3620be29b11b0374be1970d4911
|
{
"intermediate": 0.4621967077255249,
"beginner": 0.13382624089717865,
"expert": 0.40397703647613525
}
|
46,241
|
Compose instructions step by step how to create a Telegram bot that interacts with users by replying to their messages with their ID, username, and tracks button clicks with code in laravel. for thas use Telegram Bot SDK and middleware
|
20610aed4320681f1cafa4b6d2d1599f
|
{
"intermediate": 0.4129845201969147,
"beginner": 0.23128020763397217,
"expert": 0.35573524236679077
}
|
46,242
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему? я предпологаю что это из-за перезаписи изображений
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
var localPageNumber = pageNumber; // Локальная переменная для каждой итерации цикла
var pageTask = Task.Run(() =>
{
// Использование localPageNumber вместо pageNumber
CallExternalProcess(pdfConverterPath, file + PathImage + localPageNumber.ToString());
return dataApplicationPath + PathImageFull; // Возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
|
567da6b3f12966ee1a1cf49a9231f601
|
{
"intermediate": 0.3579648733139038,
"beginner": 0.42437148094177246,
"expert": 0.21766367554664612
}
|
46,243
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему? я предпологаю что это из-за перезаписи изображений
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
var localPageNumber = pageNumber; // Локальная переменная для каждой итерации цикла
var pageTask = Task.Run(() =>
{
// Использование localPageNumber вместо pageNumber
CallExternalProcess(pdfConverterPath, file + PathImage + localPageNumber.ToString());
return dataApplicationPath + PathImageFull; // Возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
public void CallExternalProcess(string processPath, string arguments)
{
var myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = processPath;
myProcess.StartInfo.Arguments = arguments;
myProcess.EnableRaisingEvents = true;
try
{
myProcess.Start();
}
catch (InvalidOperationException ex)
{
UnityEngine.Debug.LogError(ex);
}
myProcess.WaitForExit();
var ExitCode = myProcess.ExitCode;
}
|
ebad49bfcbfc3dea46e08d75c6ad2e4a
|
{
"intermediate": 0.4306710362434387,
"beginner": 0.4118143916130066,
"expert": 0.15751458704471588
}
|
46,244
|
Heres a particles config file that loops correctly:
{
"autoPlay": true,
"background": {
"color": {
"value": "#333"
},
"image": "",
"position": "",
"repeat": "",
"size": "",
"opacity": 1
},
"backgroundMask": {
"composite": "destination-out",
"cover": {
"color": {
"value": "#fff"
},
"opacity": 1
},
"enable": false
},
"clear": true,
"defaultThemes": {},
"delay": 0,
"fullScreen": {
"enable": false,
"zIndex": 0
},
"detectRetina": true,
"duration": 0,
"fpsLimit": 120,
"interactivity": {
"detectsOn": "window",
"events": {
"onClick": {
"enable": true,
"mode": "push"
},
"onDiv": {
"selectors": [],
"enable": false,
"mode": [],
"type": "circle"
},
"onHover": {
"enable": true,
"mode": "grab",
"parallax": {
"enable": true,
"force": 60,
"smooth": 10
}
},
"resize": {
"delay": 0.5,
"enable": true
}
},
"modes": {
"trail": {
"delay": 1,
"pauseOnStop": false,
"quantity": 1
},
"attract": {
"distance": 200,
"duration": 0.4,
"easing": "ease-out-quad",
"factor": 1,
"maxSpeed": 50,
"speed": 1
},
"bounce": {
"distance": 200
},
"bubble": {
"distance": 400,
"duration": 2,
"mix": false,
"opacity": 0.8,
"size": 40,
"divs": {
"distance": 200,
"duration": 0.4,
"mix": false,
"selectors": []
}
},
"connect": {
"distance": 80,
"links": {
"opacity": 0.5
},
"radius": 60
},
"grab": {
"distance": 400,
"links": {
"blink": false,
"consent": false,
"opacity": 1
}
},
"push": {
"default": true,
"groups": [],
"quantity": 4
},
"remove": {
"quantity": 2
},
"repulse": {
"distance": 200,
"duration": 0.4,
"factor": 100,
"speed": 1,
"maxSpeed": 50,
"easing": "ease-out-quad",
"divs": {
"distance": 200,
"duration": 0.4,
"factor": 100,
"speed": 1,
"maxSpeed": 50,
"easing": "ease-out-quad",
"selectors": []
}
},
"slow": {
"factor": 3,
"radius": 200
},
"light": {
"area": {
"gradient": {
"start": {
"value": "#ffffff"
},
"stop": {
"value": "#000000"
}
},
"radius": 1000
},
"shadow": {
"color": {
"value": "#000000"
},
"length": 2000
}
}
}
},
"manualParticles": [],
"particles": {
"bounce": {
"horizontal": {
"value": 1
},
"vertical": {
"value": 1
}
},
"collisions": {
"absorb": {
"speed": 2
},
"bounce": {
"horizontal": {
"value": 1
},
"vertical": {
"value": 1
}
},
"enable": false,
"maxSpeed": 50,
"mode": "bounce",
"overlap": {
"enable": true,
"retries": 0
}
},
"color": {
"value": "#ffffff",
"animation": {
"h": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
},
"s": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
},
"l": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
}
}
},
"effect": {
"close": true,
"fill": true,
"options": {},
"type": []
},
"groups": {},
"move": {
"angle": {
"offset": 0,
"value": 90
},
"attract": {
"distance": 200,
"enable": false,
"rotate": {
"x": 3000,
"y": 3000
}
},
"center": {
"x": 50,
"y": 50,
"mode": "percent",
"radius": 0
},
"decay": 0,
"distance": {},
"direction": "none",
"drift": 0,
"enable": true,
"gravity": {
"acceleration": 9.81,
"enable": false,
"inverse": false,
"maxSpeed": 50
},
"path": {
"clamp": true,
"delay": {
"value": 0
},
"enable": false,
"options": {}
},
"outModes": {
"default": "out",
"bottom": "out",
"left": "out",
"right": "out",
"top": "out"
},
"random": false,
"size": false,
"speed": 2,
"spin": {
"acceleration": 0,
"enable": false
},
"straight": false,
"trail": {
"enable": false,
"length": 10,
"fill": {}
},
"vibrate": false,
"warp": false
},
"number": {
"density": {
"enable": true,
"width": 1920,
"height": 1080
},
"limit": {
"mode": "delete",
"value": 0
},
"value": 100
},
"opacity": {
"value": {
"min": 0.1,
"max": 0.5
},
"animation": {
"count": 0,
"enable": true,
"speed": 3,
"decay": 0,
"delay": 0,
"sync": false,
"mode": "auto",
"startValue": "random",
"destroy": "none"
}
},
"reduceDuplicates": false,
"shadow": {
"blur": 0,
"color": {
"value": "#000"
},
"enable": false,
"offset": {
"x": 0,
"y": 0
}
},
"shape": {
"close": true,
"fill": true,
"options": {},
"type": "circle"
},
"size": {
"value": {
"min": 1,
"max": 10
},
"animation": {
"count": 0,
"enable": true,
"speed": 20,
"decay": 0,
"delay": 0,
"sync": false,
"mode": "auto",
"startValue": "random",
"destroy": "none"
}
},
"stroke": {
"width": 0
},
"zIndex": {
"value": 0,
"opacityRate": 1,
"sizeRate": 1,
"velocityRate": 1
},
"destroy": {
"bounds": {},
"mode": "none",
"split": {
"count": 1,
"factor": {
"value": 3
},
"rate": {
"value": {
"min": 4,
"max": 9
}
},
"sizeOffset": true,
"particles": {}
}
},
"roll": {
"darken": {
"enable": false,
"value": 0
},
"enable": false,
"enlighten": {
"enable": false,
"value": 0
},
"mode": "vertical",
"speed": 25
},
"tilt": {
"value": 0,
"animation": {
"enable": false,
"speed": 0,
"decay": 0,
"sync": false
},
"direction": "clockwise",
"enable": false
},
"twinkle": {
"lines": {
"enable": false,
"frequency": 0.05,
"opacity": 1
},
"particles": {
"enable": false,
"frequency": 0.05,
"opacity": 1
}
},
"wobble": {
"distance": 5,
"enable": false,
"speed": {
"angle": 50,
"move": 10
}
},
"life": {
"count": 0,
"delay": {
"value": 0,
"sync": false
},
"duration": {
"value": 0,
"sync": false
}
},
"rotate": {
"value": 0,
"animation": {
"enable": false,
"speed": 0,
"decay": 0,
"sync": false
},
"direction": "clockwise",
"path": false
},
"orbit": {
"animation": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": false
},
"enable": false,
"opacity": 1,
"rotation": {
"value": 45
},
"width": 1
},
"links": {
"blink": false,
"color": {
"value": "#ffffff"
},
"consent": false,
"distance": 150,
"enable": true,
"frequency": 1,
"opacity": 0.4,
"shadow": {
"blur": 5,
"color": {
"value": "#000"
},
"enable": false
},
"triangles": {
"enable": false,
"frequency": 1
},
"width": 1,
"warp": false
},
"repulse": {
"value": 0,
"enabled": false,
"distance": 1,
"duration": 1,
"factor": 1,
"speed": 1
}
},
"pauseOnBlur": true,
"pauseOnOutsideViewport": true,
"responsive": [],
"smooth": false,
"style": {},
"themes": [],
"zLayers": 100,
"name": "Parallax",
"motion": {
"disable": false,
"reduce": {
"factor": 4,
"value": true
}
}
}
This one doesn't:
{
"autoPlay": true,
"background": {
"color": {
"value": "#000000"
},
"image": "",
"position": "",
"repeat": "",
"size": "",
"opacity": 1
},
"backgroundMask": {
"composite": "destination-out",
"cover": {
"color": {
"value": "#fff"
},
"opacity": 1
},
"enable": false
},
"clear": true,
"defaultThemes": {},
"delay": 0,
"fullScreen": {
"enable": false,
"zIndex": 0
},
"detectRetina": true,
"duration": 0,
"fpsLimit": 120,
"interactivity": {
"detectsOn": "window",
"events": {
"onClick": {
"enable": false,
"mode": []
},
"onDiv": {
"selectors": [],
"enable": false,
"mode": [],
"type": "circle"
},
"onHover": {
"enable": false,
"mode": [],
"parallax": {
"enable": false,
"force": 2,
"smooth": 10
}
},
"resize": {
"delay": 0.5,
"enable": true
}
},
"modes": {
"trail": {
"delay": 1,
"pauseOnStop": false,
"quantity": 1
},
"attract": {
"distance": 200,
"duration": 0.4,
"easing": "ease-out-quad",
"factor": 1,
"maxSpeed": 50,
"speed": 1
},
"bounce": {
"distance": 200
},
"bubble": {
"distance": 200,
"duration": 0.4,
"mix": false
},
"connect": {
"distance": 80,
"links": {
"opacity": 0.5
},
"radius": 60
},
"grab": {
"distance": 100,
"links": {
"blink": false,
"consent": false,
"opacity": 1
}
},
"push": {
"default": true,
"groups": [],
"quantity": 4
},
"remove": {
"quantity": 2
},
"repulse": {
"distance": 200,
"duration": 0.4,
"factor": 100,
"speed": 1,
"maxSpeed": 50,
"easing": "ease-out-quad"
},
"slow": {
"factor": 3,
"radius": 200
},
"light": {
"area": {
"gradient": {
"start": {
"value": "#ffffff"
},
"stop": {
"value": "#000000"
}
},
"radius": 1000
},
"shadow": {
"color": {
"value": "#000000"
},
"length": 2000
}
}
}
},
"manualParticles": [],
"particles": {
"bounce": {
"horizontal": {
"value": 1
},
"vertical": {
"value": 1
}
},
"collisions": {
"absorb": {
"speed": 2
},
"bounce": {
"horizontal": {
"value": 1
},
"vertical": {
"value": 1
}
},
"enable": false,
"maxSpeed": 50,
"mode": "bounce",
"overlap": {
"enable": true,
"retries": 0
}
},
"color": {
"value": "#fff",
"animation": {
"h": {
"count": 0,
"enable": false,
"speed": 20,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
},
"s": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
},
"l": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
}
}
},
"effect": {
"close": true,
"fill": true,
"options": {},
"type": []
},
"groups": {
"z5000": {
"number": {
"value": 70
},
"zIndex": {
"value": 50
}
},
"z7500": {
"number": {
"value": 30
},
"zIndex": {
"value": 75
}
},
"z2500": {
"number": {
"value": 50
},
"zIndex": {
"value": 25
}
},
"z1000": {
"number": {
"value": 40
},
"zIndex": {
"value": 10
}
}
},
"move": {
"angle": {
"offset": 0,
"value": 10
},
"attract": {
"distance": 200,
"enable": false,
"rotate": {
"x": 3000,
"y": 3000
}
},
"center": {
"x": 50,
"y": 50,
"mode": "percent",
"radius": 0
},
"decay": 0,
"distance": {},
"direction": "right",
"drift": 0,
"enable": true,
"gravity": {
"acceleration": 9.81,
"enable": false,
"inverse": false,
"maxSpeed": 50
},
"path": {
"clamp": true,
"delay": {
"value": 0
},
"enable": false,
"options": {}
},
"outModes": {
"default": "out",
"bottom": "out",
"left": "out",
"right": "out",
"top": "out"
},
"random": false,
"size": false,
"speed": 5,
"spin": {
"acceleration": 0,
"enable": false
},
"straight": false,
"trail": {
"enable": false,
"length": 10,
"fill": {}
},
"vibrate": false,
"warp": false
},
"number": {
"density": {
"enable": false,
"width": 1920,
"height": 1080
},
"limit": {
"mode": "delete",
"value": 0
},
"value": 200
},
"opacity": {
"value": 1,
"animation": {
"count": 0,
"enable": false,
"speed": 2,
"decay": 0,
"delay": 0,
"sync": false,
"mode": "auto",
"startValue": "random",
"destroy": "none"
}
},
"reduceDuplicates": false,
"shadow": {
"blur": 0,
"color": {
"value": "#000"
},
"enable": false,
"offset": {
"x": 0,
"y": 0
}
},
"shape": {
"close": true,
"fill": true,
"options": {},
"type": "circle"
},
"size": {
"value": 3,
"animation": {
"count": 0,
"enable": false,
"speed": 5,
"decay": 0,
"delay": 0,
"sync": false,
"mode": "auto",
"startValue": "random",
"destroy": "none"
}
},
"stroke": {
"width": 0
},
"zIndex": {
"value": 5,
"opacityRate": 0.5,
"sizeRate": 1,
"velocityRate": 1
},
"destroy": {
"bounds": {},
"mode": "none",
"split": {
"count": 1,
"factor": {
"value": 3
},
"rate": {
"value": {
"min": 4,
"max": 9
}
},
"sizeOffset": true,
"particles": {}
}
},
"roll": {
"darken": {
"enable": false,
"value": 0
},
"enable": false,
"enlighten": {
"enable": false,
"value": 0
},
"mode": "vertical",
"speed": 25
},
"tilt": {
"value": 0,
"animation": {
"enable": false,
"speed": 0,
"decay": 0,
"sync": false
},
"direction": "clockwise",
"enable": false
},
"twinkle": {
"lines": {
"enable": false,
"frequency": 0.05,
"opacity": 1
},
"particles": {
"enable": false,
"frequency": 0.05,
"opacity": 1
}
},
"wobble": {
"distance": 5,
"enable": false,
"speed": {
"angle": 50,
"move": 10
}
},
"life": {
"count": 0,
"delay": {
"value": 0,
"sync": false
},
"duration": {
"value": 0,
"sync": false
}
},
"rotate": {
"value": 0,
"animation": {
"enable": false,
"speed": 0,
"decay": 0,
"sync": false
},
"direction": "clockwise",
"path": false
},
"orbit": {
"animation": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": false
},
"enable": false,
"opacity": 1,
"rotation": {
"value": 45
},
"width": 1
},
"links": {
"blink": false,
"color": {
"value": "#fff"
},
"consent": false,
"distance": 100,
"enable": false,
"frequency": 1,
"opacity": 1,
"shadow": {
"blur": 5,
"color": {
"value": "#000"
},
"enable": false
},
"triangles": {
"enable": false,
"frequency": 1
},
"width": 1,
"warp": false
},
"repulse": {
"value": 0,
"enabled": false,
"distance": 1,
"duration": 1,
"factor": 1,
"speed": 1
}
},
"pauseOnBlur": true,
"pauseOnOutsideViewport": true,
"responsive": [],
"smooth": false,
"style": {},
"themes": [],
"zLayers": 100,
"name": "Among Us",
"emitters": {
"autoPlay": true,
"fill": true,
"life": {
"wait": false
},
"rate": {
"quantity": 1,
"delay": 7
},
"shape": {
"options": {},
"replace": {
"color": false,
"opacity": false
},
"type": "square"
},
"startCount": 0,
"size": {
"mode": "percent",
"height": 0,
"width": 0
},
"particles": {
"shape": {
"type": "images",
"options": {
"images": {
"src": "https://particles.js.org/images/cyan_amongus.png",
"width": 500,
"height": 634
}
}
},
"size": {
"value": 40
},
"move": {
"speed": 10,
"outModes": {
"default": "none",
"right": "destroy"
},
"straight": true
},
"zIndex": {
"value": 0
},
"rotate": {
"value": {
"min": 0,
"max": 360
},
"animation": {
"enable": true,
"speed": 10,
"sync": true
}
}
},
"position": {
"x": -5,
"y": 55
}
},
"motion": {
"disable": false,
"reduce": {
"factor": 4,
"value": true
}
}
}
Why?
|
01959b548bb5a1dbbfa488ee9967dd6d
|
{
"intermediate": 0.24602457880973816,
"beginner": 0.5868037939071655,
"expert": 0.1671716272830963
}
|
46,245
|
Is there a more elegant way to check for items in my dictionary as "Container" is repeating all over again?
Dictionary<string, List<MyTerminalBlock>> ContainerMap = new Dictionary<string, List<IMyTerminalBlock>>{
{StoneContainerKeyword, StoneContainers},
{FeOreContainerKeyword, FeOreContainers},
{MgOreContainerKeyword, MgOreContainers},
{NiOreContainerKeyword, NiOreContainers},
{SiOreContainerKeyword, SiOreContainers},
{CoOreContainerKeyword, CoOreContainers},
{PtOreContainerKeyword, PtOreContainers},
{AgOreContainerKeyword, AgOreContainers},
{AuOreContainerKeyword, AuOreContainers},
{UOreContainerKeyword, UOreContainers},
{FeIngotContainerKeyword, FeIngotContainers},
{MgIngotContainerKeyword, MgIngotContainers},
{NiIngotContainerKeyword, NiIngotContainers},
{SiIngotContainerKeyword, SiIngotContainers},
{CoIngotContainerKeyword, CoIngotContainers},
{PtIngotContainerKeyword, PtIngotContainers},
{AgIngotContainerKeyword, AgIngotContainers},
{AuIngotContainerKeyword, AuIngotContainers},
{UIngotContainerKeyword, UIngotContainers},
{ComponentContainerKeyword, ComponentContainers},
{AmmoContainerKeyword, AmmoContainers},
{SpecialContainerKeyword, SpecialContainer}
}
bool isTypeContainer = false;
foreach(var pair in ContainerMap){
if (blockname.Contains(pair.Key)) {
pair.Value.Add(block);
isTypeContainer = true;
}
}
|
4e6afe13a595c76abf13b3c4257e675b
|
{
"intermediate": 0.2943551242351532,
"beginner": 0.44742444157600403,
"expert": 0.258220374584198
}
|
46,246
|
write arduino nano wtd example
|
79f513125eaebeb26e5b457eba176bff
|
{
"intermediate": 0.3800114393234253,
"beginner": 0.251914381980896,
"expert": 0.3680742084980011
}
|
46,247
|
When running npm install, this appears npm WARN deprecated particles.vue3@2.12.0: @tsparticles/vue3 is the new package for v3, please use that
How do I get rid of the old and install the new
|
65be605d512a954f7f206c44778c03a1
|
{
"intermediate": 0.5329390168190002,
"beginner": 0.2549767792224884,
"expert": 0.21208418905735016
}
|
46,248
|
is it ok to store 9kk files in one directory?
|
8054bb07c9617b5db63f49917bf83e8b
|
{
"intermediate": 0.3507598340511322,
"beginner": 0.2531202435493469,
"expert": 0.3961198925971985
}
|
46,249
|
import tensorflow as tf
from transformers import TFAutoModelForCausalLM, AutoTokenizer
# Initialize MirroredStrategy
strategy = tf.distribute.MirroredStrategy(
devices=["/gpu:0", "/gpu:1", "/gpu:2", "/gpu:3", "/gpu:4", "/gpu:5"],
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce()
)
print('Number of devices: {}'.format(strategy.num_replicas_in_sync))
# Load model and tokenizer outside of strategy, tokenizer operations don't need to be distributed
model_name = "distilgpt2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
with strategy.scope():
# Load model within strategy's scope to ensure it's distributed across the specified GPUs
model = TFAutoModelForCausalLM.from_pretrained(model_name, pad_token_id=tokenizer.eos_token_id)
def generate_response(context_messages, user_prompts):
with strategy.scope():
relevant_context = [msg['content'] for msg in context_messages[-3:]] # Limiting to the last 3 messages for context
combined_prompts = [
context + " " + user_input['content']
for context in relevant_context for user_input in user_prompts
]
responses = [] # Placeholder for responses
with strategy.scope(): # Ensure generation occurs within strategy context
input_ids = tokenizer(combined_prompts, return_tensors='tf', padding=True, truncation=True, max_length=128)
attention_mask = input_ids['attention_mask']
with strategy.scope():
output_ids = model.generate(input_ids=input_ids['input_ids'], attention_mask=attention_mask,
max_length=128, do_sample=True, temperature=0.7,
top_k=50, top_p=0.95,)
responses = [
"Market Analysis: " + tokenizer.decode(out_id, skip_special_tokens=True)
+ " Trading Suggestion: ..."
for out_id in output_ids
]
return responses
# Initial Context
messages = [
{"role": "system", "content": "You are a futures stock, forex, and cryptocurrency day trader."},
{"role": "system", "content": "The NASDAQ is up slightly today. I'm considering taking a position in Apple."}
]
user_inputs = [] # To collect user prompts
# Main Interaction Loop
while True:
with strategy.scope():
new_prompt = input("Enter your new prompt (or type 'go' to process): ")
if new_prompt.lower() == 'go':
if not user_inputs:
print("No prompts entered. Exiting.")
break
# Generate responses based on collected prompts and existing context
responses = generate_response(messages, user_inputs)
for response in responses:
print("Trader Response:", response)
# Extend the messages (context history) with the collected user inputs for next iteration
messages.extend(user_inputs)
user_inputs = [] # Clear user inputs for next batch of prompts
else:
user_inputs.append({"role": "user", "content": new_prompt}) fix this format output according to the documentation.
|
f0395399d7457af045b40486bf41fd2f
|
{
"intermediate": 0.30101093649864197,
"beginner": 0.47843167185783386,
"expert": 0.22055740654468536
}
|
46,250
|
TUrn this into a json config file:
//tsParticles library - https://github.com/matteobruni/tsparticles
//tsParticles library - https://github.com/matteobruni/tsparticles
tsParticles.load("tsparticles", {
fullScreen: {
enable: true
},
fpsLimit: 60,
particles: {
groups: {
z5000: {
number: {
value: 70
},
zIndex: {
value: 5000
}
},
z7500: {
number: {
value: 30
},
zIndex: {
value: 75
}
},
z2500: {
number: {
value: 50
},
zIndex: {
value: 25
}
},
z1000: {
number: {
value: 40
},
zIndex: {
value: 10
}
}
},
number: {
value: 200,
density: {
enable: false,
value_area: 800
}
},
color: {
value: "#fff",
animation: {
enable: false,
speed: 20,
sync: true
}
},
shape: {
type: "circle"
},
opacity: {
value: 1,
random: false,
animation: {
enable: false,
speed: 3,
minimumValue: 0.1,
sync: false
}
},
size: {
value: 3
},
links: {
enable: false,
distance: 100,
color: "#ffffff",
opacity: 0.4,
width: 1
},
move: {
angle: {
value: 10,
offset: 0
},
enable: true,
speed: 5,
direction: "right",
random: false,
straight: true,
outModes: {
default: "out"
},
attract: {
enable: false,
rotateX: 600,
rotateY: 1200
}
},
zIndex: {
value: 5,
opacityRate: 0.5
}
},
interactivity: {
detectsOn: "canvas",
events: {
onHover: {
enable: false,
mode: "repulse"
},
onClick: {
enable: true,
mode: "push"
},
resize: true
},
modes: {
grab: {
distance: 400,
links: {
opacity: 1
}
},
bubble: {
distance: 400,
size: 40,
duration: 2,
opacity: 0.8
},
repulse: {
distance: 200
},
push: {
quantity: 4,
groups: ["z5000", "z7500", "z2500", "z1000"]
},
remove: {
quantity: 2
}
}
},
detectRetina: true,
background: {
color: "#000000",
image: "",
position: "50% 50%",
repeat: "no-repeat",
size: "cover"
},
emitters: {
position: {
y: 55,
x: -30
},
rate: {
delay: 7,
quantity: 1
},
size: {
width: 0,
height: 0
},
particles: {
shape: {
type: "images",
options: {
images: [
{
src: "https://particles.js.org/images/amongus_blue.png",
width: 205,
height: 267
},
{
src: "https://particles.js.org/images/amongus_cyan.png",
width: 207,
height: 265
},
{
src: "https://particles.js.org/images/amongus_green.png",
width: 204,
height: 266
},
{
src: "https://particles.js.org/images/amongus_lime.png",
width: 206,
height: 267
},
{
src: "https://particles.js.org/images/amongus_orange.png",
width: 205,
height: 265
},
{
src: "https://particles.js.org/images/amongus_pink.png",
width: 205,
height: 265
},
{
src: "https://particles.js.org/images/amongus_red.png",
width: 204,
height: 267
},
{
src: "https://particles.js.org/images/amongus_white.png",
width: 205,
height: 267
}
]
}
},
size: {
value: 40
},
move: {
speed: 10,
outModes: {
default: "destroy",
left: "none"
},
straight: true
},
zIndex: {
value: 0
},
rotate: {
value: {
min: 0,
max: 360
},
animation: {
enable: true,
speed: 10,
sync: true
}
}
}
}
});
|
3ca9cd94c91c4aac18ef570c1d1c2388
|
{
"intermediate": 0.3696451187133789,
"beginner": 0.4054873287677765,
"expert": 0.2248675674200058
}
|
46,251
|
in bash script pass a command as an array, add a parameter to it and execute it
|
0728aaa0142342a5c771e9314e4ecf8d
|
{
"intermediate": 0.3578106760978699,
"beginner": 0.23138843476772308,
"expert": 0.41080090403556824
}
|
46,252
|
i processing many images and i want somehow appent result in one file every 10 files, rewriting whole file everytime is bad, how i can do that?
|
53636b275a01b844d3cb3c10bf144e1e
|
{
"intermediate": 0.3992415964603424,
"beginner": 0.20783275365829468,
"expert": 0.3929256796836853
}
|
46,253
|
how install Celtoys / Remotery profiler in Defold project
|
48d23b1d1af6dc7ffa753003a32b67d9
|
{
"intermediate": 0.6325185298919678,
"beginner": 0.07951650023460388,
"expert": 0.28796496987342834
}
|
46,254
|
此处的 x, attn = self.backbone(z=x_template_img, x=x_search_img,
ce_template_mask=ce_template_mask,
ce_keep_rate=ce_keep_rate,
return_last_attn=return_last_attn)
event_x,event_attn = self.backbone(z=event_template_img, x=event_search_img,
ce_template_mask=ce_template_mask,
ce_keep_rate=ce_keep_rate,
return_last_attn=return_last_attn)
# Forward head
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last,s_attn,None)
return out中采用双头输出,需要对 feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last,s_attn,None)
return out进行修改
|
25e85ae0cd35d37b9060cbb43607fc0a
|
{
"intermediate": 0.37892237305641174,
"beginner": 0.3619558811187744,
"expert": 0.25912171602249146
}
|
46,255
|
I'm using Vue3 and tsparticles. The white particles are supposed to fly right, then loop endlessly. It starts out fine, but doens't appear to loop even though the behavior works on other websites. When I click, however, a wave of particles in a row all start from the left side of the screen. I'm not sure what's happening. How can I fix it
{
"fullScreen": {
"enable": false
},
"fpsLimit": 60,
"particles": {
"groups": {
"z5000": {
"number": {
"value": 70
},
"zIndex": {
"value": 5000
}
},
"z7500": {
"number": {
"value": 30
},
"zIndex": {
"value": 75
}
},
"z2500": {
"number": {
"value": 50
},
"zIndex": {
"value": 25
}
},
"z1000": {
"number": {
"value": 40
},
"zIndex": {
"value": 10
}
}
},
"number": {
"value": 200,
"density": {
"enable": false,
"value_area": 800
}
},
"color": {
"value": "#fff",
"animation": {
"enable": false,
"speed": 20,
"sync": true
}
},
"shape": {
"type": "circle"
},
"opacity": {
"value": 1,
"random": false,
"animation": {
"enable": false,
"speed": 3,
"minimumValue": 0.1,
"sync": false
}
},
"size": {
"value": 3
},
"links": {
"enable": false,
"distance": 100,
"color": "#ffffff",
"opacity": 0.4,
"width": 1
},
"move": {
"angle": {
"value": 10,
"offset": 0
},
"enable": true,
"speed": 5,
"direction": "right",
"random": false,
"straight": true,
"outModes": {
"default": "out"
},
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
},
"zIndex": {
"value": 5,
"opacityRate": 0.5
}
},
"interactivity": {
"detectsOn": "canvas",
"events": {
"onHover": {
"enable": false,
"mode": "repulse"
},
"onClick": {
"enable": true,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 400,
"links": {
"opacity": 1
}
},
"bubble": {
"distance": 400,
"size": 40,
"duration": 2,
"opacity": 0.8
},
"repulse": {
"distance": 200
},
"push": {
"quantity": 4,
"groups": ["z5000", "z7500", "z2500", "z1000"]
},
"remove": {
"quantity": 2
}
}
},
"detectRetina": true,
"background": {
"color": "#000000",
"image": "",
"position": "50% 50%",
"repeat": "no-repeat",
"size": "cover"
},
"emitters": {
"position": {
"y": 55,
"x": -30
},
"rate": {
"delay": 7,
"quantity": 1
},
"size": {
"width": 0,
"height": 0
},
"particles": {
"shape": {
"type": "images",
"options": {
"images": [
{
"src": "https://particles.js.org/images/amongus_blue.png",
"width": 205,
"height": 267
},
{
"src": "https://particles.js.org/images/amongus_cyan.png",
"width": 207,
"height": 265
},
{
"src": "https://particles.js.org/images/amongus_green.png",
"width": 204,
"height": 266
},
{
"src": "https://particles.js.org/images/amongus_lime.png",
"width": 206,
"height": 267
},
{
"src": "https://particles.js.org/images/amongus_orange.png",
"width": 205,
"height": 265
},
{
"src": "https://particles.js.org/images/amongus_pink.png",
"width": 205,
"height": 265
},
{
"src": "https://particles.js.org/images/amongus_red.png",
"width": 204,
"height": 267
},
{
"src": "https://particles.js.org/images/amongus_white.png",
"width": 205,
"height": 267
}
]
}
},
"size": {
"value": 40
},
"move": {
"speed": 10,
"outModes": {
"default": "destroy",
"left": "none"
},
"straight": true
},
"zIndex": {
"value": 0
},
"rotate": {
"value": {
"min": 0,
"max": 360
},
"animation": {
"enable": true,
"speed": 10,
"sync": true
}
}
}
}
}
|
6b4948ee89f3f0b26c73faa76ef27f7a
|
{
"intermediate": 0.4095708131790161,
"beginner": 0.37087154388427734,
"expert": 0.21955764293670654
}
|
46,256
|
I'm using Vue3 and tsparticles. I copied this config file from the demo website which works flawlessly on their site, but is broken on mine. The white particles are supposed to fly right, then loop endlessly. It starts out fine, but doens't appear to loop even though the behavior works on other websites. When I click, however, a wave of particles in a row all start from the left side of the screen. I'm not sure what's happening. How can I fix it
{
"fullScreen": {
"enable": false
},
"fpsLimit": 60,
"particles": {
"groups": {
"z5000": {
"number": {
"value": 70
},
"zIndex": {
"value": 5000
}
},
"z7500": {
"number": {
"value": 30
},
"zIndex": {
"value": 75
}
},
"z2500": {
"number": {
"value": 50
},
"zIndex": {
"value": 25
}
},
"z1000": {
"number": {
"value": 40
},
"zIndex": {
"value": 10
}
}
},
"number": {
"value": 200,
"density": {
"enable": false,
"value_area": 800
}
},
"color": {
"value": "#fff",
"animation": {
"enable": false,
"speed": 20,
"sync": true
}
},
"shape": {
"type": "circle"
},
"opacity": {
"value": 1,
"random": false,
"animation": {
"enable": false,
"speed": 3,
"minimumValue": 0.1,
"sync": false
}
},
"size": {
"value": 3
},
"links": {
"enable": false,
"distance": 100,
"color": "#ffffff",
"opacity": 0.4,
"width": 1
},
"move": {
"angle": {
"value": 10,
"offset": 0
},
"enable": true,
"speed": 5,
"direction": "right",
"random": false,
"straight": true,
"outModes": {
"default": "out"
},
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
},
"zIndex": {
"value": 5,
"opacityRate": 0.5
}
},
"interactivity": {
"detectsOn": "canvas",
"events": {
"onHover": {
"enable": false,
"mode": "repulse"
},
"onClick": {
"enable": true,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 400,
"links": {
"opacity": 1
}
},
"bubble": {
"distance": 400,
"size": 40,
"duration": 2,
"opacity": 0.8
},
"repulse": {
"distance": 200
},
"push": {
"quantity": 4,
"groups": ["z5000", "z7500", "z2500", "z1000"]
},
"remove": {
"quantity": 2
}
}
},
"detectRetina": true,
"background": {
"color": "#000000",
"image": "",
"position": "50% 50%",
"repeat": "no-repeat",
"size": "cover"
},
"emitters": {
"position": {
"y": 55,
"x": -30
},
"rate": {
"delay": 7,
"quantity": 1
},
"size": {
"width": 0,
"height": 0
},
"particles": {
"shape": {
"type": "images",
"options": {
"images": [
{
"src": "https://particles.js.org/images/amongus_blue.png",
"width": 205,
"height": 267
},
{
"src": "https://particles.js.org/images/amongus_cyan.png",
"width": 207,
"height": 265
},
{
"src": "https://particles.js.org/images/amongus_green.png",
"width": 204,
"height": 266
},
{
"src": "https://particles.js.org/images/amongus_lime.png",
"width": 206,
"height": 267
},
{
"src": "https://particles.js.org/images/amongus_orange.png",
"width": 205,
"height": 265
},
{
"src": "https://particles.js.org/images/amongus_pink.png",
"width": 205,
"height": 265
},
{
"src": "https://particles.js.org/images/amongus_red.png",
"width": 204,
"height": 267
},
{
"src": "https://particles.js.org/images/amongus_white.png",
"width": 205,
"height": 267
}
]
}
},
"size": {
"value": 40
},
"move": {
"speed": 10,
"outModes": {
"default": "destroy",
"left": "none"
},
"straight": true
},
"zIndex": {
"value": 0
},
"rotate": {
"value": {
"min": 0,
"max": 360
},
"animation": {
"enable": true,
"speed": 10,
"sync": true
}
}
}
}
}
|
be0dbdc23d398697315cbaf935eef3ef
|
{
"intermediate": 0.4705151319503784,
"beginner": 0.3189700245857239,
"expert": 0.21051476895809174
}
|
46,257
|
You’re an experienced scriptwriter for Roblox games, known for creating innovative and efficient scripts that enhance user experience through data storage mechanisms like Datastores. Your task is to write a script for a Roblox game that effectively datastores hats with a handle in them. The script should ensure seamless handling of hat storage, retrieval, and modification processes.
When creating the script, keep in mind the essential functionalities required for this task, such as setting up Datastores to store hat data, including handle details, implementing robust data retrieval mechanisms, and ensuring secure data modification capabilities without compromising game performance.
For example, in similar projects, you have efficiently managed complex data storage systems in Roblox games, ensuring optimal performance and data integrity. You have developed scripts that seamlessly handle various in-game items, such as weapons, accessories, and cosmetic items, along with their individual attributes and properties. Your expertise lies in creating scripts that are not only functional and reliable but also contribute to a smooth and enjoyable gameplay experience for users.
|
ec08bee27f20a7b4d1ed5602b577dae2
|
{
"intermediate": 0.4288422167301178,
"beginner": 0.3376659154891968,
"expert": 0.23349183797836304
}
|
46,258
|
I'm using Vue3 and tsparticles. I copied this config file from the demo website which works flawlessly on their site, but is broken on mine. The white particles are supposed to loop endlessly. Again, the config file was copied directly from their website, but it fails on mine. I think it's related to my particular setup. I'm using tsparticles with vue. It starts out fine, but doens't appear to loop even though the behavior works on other websites. When I click, however, a wave of particles in a row all start from the left side of the screen. It's NOT an outmodes problem, because it works on their site but not on mine. It's not a config file problem.
{
"autoPlay": true,
"background": {
"color": {
"value": "#000000"
},
"image": "",
"position": "",
"repeat": "",
"size": "",
"opacity": 1
},
"backgroundMask": {
"composite": "destination-out",
"cover": {
"color": {
"value": "#fff"
},
"opacity": 1
},
"enable": false
},
"clear": true,
"defaultThemes": {},
"delay": 0,
"fullScreen": {
"enable": true,
"zIndex": 0
},
"detectRetina": true,
"duration": 0,
"fpsLimit": 120,
"interactivity": {
"detectsOn": "window",
"events": {
"onClick": {
"enable": false,
"mode": []
},
"onDiv": {
"selectors": [],
"enable": false,
"mode": [],
"type": "circle"
},
"onHover": {
"enable": false,
"mode": [],
"parallax": {
"enable": false,
"force": 2,
"smooth": 10
}
},
"resize": {
"delay": 0.5,
"enable": true
}
},
"modes": {
"trail": {
"delay": 1,
"pauseOnStop": false,
"quantity": 1
},
"attract": {
"distance": 200,
"duration": 0.4,
"easing": "ease-out-quad",
"factor": 1,
"maxSpeed": 50,
"speed": 1
},
"bounce": {
"distance": 200
},
"bubble": {
"distance": 200,
"duration": 0.4,
"mix": false
},
"connect": {
"distance": 80,
"links": {
"opacity": 0.5
},
"radius": 60
},
"grab": {
"distance": 100,
"links": {
"blink": false,
"consent": false,
"opacity": 1
}
},
"push": {
"default": true,
"groups": [],
"quantity": 4
},
"remove": {
"quantity": 2
},
"repulse": {
"distance": 200,
"duration": 0.4,
"factor": 100,
"speed": 1,
"maxSpeed": 50,
"easing": "ease-out-quad"
},
"slow": {
"factor": 3,
"radius": 200
},
"light": {
"area": {
"gradient": {
"start": {
"value": "#ffffff"
},
"stop": {
"value": "#000000"
}
},
"radius": 1000
},
"shadow": {
"color": {
"value": "#000000"
},
"length": 2000
}
}
}
},
"manualParticles": [],
"particles": {
"bounce": {
"horizontal": {
"value": 1
},
"vertical": {
"value": 1
}
},
"collisions": {
"absorb": {
"speed": 2
},
"bounce": {
"horizontal": {
"value": 1
},
"vertical": {
"value": 1
}
},
"enable": false,
"maxSpeed": 50,
"mode": "bounce",
"overlap": {
"enable": true,
"retries": 0
}
},
"color": {
"value": "#fff",
"animation": {
"h": {
"count": 0,
"enable": false,
"speed": 20,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
},
"s": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
},
"l": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": true,
"offset": 0
}
}
},
"effect": {
"close": true,
"fill": true,
"options": {},
"type": []
},
"groups": {
"z5000": {
"number": {
"value": 70
},
"zIndex": {
"value": 50
}
},
"z7500": {
"number": {
"value": 30
},
"zIndex": {
"value": 75
}
},
"z2500": {
"number": {
"value": 50
},
"zIndex": {
"value": 25
}
},
"z1000": {
"number": {
"value": 40
},
"zIndex": {
"value": 10
}
}
},
"move": {
"angle": {
"offset": 0,
"value": 10
},
"attract": {
"distance": 200,
"enable": false,
"rotate": {
"x": 3000,
"y": 3000
}
},
"center": {
"x": 50,
"y": 50,
"mode": "percent",
"radius": 0
},
"decay": 0,
"distance": {},
"direction": "right",
"drift": 0,
"enable": true,
"gravity": {
"acceleration": 9.81,
"enable": false,
"inverse": false,
"maxSpeed": 50
},
"path": {
"clamp": true,
"delay": {
"value": 0
},
"enable": false,
"options": {}
},
"outModes": {
"default": "out",
"bottom": "out",
"left": "out",
"right": "out",
"top": "out"
},
"random": false,
"size": false,
"speed": 5,
"spin": {
"acceleration": 0,
"enable": false
},
"straight": false,
"trail": {
"enable": false,
"length": 10,
"fill": {}
},
"vibrate": false,
"warp": false
},
"number": {
"density": {
"enable": false,
"width": 1920,
"height": 1080
},
"limit": {
"mode": "delete",
"value": 0
},
"value": 200
},
"opacity": {
"value": 1,
"animation": {
"count": 0,
"enable": false,
"speed": 2,
"decay": 0,
"delay": 0,
"sync": false,
"mode": "auto",
"startValue": "random",
"destroy": "none"
}
},
"reduceDuplicates": false,
"shadow": {
"blur": 0,
"color": {
"value": "#000"
},
"enable": false,
"offset": {
"x": 0,
"y": 0
}
},
"shape": {
"close": true,
"fill": true,
"options": {},
"type": "circle"
},
"size": {
"value": 3,
"animation": {
"count": 0,
"enable": false,
"speed": 5,
"decay": 0,
"delay": 0,
"sync": false,
"mode": "auto",
"startValue": "random",
"destroy": "none"
}
},
"stroke": {
"width": 0
},
"zIndex": {
"value": 5,
"opacityRate": 0.5,
"sizeRate": 1,
"velocityRate": 1
},
"destroy": {
"bounds": {},
"mode": "none",
"split": {
"count": 1,
"factor": {
"value": 3
},
"rate": {
"value": {
"min": 4,
"max": 9
}
},
"sizeOffset": true,
"particles": {}
}
},
"roll": {
"darken": {
"enable": false,
"value": 0
},
"enable": false,
"enlighten": {
"enable": false,
"value": 0
},
"mode": "vertical",
"speed": 25
},
"tilt": {
"value": 0,
"animation": {
"enable": false,
"speed": 0,
"decay": 0,
"sync": false
},
"direction": "clockwise",
"enable": false
},
"twinkle": {
"lines": {
"enable": false,
"frequency": 0.05,
"opacity": 1
},
"particles": {
"enable": false,
"frequency": 0.05,
"opacity": 1
}
},
"wobble": {
"distance": 5,
"enable": false,
"speed": {
"angle": 50,
"move": 10
}
},
"life": {
"count": 0,
"delay": {
"value": 0,
"sync": false
},
"duration": {
"value": 0,
"sync": false
}
},
"rotate": {
"value": 0,
"animation": {
"enable": false,
"speed": 0,
"decay": 0,
"sync": false
},
"direction": "clockwise",
"path": false
},
"orbit": {
"animation": {
"count": 0,
"enable": false,
"speed": 1,
"decay": 0,
"delay": 0,
"sync": false
},
"enable": false,
"opacity": 1,
"rotation": {
"value": 45
},
"width": 1
},
"links": {
"blink": false,
"color": {
"value": "#fff"
},
"consent": false,
"distance": 100,
"enable": false,
"frequency": 1,
"opacity": 1,
"shadow": {
"blur": 5,
"color": {
"value": "#000"
},
"enable": false
},
"triangles": {
"enable": false,
"frequency": 1
},
"width": 1,
"warp": false
},
"repulse": {
"value": 0,
"enabled": false,
"distance": 1,
"duration": 1,
"factor": 1,
"speed": 1
}
},
"pauseOnBlur": true,
"pauseOnOutsideViewport": true,
"responsive": [],
"smooth": false,
"style": {},
"themes": [],
"zLayers": 100,
"name": "Among Us",
"emitters": {
"autoPlay": true,
"fill": true,
"life": {
"wait": false
},
"rate": {
"quantity": 1,
"delay": 7
},
"shape": {
"options": {},
"replace": {
"color": false,
"opacity": false
},
"type": "square"
},
"startCount": 0,
"size": {
"mode": "percent",
"height": 0,
"width": 0
},
"particles": {
"shape": {
"type": "images",
"options": {
"images": {
"src": "https://particles.js.org/images/cyan_amongus.png",
"width": 500,
"height": 634
}
}
},
"size": {
"value": 40
},
"move": {
"speed": 10,
"outModes": {
"default": "none",
"right": "destroy"
},
"straight": true
},
"zIndex": {
"value": 0
},
"rotate": {
"value": {
"min": 0,
"max": 360
},
"animation": {
"enable": true,
"speed": 10,
"sync": true
}
}
},
"position": {
"x": -5,
"y": 55
}
},
"motion": {
"disable": false,
"reduce": {
"factor": 4,
"value": true
}
}
}
|
0ffd159f736f9f4d08597d4e01c33460
|
{
"intermediate": 0.47846099734306335,
"beginner": 0.3378922939300537,
"expert": 0.18364667892456055
}
|
46,259
|
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
const port = 3000;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public')); // Serve static files from 'public' directory
// Route for registration form
app.get('/registration', (req, res) => {
res.sendFile(__dirname + '/public/registration.html');
});
// Route to handle form submission
app.post('/register', (req, res) => {
const { username, email, password } = req.body;
const userData = { username, email, password };
// Append user data to a JSON file
fs.readFile('users.json', (err, data) => {
let json = data.length ? JSON.parse(data) : [];
json.push(userData);
fs.writeFile('users.json', JSON.stringify(json, null, 2), (err) => {
if (err) throw err;
res.redirect('/content'); // Redirect to the content page
});
});
});
// Route for content page
app.get('/content', (req, res) => {
res.sendFile(__dirname + '/public/content.html');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Can you change this code so it runs publicly instead of localhost?
|
4bfe0a4e286e9a59987e903737c9948e
|
{
"intermediate": 0.6638413667678833,
"beginner": 0.17030827701091766,
"expert": 0.16585040092468262
}
|
46,260
|
i try to run this code in jupyternotebook in cloud <code>!conda install -y aria2</code>. but when i run the code this error is shown <error>Channels:
- defaults
Platform: linux-64
Collecting package metadata (repodata.json): done
Solving environment: failed
PackagesNotFoundError: The following packages are not available from current channels:
- aria2
Current channels:
- defaults
To search for alternate channels that may provide the conda package you're
looking for, navigate to
https://anaconda.org
and use the search bar at the top of the page.</error>. can you fx it
|
c3b35ff16832533340d18225e638e75f
|
{
"intermediate": 0.4020465612411499,
"beginner": 0.23870329558849335,
"expert": 0.35925009846687317
}
|
46,261
|
Что не так в моей функции generate? from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup
from aiogram.utils.callback_data import CallbackData
import aiosqlite
import asyncio
import requests
API_TOKEN = '6996318383:AAEcQfdQhzEg3L_6DKQVidJEn46Wb27Sy4g'
ADMINS = [989037374, 123456789]
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
class Form(StatesGroup):
choosing_action = State()
answer_question = State()
class lk(StatesGroup):
personal_account = State()
edit_answer = State()
new_answer = State()
edit_answer_select = State()
edit_answer_cb = State()
new_answer_cb = State()
class admin(StatesGroup):
admin_panel = State()
select_question_to_delete = State()
select_question_to_edit = State()
edit_question_text = State()
new_question = State()
async def create_db():
async with aiosqlite.connect('base.db') as db:
await db.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
last_question_idx INTEGER DEFAULT 0)''')
await db.execute('''CREATE TABLE IF NOT EXISTS questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT NOT NULL,
order_num INTEGER NOT NULL)''')
await db.execute('''CREATE TABLE IF NOT EXISTS answers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
question TEXT,
answer TEXT,
FOREIGN KEY (user_id) REFERENCES users (id))''')
await db.commit()
# Обработка под MarkdownV2
def mdv2(text: str) -> str:
escape_chars = [
"_", "*", "[", "]", "(", ")", "~", "`", ">",
"#", "+", "-", "=", "|", "{", "}", ".", "!"
]
for char in escape_chars:
text = text.replace(char, f"\{char}")
text = text.replace('"', '“')
return text
# калбэки
change_action_cb = CallbackData('change', 'action')
# КНОПКА МЕНЮ
menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
menu.add(KeyboardButton("В меню"))
async def add_user(user_id: int, username: str):
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,))
user_exists = await cursor.fetchone()
if user_exists:
await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id))
else:
await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username))
await db.commit()
@dp.message_handler(commands="start", state="*")
async def cmd_start(message: types.Message):
markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
markup.add(KeyboardButton("Сгенерировать био"))
markup.add(KeyboardButton("Личный кабинет"))
user_id = message.from_user.id
username = message.from_user.username or "unknown"
await add_user(user_id, username)
if user_id not in ADMINS:
await message.answer("Выберите действие:", reply_markup=markup)
await Form.choosing_action.set()
else:
markup.add(KeyboardButton("Админ-панель"))
await message.answer("Выберите действие:", reply_markup=markup)
await Form.choosing_action.set()
@dp.message_handler(lambda message: message.text == "В меню", state="*")
async def back_to_menu(message: types.Message):
markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
markup.add(KeyboardButton("Сгенерировать био"))
markup.add(KeyboardButton("Личный кабинет"))
if message.from_user.id not in ADMINS:
await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup)
await Form.choosing_action.set()
else:
markup.add(KeyboardButton("Админ-панель"))
await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup)
await Form.choosing_action.set()
async def save_answer(user_id: int, question: str, answer: str, question_idx: int):
async with aiosqlite.connect('base.db') as db:
await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)',
(user_id, question, answer))
await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id))
await db.commit()
async def set_next_question(user_id: int):
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,))
result = await cursor.fetchone()
last_question_idx = result[0] if result else 0
next_question_idx = last_question_idx + 1
question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,))
question_text = await question_cursor.fetchone()
if question_text:
await bot.send_message(user_id, question_text[0], reply_markup=menu)
await Form.answer_question.set()
await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id))
await db.commit()
else:
answers_text = ""
cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,))
answers = await cursor.fetchall()
for idx, (question, answer) in enumerate(answers, start=1):
answers_text += f"{idx}. {question} - {answer}\n"
markup = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="Сгенерировать", callback_data=change_action_cb.new(action="generate"))],
[InlineKeyboardButton(text="Изменить ответ", callback_data=change_action_cb.new(action="change"))],
[InlineKeyboardButton(text="Заполнить заново",
callback_data=change_action_cb.new(action="refill"))],
]
)
await bot.send_message(user_id, f"Вот ваши ответы:\n\n{answers_text}", reply_markup=markup)
await dp.current_state(user=user_id).reset_state(with_data=False)
@dp.callback_query_handler(change_action_cb.filter(action="change"), state="*")
async def change_answer(callback_query: types.CallbackQuery, state: FSMContext):
await bot.answer_callback_query(callback_query.id)
await lk.edit_answer.set()
await bot.send_message(callback_query.from_user.id, "Введите номер вопроса, который хотите изменить:")
@dp.message_handler(state=lk.edit_answer_cb)
async def enter_question_number(message: types.Message, state: FSMContext):
question_number = message.text
if not question_number.isdigit():
await message.reply("Пожалуйста, введите номер вопроса цифрами. Попробуйте снова:")
return
await state.update_data(question_number=int(question_number))
await lk.new_answer.set()
await message.answer("Введите новый ответ:")
@dp.callback_query_handler(change_action_cb.filter(action="refill"), state="*")
async def process_refill(callback_query: types.CallbackQuery, callback_data: dict):
user_id = callback_query.from_user.id
await bot.answer_callback_query(callback_query.id)
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да, начать заново", callback_data="confirm_refill"))
await bot.send_message(user_id, "Вы уверены, что хотите начать заново? Ваши текущие ответы будут удалены.", reply_markup=markup)
@dp.message_handler(state=lk.new_answer_cb)
async def update_answer(message: types.Message, state: FSMContext):
new_answer_text = message.text
user_data = await state.get_data()
question_number = user_data['question_number']
user_id = message.from_user.id
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,))
question_text = await cursor.fetchone()
if question_text:
await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?',
(new_answer_text, user_id, question_text[0]))
await db.commit()
await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer_text}", reply_markup=menu)
else:
await message.answer(f"Проблема при редактировании ответа, вопрос не найден.")
await state.finish()
await set_next_question(user_id)
@dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action)
async def generate_bio(message: types.Message):
user_id = message.from_user.id
await set_next_question(user_id)
@dp.message_handler(state=Form.answer_question)
async def process_question_answer(message: types.Message, state: FSMContext):
user_id = message.from_user.id
answer_text = message.text
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,))
result = await cursor.fetchone()
current_question_idx = result[0] if result else 0
cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,))
question = await cursor.fetchone()
if question:
question_text = question[0]
await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)',
(user_id, question_text, answer_text))
await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id))
await db.commit()
else:
await message.answer("Произошла ошибка при сохранении вашего ответа.")
await set_next_question(user_id)
@dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action)
async def personal_account(message: types.Message):
user_id = message.from_user.id
answers_text = "Личный кабинет\n\nВаши ответы:\n"
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,))
answers = await cursor.fetchall()
for idx, (question, answer) in enumerate(answers, start=1):
answers_text += f"{idx}. {question}: {answer}\n"
if answers_text == "Личный кабинет\n\nВаши ответы:\n":
answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы"
await message.answer(answers_text, reply_markup=menu)
else:
markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
markup.add(KeyboardButton("Изменить ответ"))
markup.add(KeyboardButton("Заполнить заново"))
markup.add(KeyboardButton("В меню"))
await message.answer(answers_text, reply_markup=markup)
await lk.personal_account.set()
@dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account)
async def change_answer(message: types.Message):
await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu)
await lk.edit_answer.set()
@dp.message_handler(state=lk.edit_answer)
async def process_question_number(message: types.Message, state: FSMContext):
text = message.text
question_number = int(text)
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,))
question_text = await cursor.fetchone()
if question_text:
await state.update_data(question=question_text[0], question_number=question_number)
await message.answer("Введите новый ответ:")
await lk.new_answer.set()
else:
await message.answer(f"Вопроса под номером {question_number} не существует.")
@dp.message_handler(state=lk.new_answer)
async def process_new_answer(message: types.Message, state: FSMContext):
user_data = await state.get_data()
question_number = user_data['question_number']
new_answer = message.text
markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
markup.add(KeyboardButton("Изменить ответ"))
markup.add(KeyboardButton("Заполнить заново"))
markup.add(KeyboardButton("В меню"))
user_id = message.from_user.id
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,))
question_text = await cursor.fetchone()
if question_text:
await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0]))
await db.commit()
await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}", reply_markup=markup)
else:
await message.answer(f"Проблема при редактировании ответа, вопрос не найден.")
await state.finish()
await personal_account(message)
@dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account)
async def refill_form(message: types.Message):
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill"))
await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup)
@dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state="*")
async def process_refill(callback_query: types.CallbackQuery):
user_id = callback_query.from_user.id
async with aiosqlite.connect('base.db') as db:
await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,))
await db.commit()
await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,))
await db.commit()
state = dp.current_state(user=user_id)
await state.reset_state(with_data=False)
await bot.answer_callback_query(callback_query.id)
await bot.send_message(user_id, "Ваши ответы удалены.")
await cmd_start(callback_query.message)
# ГЕНЕРАЦИЯ
async def generate(prompt: str, apikey: str, sa_id: str, user_id -> str:
url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Api-Key {apikey}'
}
data = {
"modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest",
"completionOptions": {
"stream": False,
"temperature": 0.6,
"maxTokens": "1000"
},
"messages": [
{
"role": "system",
"text": "Отвечай как можно более кратко"
},
{
"role": "user",
"text": prompt
}
]
}
try:
response = requests.post(url, json=data, headers=headers)
response_data = response.json()
answer = response_data.get("completions")[-1].get("text")
await bot.send_message(user_id, answer)
except Exception as e:
return await bot.send_message(user_id, "Произошла ошибка. Пожалуйста, попробуйте еще раз.")
@dp.callback_query_handler(change_action_cb.filter(action="generate"), state="*")
async def process_generate(callback_query: types.CallbackQuery):
user_id = callback_query.from_user.id
prompt = ""
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,))
answers = await cursor.fetchall()
for question, answer in answers:
prompt += f"\n{question} - {answer}"
api_key = "ваш_ключ_api"
sa_id = "ваш_sa_id"
await generate(prompt, api_key, sa_id, user_id)
# АДМИН-ПАНЕЛЬ
# КНОПКА НАЗАД
back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False)
back.add(KeyboardButton("Назад"))
# КЛАВА
admin_kb = ReplyKeyboardMarkup(resize_keyboard=True)
admin_kb.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню")
@dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete])
async def back_to_admin_panel(message: types.Message, state: FSMContext):
await state.finish()
await admin_panel(message)
@dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action)
async def admin_panel(message: types.Message):
if message.from_user.id not in ADMINS:
await message.answer("Доступ запрещен.")
return
await message.answer("Админ-панель:", reply_markup=admin_kb)
await admin.admin_panel.set()
@dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel)
async def show_questions(message: types.Message):
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC")
questions = await cursor.fetchall()
if questions:
text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)])
else:
text = "Вопросы отсутствуют."
await message.answer(text)
@dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel)
async def add_question_start(message: types.Message):
await message.answer("Введите текст нового вопроса:", reply_markup=back)
await admin.new_question.set()
@dp.message_handler(state=admin.new_question)
async def add_question_process(message: types.Message, state: FSMContext):
new_question = message.text
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute("SELECT MAX(order_num) FROM questions")
max_order_num = await cursor.fetchone()
next_order_num = (max_order_num[0] or 0) + 1
await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num))
await db.commit()
await message.answer("Вопрос успешно добавлен.", reply_markup=admin_kb)
await admin.admin_panel.set()
@dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel)
async def select_question_to_edit_start(message: types.Message):
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC")
questions = await cursor.fetchall()
if not questions:
await message.answer("Вопросы отсутствуют.")
return
text = "Выберите номер вопроса для редактирования:\n\n"
text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions)
await message.answer(text, reply_markup=back)
await admin.select_question_to_edit.set()
@dp.message_handler(state=admin.select_question_to_edit)
async def edit_question(message: types.Message, state: FSMContext):
qid_text = message.text
if not qid_text.isdigit():
await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back)
return
qid = int(qid_text)
async with state.proxy() as data:
data['question_id'] = qid
await admin.edit_question_text.set()
await message.answer("Введите новый текст вопроса:", reply_markup=back)
@dp.message_handler(state=admin.edit_question_text)
async def update_question(message: types.Message, state: FSMContext):
new_text = message.text
async with state.proxy() as data:
qid = data['question_id']
async with aiosqlite.connect('base.db') as db:
await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid))
await db.commit()
await message.answer("Вопрос успешно отредактирован.", reply_markup=admin_kb)
await admin.admin_panel.set()
@dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel)
async def select_question_to_delete_start(message: types.Message):
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC")
questions = await cursor.fetchall()
if not questions:
await message.answer("Вопросы отсутствуют.")
return
text = "Выберите номер вопроса для удаления:\n\n"
text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions)
await message.answer(text, reply_markup=back)
await admin.select_question_to_delete.set()
@dp.message_handler(state=admin.select_question_to_delete)
async def delete_question(message: types.Message, state: FSMContext):
qid_text = message.text
if not qid_text.isdigit():
await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back)
return
qid = int(qid_text)
async with aiosqlite.connect('base.db') as db:
cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,))
question = await cursor.fetchone()
if not question:
await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.")
return
order_num_to_delete = question[0]
await db.execute("DELETE FROM questions WHERE id = ?", (qid,))
await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,))
await db.commit()
await message.answer("Вопрос успешно удален.", reply_markup=admin_kb)
await admin.admin_panel.set()
async def main():
await create_db()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
executor.start_polling(dp, skip_updates=True)
|
90d8e6ef233227dd560c8076938d91a8
|
{
"intermediate": 0.32209745049476624,
"beginner": 0.5310580730438232,
"expert": 0.14684441685676575
}
|
46,262
|
write an vba code to copy data from one excel file to another
|
59c6db12a96935de7f0774d35d3fa6b3
|
{
"intermediate": 0.6028842329978943,
"beginner": 0.15376080572605133,
"expert": 0.24335499107837677
}
|
46,263
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Objects;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Net;
using System.Reflection;
using ServicesApiOcaPeek.Data;
using ServicesApiOcaPeek.ExceptionPersonnalisees;
using ServicesApiOcaPeek.Extensions;
using ServicesApiOcaPeek.Models;
namespace ServicesApiOcaPeek.Helpers
{
/// <summary>
/// Gestion de l'accès à la couche de données
/// </summary>
public class ServicesApiOcaPeekDataHelper : IDisposable
{
OCAPEEKEntities ent;
public virtual void Dispose()
{
ent.Dispose();
ent = null;
}
/// <summary>
///
/// </summary>
public ServicesApiOcaPeekDataHelper()
{
try
{
ent = new OCAPEEKEntities();
}
catch (Exception exc)
{
Utils.ElmahLogException(exc);
throw exc;
}
}
#region Check connection base
/// <summary>
/// Permet de test si la base de données est disponible
/// </summary>
/// <returns></returns>
internal bool CheckConnectionBase()
{
return ent.DatabaseExists();
}
internal bool CheckAccessTable()
{
return ent.OP_VISITE.Any();
}
#endregion
public PAR_GEN_SERV GetParcGenServDansBdd(string environnement)
{
return ent.PAR_GEN_SERV.Where(w => w.PGS_ENV.Equals(environnement, StringComparison.OrdinalIgnoreCase))
.SingleOrDefault();
}
/// <summary>
/// recuperer les visites
/// </summary>
/// <param name="site">site</param>
/// <param name="username">nom d'utilisateur</param>
/// <param name="startDate">date de debut</param>
/// <param name="endDate">date de fin</param>
/// <param name="sortindex">nom propiete </param>
/// <param name="sortdir">sans de l'ordre (exemple : 'ASC' pour croissant)</param>
/// <param name="page">numéro de page</param>
/// <param name="count">nombre element dans une page</param>
/// <param name="archive"></param>
/// <returns></returns>
public ListePaginee<Visite> ListeVisites(string site = null, string username = null, DateTime? startDate = null,
DateTime? endDate = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10,
bool archive = false)
{
var req = ent.OP_VISITE
.Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh })
.Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID,
(joined, ovv) => new { joined.ov, joined.odh, ovv })
.Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID,
(joined, ovvs) => new { joined.ov, joined.odh, joined.ovv, ovvs })
.Where(joined => (string.IsNullOrEmpty(site) || joined.ov.OPV_SITE.StartsWith(site)) &&
(string.IsNullOrEmpty(username) ||
joined.ov.OPV_COLLAB_USERNAME.StartsWith(username)) &&
(startDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) >=
EntityFunctions.TruncateTime(startDate)) &&
(endDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) <=
EntityFunctions.TruncateTime(endDate)) &&
(joined.ov.OPV_ARCHIVE == archive))
.Select(result => new Visite
{
id = result.ov.OPV_ID,
archive = result.ov.OPV_ARCHIVE,
description = result.ov.OPV_DESCRIPTION,
site = result.ov.OPV_SITE,
status = result.ov.OPV_STATUS,
sujet = result.ov.OPV_SUJET,
titre = result.ov.OPV_TITRE,
type = result.ov.OPV_TYPE_VISITE,
dateDebut = result.odh.OPDH_DATE_DEBUT,
dateFin = result.odh.OPDH_DATE_FIN,
duree = result.odh.OPDH_DUREE,
heureArrivee = result.odh.OPDH_HEURE_ARRIVEE,
heureDepart = result.odh.OPDH_HEURE_DEPART,
badge = result.ovv.OPVVS_BADGE,
overtime = result.ovv.OPVVS_OVERTIME,
plaqueImmatriculation = result.ovv.OPVVS_PLAQUE_IMMATRICUL,
parking = result.ovv.OPVVS_PARKING,
nomCollaborateur = result.ov.OPV_COLLAB_USERNAME,
contact = new VisiteContact
{
nom = result.ov.OPV_NOM_CONTACT,
telephone = result.ov.OPV_TELEPHONE_CONTACT
}
}).OrderBy(x => EntityFunctions.DiffDays(x.dateDebut, DateTime.Now)).AsEnumerable();
req = req.Distinct();
var visiteListe = req.ToList();
List<Visite> listeVisite = new List<Visite>();
#region système de pagination
int total = req.Count();
IEnumerable<Visite> elems = Enumerable.Empty<Visite>();
if (string.IsNullOrEmpty(sortindex))
{
elems = req.AsEnumerable();
}
else
{
var nomPropriete = typeof(Visite).GetProperty(sortindex,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase))
{
elems = req.OrderBy(x => nomPropriete.GetValue(x, null));
}
else
{
elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null));
}
}
var res = elems.Skip((page - 1) * count).Take(count);
#endregion
return new ListePaginee<Visite> { count = count, elements = res.ToList(), page = page, total = total };
}
public Visite GetVisite(int visiteId)
{
var listeVisiteur = GetListeVisiteurFromVisite(visiteId);
var req = (from ov in ent.OP_VISITE
join odh in ent.OP_DATE_HORAIRE on ov.OPV_ID equals odh.OPDH_OPV_ID
join ovv in ent.OP_VISITE_VISITEUR on ov.OPV_ID equals ovv.OPVVS_OPV_ID
join ovvs in ent.OP_VISITEUR on ovv.OPVVS_OPVS_ID equals ovvs.OPVS_ID
where
(
ov.OPV_ID.Equals(visiteId)
)
select new Visite
{
archive = ov.OPV_ARCHIVE,
badge = ovv.OPVVS_BADGE,
dateDebut = odh.OPDH_DATE_DEBUT,
dateFin = odh.OPDH_DATE_FIN,
overtime = ovv.OPVVS_OVERTIME,
titre = ov.OPV_TITRE,
description = ov.OPV_DESCRIPTION,
site = ov.OPV_SITE,
type = ov.OPV_TYPE_VISITE,
status = ov.OPV_STATUS,
id = ov.OPV_ID,
duree = odh.OPDH_DUREE,
heureArrivee = odh.OPDH_HEURE_ARRIVEE,
heureDepart = odh.OPDH_HEURE_DEPART,
nomCollaborateur = ov.OPV_COLLAB_USERNAME,
reponse = new VisiteReponse
{
refus = (bool)ovv.OPVVS_REFUS ? ovv.OPVVS_REFUS : false,
raisonRefus = ovv.OPVVS_RAISON_REFUS
},
contact = new VisiteContact
{
nom = ov.OPV_NOM_CONTACT,
telephone = ov.OPV_TELEPHONE_CONTACT
}
}).AsEnumerable();
if (listeVisiteur.Count == 0)
{
throw new Exception("Aucun visiteur pour cette visite");
}
var visiteWithVisiteurs = req.ToArray();
var visiteToReturn = req.FirstOrDefault();
visiteToReturn.reponse = null;
for (var i = 0; i < visiteWithVisiteurs.Length; i++)
{
var visiteur = listeVisiteur.ElementAt(i);
var visite = visiteWithVisiteurs.ElementAt(i);
visiteur.reponse = visite.reponse;
}
if (visiteToReturn != null)
{
visiteToReturn.visiteurs = listeVisiteur;
}
//return visiteWithVisiteurs;
return visiteToReturn;
}
public VisiteCourante GetVisiteByKey(string key)
{
var vvs = ent.OP_VISITE_VISITEUR.SingleOrDefault(v => v.OPVVS_CLE_LIEN == key);
if (vvs == null)
{
throw new ExceptionNotFoundApi("Clé invalide");
}
var visiteur = vvs.OP_VISITEUR;
var visite = vvs.OP_VISITE;
var odh = visite.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID);
if (odh == null || vvs == null)
{
throw new ExceptionNotFoundApi("Erreur: Cette visite n'existe pas");
}
return new VisiteCourante
{
archive = vvs.OP_VISITE.OPV_ARCHIVE,
collabUsername = visite.OPV_COLLAB_USERNAME,
confirmee = vvs.OPVVS_CONFIRMEE,
overtime = vvs.OPVVS_OVERTIME,
badge = vvs.OPVVS_BADGE,
parking = vvs.OPVVS_PARKING,
dateDebut = odh.OPDH_DATE_DEBUT,
heureDebut = odh.OPDH_HEURE_ARRIVEE,
heureDebutPrev = odh.OPDH_HEURE_DEBUT_PREV,
dateDebutPrev = odh.OPDH_DATE_DEBUT_PREV,
dateFinPrev = odh.OPDH_DATE_FIN_PREV,
heureFinPrev = odh.OPDH_HEURE_FIN_PREV,
description = visite.OPV_DESCRIPTION,
donneeReponse = vvs.OPVVS_DONNEE_REPONSE,
horaireId = odh.OPDH_ID,
idVvs = vvs.OPVVS_ID,
idVisite = visite.OPV_ID,
idVisiteur = visiteur.OPVS_ID,
email = visiteur.OPVS_EMAIL,
nom = visiteur.OPVS_NOM,
prenom = visiteur.OPVS_PRENOM,
telephone = visiteur.OPVS_TELEPHONE,
site = visite.OPV_SITE,
status = visite.OPV_STATUS,
titre = visite.OPV_TITRE,
typeVisite = visite.OPV_TYPE_VISITE,
duree = odh.OPDH_DUREE.HasValue ? odh.OPDH_DUREE.Value : 0,
};
}
/// <summary>
/// Crée une visite
/// </summary>
/// <param name="valeur"></param>
/// <returns>Identifiant de la visite crée</returns>
public VisiteVisiteur CreerVisite(VisiteVisiteur valeur)
{
if (valeur.visiteurs.Count <= 0)
{
throw new Exception("Au moins un visiteur est requis");
}
var visite = new OP_VISITE
{
OPV_ARCHIVE = false,
OPV_DESCRIPTION = valeur.visite.description,
OPV_SITE = valeur.visite.site,
OPV_STATUS = valeur.visite.status,
OPV_SUJET = valeur.visite.sujet,
OPV_TITRE = valeur.visite.titre,
OPV_TYPE_VISITE = valeur.visite.type,
OPV_COLLAB_USERNAME = valeur.visite.initiateur,
OPV_NOM_CONTACT = valeur.visite.contact.nom,
OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone
};
var dateHoraire = new OP_DATE_HORAIRE
{
OPDH_DATE_DEBUT = valeur.visite.dateDebut,
OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee,
OPDH_DUREE = valeur.visite.duree,
OPDH_SITE = valeur.visite.site,
OP_VISITE = visite,
};
var index = 0;
Random rnd = new Random();
valeur.visiteurs.ForEach((payloadVisiteur) =>
{
OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR
{
// données globales
OPVVS_BADGE = valeur.badge,
OPVVS_OVERTIME = valeur.overtime,
OP_VISITE = visite,
OPVVS_PARKING = payloadVisiteur.parking,
OPVVS_PLAQUE_IMMATRICUL = payloadVisiteur.plaqueImmatriculation,
};
var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == payloadVisiteur.id);
if (visiteurExistant != null)
{
visiteCourrante.OP_VISITEUR = visiteurExistant;
}
else
{
visiteCourrante.OP_VISITEUR = new OP_VISITEUR
{
OPVS_EMAIL = payloadVisiteur.email,
OPVS_NOM = payloadVisiteur.nom,
OPVS_PRENOM = payloadVisiteur.prenom,
OPVS_TELEPHONE = payloadVisiteur.telephone,
};
}
string hash = UtilHelpers.GenSHA512($"{rnd.Next()}{visiteCourrante.OP_VISITEUR.OPVS_EMAIL}");
visiteCourrante.OPVVS_CLE_LIEN = hash;
valeur.visiteurs[index].hashKey = hash;
ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante);
index++;
});
ent.OP_DATE_HORAIRE.AddObject(dateHoraire);
ent.SaveChanges();
return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs };
}
/// <summary>
/// Modifier une visite
/// </summary>
/// <param name="id"></param>
/// <param name="valeur"></param>
/// <returns></returns>
///
public VisiteVisiteur ModifierVisite(int id, VisiteVisiteur valeur)
{
var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id);
if (visite == null)
{
throw new ExceptionDataConstraint("La visite n'existe pas");
}
visite.OPV_ARCHIVE = valeur.visite.archive;
visite.OPV_DESCRIPTION = valeur.visite.description;
visite.OPV_SITE = valeur.visite.site;
visite.OPV_STATUS = valeur.visite.status;
visite.OPV_SUJET = valeur.visite.sujet;
visite.OPV_TITRE = valeur.visite.titre;
visite.OPV_TYPE_VISITE = valeur.visite.type;
visite.OPV_COLLAB_USERNAME = valeur.visite.initiateur;
visite.OPV_NOM_CONTACT = valeur.visite.contact.nom;
visite.OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone;
var dateHoraire = ent.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID);
if (dateHoraire == null)
{
throw new ExceptionDataConstraint("La date de la visite n'existe pas");
}
dateHoraire.OPDH_DATE_DEBUT = valeur.visite.dateDebut;
dateHoraire.OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee;
dateHoraire.OPDH_DUREE = valeur.visite.duree;
ent.SaveChanges();
AddVisitorsToVisit(id, valeur.visiteurs);
return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs };
}
//AddVisitorsToVisit
public void AddVisitorsToVisit(int id, List<Visiteur> visiteurs)
{
var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id);
if (visite == null)
{
throw new ExceptionDataConstraint("La visite n'existe pas");
}
visite.OP_VISITE_VISITEUR.ToList().ForEach(v => ent.OP_VISITE_VISITEUR.DeleteObject(v));
visiteurs.ForEach((visiteur) =>
{
OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR
{
// données globales
OP_VISITE = visite,
OPVVS_PARKING = visiteurs[0].parking,
OPVVS_PLAQUE_IMMATRICUL = visiteurs[0].plaqueImmatriculation,
};
var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == visiteur.id);
if (visiteurExistant != null)
{
visiteCourrante.OP_VISITEUR = visiteurExistant;
}
else
{
visiteCourrante.OP_VISITEUR = new OP_VISITEUR
{
OPVS_EMAIL = visiteur.email,
OPVS_NOM = visiteur.nom,
OPVS_PRENOM = visiteur.prenom,
OPVS_TELEPHONE = visiteur.telephone,
};
}
ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante);
});
ent.SaveChanges();
}
/// <summary>
///
/// </summary>
/// <param name="nom"></param>
/// <param name="prenom"></param>
/// <param name="username"></param>
/// <param name="sortindex"></param>
/// <param name="sortdir"></param>
/// <param name="page"></param>
/// <param name="count"></param>
/// <returns></returns>
public ListePaginee<Visiteur> ListeVisiteur(string nom = null, string prenom = null, string username = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10)
{
var req = ent.OP_VISITEUR
.Join(ent.OP_VISITE_VISITEUR,
ov => ov.OPVS_ID,
ovv => ovv.OPVVS_OPVS_ID,
(ov, ovv) => new Visiteur
{
nom = ov.OPVS_NOM,
prenom = ov.OPVS_PRENOM,
email = ov.OPVS_EMAIL,
telephone = ov.OPVS_TELEPHONE,
id = ov.OPVS_ID
})
.Where(ov =>
(string.IsNullOrEmpty(nom) || ov.nom.StartsWith(nom)) &&
(string.IsNullOrEmpty(prenom) || ov.prenom.StartsWith(prenom)))
.Distinct()
.AsEnumerable();
#region système de pagination
int total = req.Count();
IEnumerable<Visiteur> elems = Enumerable.Empty<Visiteur>();
if (string.IsNullOrEmpty(sortindex))
{
elems = req;
}
else
{
var nomPropriete = typeof(Visiteur).GetProperty(sortindex, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase))
{
elems = req.OrderBy(x => nomPropriete.GetValue(x, null));
}
else
{
elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null));
}
}
var res = elems.Skip((page - 1) * count).Take(count);
#endregion
return new ListePaginee<Visiteur> { count = count, elements = res.ToList(), page = 0, total = total };
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="valeur"></param>
/// <returns></returns>
public VisiteVisiteur ModifierVisiteur(int id, VisiteVisiteur valeur)
{
var visiteur = ent.OP_VISITEUR.SingleOrDefault(v => v.OPVS_ID == id);
if (visiteur == null)
{
throw new ExceptionDataConstraint("Le visiteur n'existe pas");
}
visiteur.OPVS_NOM = valeur.visiteurs[0].nom;
visiteur.OPVS_PRENOM = valeur.visiteurs[0].prenom;
visiteur.OPVS_EMAIL = valeur.visiteurs[0].email;
visiteur.OPVS_TELEPHONE = valeur.visiteurs[0].telephone;
ent.SaveChanges();
return new VisiteVisiteur() { id = visiteur.OPVS_ID, visite = valeur.visite, visiteurs = valeur.visiteurs };
}
public VisiteVisiteur EnvoieReponseVisite(int visiteId, int visiteurId, VisiteReponse valeur)
{
var result = GetVisiteCourante(visiteId, visiteurId);
var visiteCourante = result.Item1;
if (visiteCourante.OPVVS_DONNEE_REPONSE == true)
{
throw new ExceptionDataConstraint("Le visiteur à déja repondu à la visite");
}
visiteCourante.OPVVS_DONNEE_REPONSE = true;
if ((bool)valeur.refus)
{
visiteCourante.OPVVS_REFUS = valeur.refus;
visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus;
}
visiteCourante.OPVVS_PLAQUE_IMMATRICUL = valeur.plaqueImmat;
visiteCourante.OPVVS_PARKING = valeur.parking;
var estCurrVisiteRefusee = estVisiteRefusee(result.Item2);
var estVisiteInitie = !estCurrVisiteRefusee && estVisiteInitiee(result.Item2);
if (estCurrVisiteRefusee)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE;
}
if (estVisiteInitie) // si tous les visiteurs ont repondu
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.CONFIRMATION_INITIATEUR;
}
ent.SaveChanges();
return new VisiteVisiteur();
}
public VisiteVisiteur EnvoieRefusVisiteur(int visiteId, int visiteurId, VisiteReponse valeur)
{
var result = GetVisiteCourante(visiteId, visiteurId);
var visiteCourante = result.Item1;
if (!visiteCourante.OPVVS_DONNEE_REPONSE)
{
throw new ExceptionDataConstraint("Le visiteur n'a pas encore donnée sa réponse");
}
if (valeur.refus.HasValue && valeur.refus.Value)
{
visiteCourante.OPVVS_REFUS = valeur.refus;
visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus;
}
visiteCourante.OPVVS_CONFIRMEE = true;
bool isVisitRefusee = estVisiteRefusee(result.Item2);
bool isVisitProgramme = !isVisitRefusee && estVisiteProgramme(result.Item2);
if (estVisiteRefusee(result.Item2))
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE;
}
if (isVisitProgramme) // si tous les visiteurs ont repondu
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE;
}
ent.SaveChanges();
return new VisiteVisiteur { };
}
public HttpResponseExtension SignalerPresenceVisiteur(int visiteId, int visiteurId)
{
var result = GetVisiteCourante(visiteId, visiteurId);
HttpResponseExtension reponse = new HttpResponseExtension();
var visiteCourante = result.Item1;
if (!visiteCourante.OPVVS_DONNEE_REPONSE ||
!visiteCourante.OPVVS_CONFIRMEE ||
(visiteCourante.OPVVS_REFUS.HasValue && visiteCourante.OPVVS_REFUS.Value))
{
throw new ExceptionDataConstraint("Erreur: L'Etat du visiteur n'est pas valide");
}
visiteCourante.OPVVS_PRESENT = true;
var estCurrVisiteEnCours = estVisiteEnCours(result.Item2);
if (estCurrVisiteEnCours)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.EN_COURS;
reponse.statusUpdated = true;
}
ent.SaveChanges();
reponse.message = "Le visiteur à été signalé comme entré";
return reponse;
}
public Tuple<OP_VISITE_VISITEUR, List<OP_VISITE_VISITEUR>> GetVisiteCourante(int visiteId, int visiteurId)
{
var visiteVisiteurs = ent.OP_VISITE_VISITEUR.Where(vvs => vvs.OP_VISITE.OPV_ID == visiteId).ToList();
var dataVisiteCourante = visiteVisiteurs.Where(visiteur => visiteur.OP_VISITEUR.OPVS_ID == visiteurId).SingleOrDefault();
if (dataVisiteCourante == null || dataVisiteCourante == null)
{
throw new ExceptionDataConstraint("Aucun visiteur ou aucune visite existante");
}
return Tuple.Create(dataVisiteCourante, visiteVisiteurs);
}
public bool estVisiteRefusee(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_REFUS == true).Count() == ovvs.Count();
}
public bool estVisiteProgramme(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_CONFIRMEE == true).Count() == ovvs.Count();
}
public bool estVisiteInitiee(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_DONNEE_REPONSE == true).Count() == ovvs.Count();
}
public bool estVisiteEnCours(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_PRESENT == true).Count() == ovvs.Count();
}
public bool ConfirmationVisiteur(int visiteId, int visiteurId)
{
var result = GetVisiteCourante(visiteId, visiteurId);
var visiteCourante = result.Item1;
visiteCourante.OPVVS_CONFIRMEE = true;
bool estCurrVisiteRefuse = estVisiteRefusee(result.Item2);
bool estCurrVisiteProgramme = estVisiteProgramme(result.Item2);
if (estCurrVisiteRefuse)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE;
}
if (estCurrVisiteProgramme)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE;
}
ent.SaveChanges();
return true;
}
public List<Visiteur> GetListeVisiteurFromVisite(int visiteId)
{
var visiteurQuery = ent.OP_VISITE
.Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh })
.Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID, (joined, ovv) => new { joined.ov, joined.odh, ovv })
.Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID, (joined, ovvs) => new { joined.ovv, ovvs })
.Where(joined => joined.ovv.OPVVS_OPV_ID == visiteId)
.Select(result => new
{
result.ovvs.OPVS_NOM,
result.ovvs.OPVS_PRENOM,
result.ovvs.OPVS_EMAIL,
result.ovvs.OPVS_TELEPHONE,
result.ovvs.OPVS_ID,
result.ovv.OPVVS_PLAQUE_IMMATRICUL,
result.ovv.OPVVS_PARKING,
result.ovv.OPVVS_DONNEE_REPONSE,
result.ovv.OPVVS_CONFIRMEE,
result.ovv.OPVVS_RAISON_REFUS,
result.ovv.OPVVS_REFUS,
result.ovv.OPVVS_PRESENT
});
var visiteurListe = visiteurQuery.ToList();
if (visiteurListe.Count == 0) throw new DataNotFoundException("Les données demandées n'existent pas");
List<Visiteur> listeVisiteur = new List<Visiteur>();
visiteurListe.ForEach((OP_VISITEUR) =>
{
listeVisiteur.Add(new Visiteur
{
nom = OP_VISITEUR.OPVS_NOM,
prenom = OP_VISITEUR.OPVS_PRENOM,
telephone = OP_VISITEUR.OPVS_TELEPHONE,
email = OP_VISITEUR.OPVS_EMAIL,
plaqueImmatriculation = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL,
id = OP_VISITEUR.OPVS_ID,
parking = OP_VISITEUR.OPVVS_PARKING,
donneeReponse = OP_VISITEUR.OPVVS_DONNEE_REPONSE,
confirmer = OP_VISITEUR.OPVVS_CONFIRMEE,
present = OP_VISITEUR.OPVVS_PRESENT,
reponse = new VisiteReponse
{
raisonRefus = OP_VISITEUR.OPVVS_RAISON_REFUS,
refus = OP_VISITEUR.OPVVS_REFUS,
plaqueImmat = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL
}
});
});
return listeVisiteur;
}
/// <summary>
/// Créer une date horaire
/// </summary>
/// <param name="valeur"></param>
/// <returns></returns>
public DateHoraire CreeHoraire(DateHoraire valeur)
{
return new DateHoraire() { };
}
/// <summary>
/// Création d'un visiteur
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Visiteur CreerVisiteur(Visiteur value)
{
return new Visiteur { };
}
public Visite ArchiveVisite(int id)
{
var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id);
if (visite == null)
{
return null;
}
visite.OPV_ARCHIVE = true;
ent.SaveChanges();
return new Visite { id = id };
}
}
}
|
311fe0e3a12b14c94376f2842f1afb87
|
{
"intermediate": 0.34747663140296936,
"beginner": 0.4042559266090393,
"expert": 0.24826745688915253
}
|
46,264
|
import json
import logging
import math
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
import torch
from torch import nn
from simple_parsing.helpers import Serializable
from mistral.rope import precompute_freqs_cis, apply_rotary_emb
from mistral.cache import CacheView, RotatingBufferCache
from mistral.moe import MoeArgs, MoeLayer
from xformers.ops.fmha import memory_efficient_attention
@dataclass
class ModelArgs(Serializable):
dim: int
n_layers: int
head_dim: int
hidden_dim: int
n_heads: int
n_kv_heads: int
norm_eps: float
vocab_size: int
max_batch_size: int = 0
# For rotary embeddings. If not set, will be infered from sliding window.
rope_theta: Optional[float] = None
# If this is set, use sliding window attention rotating cache.
sliding_window: Optional[int] = None
# If this is set, we will use MoE layers instead of dense layers.
moe: Optional[MoeArgs] = None
@dataclass
class SimpleInputMetadata:
# rope absolute positions
positions: torch.Tensor
@staticmethod
def from_seqlens(seqlens: List[int], device: torch.device) -> "SimpleInputMetadata":
return SimpleInputMetadata(
positions=torch.cat([torch.arange(0, seqlen) for seqlen in seqlens]).to(
device=device, dtype=torch.long
)
)
def repeat_kv(keys: torch.Tensor, values: torch.Tensor, repeats: int, dim: int):
keys = torch.repeat_interleave(keys, repeats=repeats, dim=dim)
values = torch.repeat_interleave(values, repeats=repeats, dim=dim)
return keys, values
class Attention(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.args = args
self.n_heads: int = args.n_heads
self.head_dim: int = args.head_dim
self.n_kv_heads: int = args.n_kv_heads
self.repeats = self.n_heads // self.n_kv_heads
self.scale = self.args.head_dim**-0.5
self.wq = nn.Linear(args.dim, args.n_heads * args.head_dim, bias=False)
self.wk = nn.Linear(args.dim, args.n_kv_heads * args.head_dim, bias=False)
self.wv = nn.Linear(args.dim, args.n_kv_heads * args.head_dim, bias=False)
self.wo = nn.Linear(args.n_heads * args.head_dim, args.dim, bias=False)
def forward(
self,
x: torch.Tensor,
freqs_cis: torch.Tensor,
cache: Optional[CacheView],
) -> torch.Tensor:
seqlen_sum, _ = x.shape
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
xq = xq.view(seqlen_sum, self.n_heads, self.head_dim)
xk = xk.view(seqlen_sum, self.n_kv_heads, self.head_dim)
xv = xv.view(seqlen_sum, self.n_kv_heads, self.head_dim)
xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
if cache is None:
key, val = xk, xv
elif cache.prefill:
key, val = cache.interleave_kv(xk, xv)
cache.update(xk, xv)
else:
cache.update(xk, xv)
key, val = cache.key, cache.value
key = key.view(
seqlen_sum * cache.sliding_window, self.n_kv_heads, self.head_dim
)
val = val.view(
seqlen_sum * cache.sliding_window, self.n_kv_heads, self.head_dim
)
# Repeat keys and values to match number of query heads
key, val = repeat_kv(key, val, self.repeats, dim=1)
# xformers requires (B=1, S, H, D)
xq, key, val = xq[None, ...], key[None, ...], val[None, ...]
output = memory_efficient_attention(
xq, key, val, None if cache is None else cache.mask
)
return self.wo(output.view(seqlen_sum, self.n_heads * self.head_dim))
class FeedForward(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.w1 = nn.Linear(args.dim, args.hidden_dim, bias=False)
self.w2 = nn.Linear(args.hidden_dim, args.dim, bias=False)
self.w3 = nn.Linear(args.dim, args.hidden_dim, bias=False)
def forward(self, x) -> torch.Tensor:
return self.w2(nn.functional.silu(self.w1(x)) * self.w3(x))
class RMSNorm(torch.nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float()).type_as(x)
return output * self.weight
class TransformerBlock(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.n_heads = args.n_heads
self.dim = args.dim
self.attention = Attention(args)
self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
self.args = args
self.feed_forward: nn.Module
if args.moe is not None:
self.feed_forward = MoeLayer(
experts=[FeedForward(args=args) for _ in range(args.moe.num_experts)],
gate=nn.Linear(args.dim, args.moe.num_experts, bias=False),
moe_args=args.moe,
)
else:
self.feed_forward = FeedForward(args=args)
def forward(
self, x: torch.Tensor, freqs_cis: torch.Tensor, cache: Optional[CacheView]
) -> torch.Tensor:
r = self.attention.forward(self.attention_norm(x), freqs_cis, cache)
h = x + r
r = self.feed_forward.forward(self.ffn_norm(h))
out = h + r
return out
class Transformer(nn.Module):
def __init__(
self,
args: ModelArgs,
pipeline_rank: int = 0,
num_pipeline_ranks: int = 1,
):
super().__init__()
self.args = args
self.vocab_size = args.vocab_size
self.n_layers = args.n_layers
self._precomputed_freqs_cis: Optional[torch.Tensor] = None
assert self.vocab_size > 0
assert pipeline_rank < num_pipeline_ranks, (pipeline_rank, num_pipeline_ranks)
self.pipeline_rank = pipeline_rank
self.num_pipeline_ranks = num_pipeline_ranks
# Modules specific to some ranks:
self.tok_embeddings: Optional[nn.Embedding] = None
self.norm: Optional[RMSNorm] = None
self.output: Optional[nn.Linear] = None
if pipeline_rank == 0:
self.tok_embeddings = nn.Embedding(args.vocab_size, args.dim)
if pipeline_rank == num_pipeline_ranks - 1:
self.norm = RMSNorm(args.dim, eps=args.norm_eps)
self.output = nn.Linear(args.dim, args.vocab_size, bias=False)
# Initialize all layers but slice off those not of this rank.
layers = [TransformerBlock(args=args) for _ in range(args.n_layers)]
num_layers_per_rank = math.ceil(self.n_layers / self.num_pipeline_ranks)
offset = self.pipeline_rank * num_layers_per_rank
end = min(self.n_layers, offset + num_layers_per_rank)
self.layers = nn.ModuleDict({str(i): layers[i] for i in range(offset, end)})
self.n_local_layers = len(self.layers)
@property
def dtype(self) -> torch.dtype:
return next(self.parameters()).dtype
@property
def device(self) -> torch.device:
return next(self.parameters()).device
@property
def freqs_cis(self) -> torch.Tensor:
# We cache freqs_cis but need to take care that it is on the right device
# and has the right dtype (complex64). The fact that the dtype is different
# from the module's dtype means we cannot register it as a buffer
if self._precomputed_freqs_cis is None:
# If no sliding window, assume a larger seqlen
theta = self.args.rope_theta
if theta is None:
theta = 1000000.0 if self.args.sliding_window is None else 10000.0
# theta = 10000.
self._precomputed_freqs_cis = precompute_freqs_cis(
self.args.head_dim, 128_000, theta
)
if self._precomputed_freqs_cis.device != self.device:
self._precomputed_freqs_cis = self._precomputed_freqs_cis.to(
device=self.device
)
return self._precomputed_freqs_cis
def forward_partial(
self,
input_ids: torch.Tensor,
seqlens: List[int],
cache: Optional[RotatingBufferCache] = None,
) -> torch.Tensor:
"""Local forward pass.
If doing pipeline parallelism, this will return the activations of the last layer of this stage.
For the last stage, this will return the normalized final embeddings.
"""
assert (
len(seqlens) <= self.args.max_batch_size
), f"Max batch size is {self.args.max_batch_size}, got batch size of {len(seqlens)}"
(num_toks,) = input_ids.shape
assert sum(seqlens) == num_toks, (sum(seqlens), num_toks)
if cache is not None:
input_metadata = cache.get_input_metadata(seqlens)
else:
input_metadata = SimpleInputMetadata.from_seqlens(seqlens, self.device)
if self.pipeline_rank == 0:
assert self.tok_embeddings is not None
h = self.tok_embeddings(input_ids)
else:
h = torch.empty(
num_toks, self.args.dim, device=self.device, dtype=self.dtype
)
torch.distributed.recv(h, src=self.pipeline_rank - 1)
freqs_cis = self.freqs_cis[input_metadata.positions]
for local_layer_id, layer in enumerate(self.layers.values()):
if cache is not None:
assert input_metadata is not None
cache_view = cache.get_view(local_layer_id, input_metadata)
else:
cache_view = None
h = layer(h, freqs_cis, cache_view)
if cache is not None:
cache.update_seqlens(seqlens)
if self.pipeline_rank < self.num_pipeline_ranks - 1:
torch.distributed.send(h, dst=self.pipeline_rank + 1)
return h
else:
# Last rank has a final normalization step.
assert self.norm is not None
return self.norm(h)
def forward(
self,
input_ids: torch.Tensor,
seqlens: List[int],
cache: Optional[RotatingBufferCache] = None,
) -> torch.Tensor:
h = self.forward_partial(input_ids, seqlens, cache=cache)
if self.pipeline_rank < self.num_pipeline_ranks - 1:
# ignore the intermediate activations as we'll get the final output from
# the last stage
outs = torch.empty(
h.shape[0], self.vocab_size, device=h.device, dtype=h.dtype
)
else:
assert self.output is not None
outs = self.output(h)
if self.num_pipeline_ranks > 1:
torch.distributed.broadcast(outs, src=self.num_pipeline_ranks - 1)
return outs.float()
def load_state_dict(self, state_dict, *args, **kwargs):
state_to_load = {}
skipped = set([])
for k, v in state_dict.items():
if k.startswith("tok_embeddings"):
if self.pipeline_rank == 0:
state_to_load[k] = v
else:
logging.debug(
"Skipping parameter %s at pipeline rank %d",
k,
self.pipeline_rank,
)
skipped.add(k)
elif k.startswith("norm") or k.startswith("output"):
if self.pipeline_rank == self.num_pipeline_ranks - 1:
state_to_load[k] = v
else:
logging.debug(
"Skipping parameter %s at pipeline rank %d",
k,
self.pipeline_rank,
)
skipped.add(k)
elif k.startswith("layers"):
layer_id = k.split(".")[1]
if layer_id in self.layers:
state_to_load[k] = v
else:
logging.debug(
"Skipping parameter %s at pipeline rank %d",
k,
self.pipeline_rank,
)
skipped.add(k)
else:
raise ValueError(f"Unexpected key {k}")
assert set(state_dict.keys()) == skipped.union(set(state_to_load.keys()))
super().load_state_dict(state_to_load, *args, **kwargs)
@staticmethod
def from_folder(
folder: Path,
max_batch_size: int = 1,
num_pipeline_ranks: int = 1,
device="cuda",
dtype=torch.float16,
) -> "Transformer":
with open(folder / "params.json", "r") as f:
model_args = ModelArgs.from_dict(json.load(f))
model_args.max_batch_size = max_batch_size
if num_pipeline_ranks > 1:
pipeline_rank = torch.distributed.get_rank()
else:
pipeline_rank = 0
with torch.device("meta"):
model = Transformer(
model_args,
pipeline_rank=pipeline_rank,
num_pipeline_ranks=num_pipeline_ranks,
)
loaded = torch.load(str(folder / "consolidated.00.pth"), mmap=True)
model.load_state_dict(loaded, assign=True)
return model.to(device=device, dtype=dtype)
|
483fe387917f323efe5b9e133e69624c
|
{
"intermediate": 0.2868121564388275,
"beginner": 0.533229649066925,
"expert": 0.17995810508728027
}
|
46,265
|
Dictionary<Key, string> dictionary = new Dictionary<Key, string>();
Key firstKey = new Key(1);
dictionary.Add(firstKey, "First");
Key secondKey = new Key(2);
dictionary.Add(secondKey, "Second");
Console.WriteLine(dictionary[firstKey]);
public class Key
{
public int Marker { get; }
public Key(int marker) => Marker = marker;
public override int GetHashCode() => Marker / 10;
public override bool Equals(object? other) =>
other is Key ? other.GetHashCode() == GetHashCode() : base.Equals(other);
}
в чем ошибка
|
354bfdb258b930d1a0a2c4e74ae0c919
|
{
"intermediate": 0.3824116587638855,
"beginner": 0.42213869094848633,
"expert": 0.19544963538646698
}
|
46,266
|
First
Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: Key
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at Program.<Main>$(String[] args) in C:\Users\zoro8\RiderProjects\ConsoleApp5\ConsoleApp5\Program.cs:line 7
Dictionary<Key, string> dictionary = new Dictionary<Key, string>();
Key firstKey = new Key(1);
dictionary.Add(firstKey, "First");
Key secondKey = new Key(2);
dictionary.Add(secondKey, "Second");
Console.WriteLine(dictionary[firstKey]);
public class Key
{
public int Marker { get; }
public Key(int marker) => Marker = marker;
public override int GetHashCode() => Marker / 10;
public override bool Equals(object? other) =>
other is Key ? other.GetHashCode() == GetHashCode() : base.Equals(other);
}
В ЧЕМ ОШИБКА
|
81a2755644f1b39f2eff9c591561691f
|
{
"intermediate": 0.33537837862968445,
"beginner": 0.41434356570243835,
"expert": 0.2502779960632324
}
|
46,267
|
JS script that displays your IP once ran
|
92fa5f7a8f1198953dae8ce67892fc74
|
{
"intermediate": 0.41114363074302673,
"beginner": 0.2932271659374237,
"expert": 0.2956292927265167
}
|
46,268
|
Write a homework problem that asks for the student to now enable the website to face the website on secure port 443 with SSL certificates for a secure connection
|
a7eb28485ce448a6255f307d9d63ff4d
|
{
"intermediate": 0.40043771266937256,
"beginner": 0.20810161530971527,
"expert": 0.3914605975151062
}
|
46,269
|
("multiplayer_find_bot_troop_and_group_for_spawn",
[
(store_script_param, ":team_no", 1),
(store_script_param, ":look_only_actives", 2),
(call_script, "script_multiplayer_find_player_leader_for_bot", ":team_no", ":look_only_actives"),
(assign, ":leader_player", reg0),
(assign, ":available_troops_in_faction", 0),
(assign, ":available_troops_to_spawn", 0),
(team_get_faction, ":team_faction_no", ":team_no"),
# (display_message, "@Find units...", 0xFFFFFFFF),
(try_for_range, ":troop_no", multiplayer_ai_troops_begin, multiplayer_ai_troops_end),
(store_troop_faction, ":troop_faction", ":troop_no"),
(eq, ":troop_faction", ":team_faction_no"),
(store_add, ":wanted_slot", slot_player_bot_type_1_wanted, ":available_troops_in_faction"),
(val_add, ":available_troops_in_faction", 1),
(try_begin),
(this_or_next|lt, ":leader_player", 0),
(player_slot_ge, ":leader_player", ":wanted_slot", 1),
(val_add, ":available_troops_to_spawn", 1),
(try_end),
(try_end),
(assign, ":available_troops_in_faction", 0),
(store_random_in_range, ":random_troop_index", 0, ":available_troops_to_spawn"),
(assign, ":end_cond", multiplayer_ai_troops_end),
(try_for_range, ":troop_no", multiplayer_ai_troops_begin, ":end_cond"),
(store_troop_faction, ":troop_faction", ":troop_no"),
(eq, ":troop_faction", ":team_faction_no"),
(store_add, ":wanted_slot", slot_player_bot_type_1_wanted, ":available_troops_in_faction"),
(val_add, ":available_troops_in_faction", 1),
(this_or_next|lt, ":leader_player", 0),
(player_slot_ge, ":leader_player", ":wanted_slot", 1),
(val_sub, ":random_troop_index", 1),
(lt, ":random_troop_index", 0),
(assign, ":end_cond", 0),
(assign, ":selected_troop", ":troop_no"),
(try_end),
(assign, reg0, ":selected_troop"),
(assign, reg1, ":leader_player"),
]),
That's warband module system script
The script is called in a loop to match the number of bots
I want to return custom list of bots to :selected_troop
That is, I have a list of each bot's ID sequence, instead of randomizing, I want to return a specific bot to a specific team
|
d81126efa156ae1358a57a6af782e99d
|
{
"intermediate": 0.29493600130081177,
"beginner": 0.44687044620513916,
"expert": 0.2581935226917267
}
|
46,270
|
can you give me a gtest for the functiion float area(const struct contour* contour) {
int p, q;
int n = contour->count - 1;
float A = 0.f;
for (p=n-1, q=0; q < n; p=q++) {
A += contour->p[p].x * contour->p[q].y - contour->p[q].x * contour->p[p].y;
}
return A * .5f;
}
|
de07b4405a68ec64be97666e87a7e37d
|
{
"intermediate": 0.37550538778305054,
"beginner": 0.35757574439048767,
"expert": 0.2669188380241394
}
|
46,271
|
i have two excel files in a folder , one with extension .xlsx and another with extension .xslm , both are opend , we need to copy all data from file .xslx to .xslm and save .xslm file in same folder with name of .xlsx file
|
3d284e5fcbf628a3b96bc76a9abf8d45
|
{
"intermediate": 0.3633919656276703,
"beginner": 0.31848078966140747,
"expert": 0.31812727451324463
}
|
46,272
|
a bash function that passes an array to another bash function
|
bd85953c4cf11448b78aa4a727a9a40d
|
{
"intermediate": 0.3038536310195923,
"beginner": 0.4731180667877197,
"expert": 0.22302822768688202
}
|
46,273
|
a bash function that passes an array to another bash function
|
12c842bd331a92a310b3779233e59875
|
{
"intermediate": 0.3038536310195923,
"beginner": 0.4731180667877197,
"expert": 0.22302822768688202
}
|
46,274
|
write a bash function that passes an array to another bash function
|
f3e3c04e720f15d45f8d2a2f4e567b29
|
{
"intermediate": 0.34092411398887634,
"beginner": 0.43596982955932617,
"expert": 0.22310611605644226
}
|
46,275
|
how to fix 403 error of xampp for apache access
|
eed10d927648d5f5e6af05be789d59b5
|
{
"intermediate": 0.6193925142288208,
"beginner": 0.12031295895576477,
"expert": 0.2602945566177368
}
|
46,276
|
explain tower of hanoi iteration approach using rust lang
|
c36c50fea49ad92757ff95ac08e234c3
|
{
"intermediate": 0.2947347164154053,
"beginner": 0.24163779616355896,
"expert": 0.46362751722335815
}
|
46,277
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Objects;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Net;
using System.Reflection;
using ServicesApiOcaPeek.Data;
using ServicesApiOcaPeek.ExceptionPersonnalisees;
using ServicesApiOcaPeek.Extensions;
using ServicesApiOcaPeek.Models;
namespace ServicesApiOcaPeek.Helpers
{
/// <summary>
/// Gestion de l'accès à la couche de données
/// </summary>
public class ServicesApiOcaPeekDataHelper : IDisposable
{
OCAPEEKEntities ent;
public virtual void Dispose()
{
ent.Dispose();
ent = null;
}
/// <summary>
///
/// </summary>
public ServicesApiOcaPeekDataHelper()
{
try
{
ent = new OCAPEEKEntities();
}
catch (Exception exc)
{
Utils.ElmahLogException(exc);
throw exc;
}
}
#region Check connection base
/// <summary>
/// Permet de test si la base de données est disponible
/// </summary>
/// <returns></returns>
internal bool CheckConnectionBase()
{
return ent.DatabaseExists();
}
internal bool CheckAccessTable()
{
return ent.OP_VISITE.Any();
}
#endregion
public PAR_GEN_SERV GetParcGenServDansBdd(string environnement)
{
return ent.PAR_GEN_SERV.Where(w => w.PGS_ENV.Equals(environnement, StringComparison.OrdinalIgnoreCase))
.SingleOrDefault();
}
/// <summary>
/// recuperer les visites
/// </summary>
/// <param name="site">site</param>
/// <param name="username">nom d'utilisateur</param>
/// <param name="startDate">date de debut</param>
/// <param name="endDate">date de fin</param>
/// <param name="sortindex">nom propiete </param>
/// <param name="sortdir">sans de l'ordre (exemple : 'ASC' pour croissant)</param>
/// <param name="page">numéro de page</param>
/// <param name="count">nombre element dans une page</param>
/// <param name="archive"></param>
/// <returns></returns>
public ListePaginee<Visite> ListeVisites(string site = null, string username = null, DateTime? startDate = null,
DateTime? endDate = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10,
bool archive = false)
{
var req = ent.OP_VISITE
.Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh })
.Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID,
(joined, ovv) => new { joined.ov, joined.odh, ovv })
.Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID,
(joined, ovvs) => new { joined.ov, joined.odh, joined.ovv, ovvs })
.Where(joined => (string.IsNullOrEmpty(site) || joined.ov.OPV_SITE.StartsWith(site)) &&
(string.IsNullOrEmpty(username) ||
joined.ov.OPV_COLLAB_USERNAME.StartsWith(username)) &&
(startDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) >=
EntityFunctions.TruncateTime(startDate)) &&
(endDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) <=
EntityFunctions.TruncateTime(endDate)) &&
(joined.ov.OPV_ARCHIVE == archive))
.Select(result => new Visite
{
id = result.ov.OPV_ID,
archive = result.ov.OPV_ARCHIVE,
description = result.ov.OPV_DESCRIPTION,
site = result.ov.OPV_SITE,
status = result.ov.OPV_STATUS,
sujet = result.ov.OPV_SUJET,
titre = result.ov.OPV_TITRE,
type = result.ov.OPV_TYPE_VISITE,
dateDebut = result.odh.OPDH_DATE_DEBUT,
dateFin = result.odh.OPDH_DATE_FIN,
duree = result.odh.OPDH_DUREE,
heureArrivee = result.odh.OPDH_HEURE_ARRIVEE,
heureDepart = result.odh.OPDH_HEURE_DEPART,
badge = result.ovv.OPVVS_BADGE,
overtime = result.ovv.OPVVS_OVERTIME,
plaqueImmatriculation = result.ovv.OPVVS_PLAQUE_IMMATRICUL,
parking = result.ovv.OPVVS_PARKING,
nomCollaborateur = result.ov.OPV_COLLAB_USERNAME,
contact = new VisiteContact
{
nom = result.ov.OPV_NOM_CONTACT,
telephone = result.ov.OPV_TELEPHONE_CONTACT
}
}).OrderBy(x => EntityFunctions.DiffDays(x.dateDebut, DateTime.Now)).AsEnumerable();
req = req.Distinct();
var visiteListe = req.ToList();
List<Visite> listeVisite = new List<Visite>();
#region système de pagination
int total = req.Count();
IEnumerable<Visite> elems = Enumerable.Empty<Visite>();
if (string.IsNullOrEmpty(sortindex))
{
elems = req.AsEnumerable();
}
else
{
var nomPropriete = typeof(Visite).GetProperty(sortindex,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase))
{
elems = req.OrderBy(x => nomPropriete.GetValue(x, null));
}
else
{
elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null));
}
}
var res = elems.Skip((page - 1) * count).Take(count);
#endregion
return new ListePaginee<Visite> { count = count, elements = res.ToList(), page = page, total = total };
}
public Visite GetVisite(int visiteId)
{
var listeVisiteur = GetListeVisiteurFromVisite(visiteId);
var req = (from ov in ent.OP_VISITE
join odh in ent.OP_DATE_HORAIRE on ov.OPV_ID equals odh.OPDH_OPV_ID
join ovv in ent.OP_VISITE_VISITEUR on ov.OPV_ID equals ovv.OPVVS_OPV_ID
join ovvs in ent.OP_VISITEUR on ovv.OPVVS_OPVS_ID equals ovvs.OPVS_ID
where
(
ov.OPV_ID.Equals(visiteId)
)
select new Visite
{
archive = ov.OPV_ARCHIVE,
badge = ovv.OPVVS_BADGE,
dateDebut = odh.OPDH_DATE_DEBUT,
dateFin = odh.OPDH_DATE_FIN,
overtime = ovv.OPVVS_OVERTIME,
titre = ov.OPV_TITRE,
description = ov.OPV_DESCRIPTION,
site = ov.OPV_SITE,
type = ov.OPV_TYPE_VISITE,
status = ov.OPV_STATUS,
id = ov.OPV_ID,
duree = odh.OPDH_DUREE,
heureArrivee = odh.OPDH_HEURE_ARRIVEE,
heureDepart = odh.OPDH_HEURE_DEPART,
nomCollaborateur = ov.OPV_COLLAB_USERNAME,
reponse = new VisiteReponse
{
refus = (bool)ovv.OPVVS_REFUS ? ovv.OPVVS_REFUS : false,
raisonRefus = ovv.OPVVS_RAISON_REFUS
},
contact = new VisiteContact
{
nom = ov.OPV_NOM_CONTACT,
telephone = ov.OPV_TELEPHONE_CONTACT
}
}).AsEnumerable();
if (listeVisiteur.Count == 0)
{
throw new Exception("Aucun visiteur pour cette visite");
}
var visiteWithVisiteurs = req.ToArray();
var visiteToReturn = req.FirstOrDefault();
visiteToReturn.reponse = null;
for (var i = 0; i < visiteWithVisiteurs.Length; i++)
{
var visiteur = listeVisiteur.ElementAt(i);
var visite = visiteWithVisiteurs.ElementAt(i);
visiteur.reponse = visite.reponse;
}
if (visiteToReturn != null)
{
visiteToReturn.visiteurs = listeVisiteur;
}
//return visiteWithVisiteurs;
return visiteToReturn;
}
public VisiteCourante GetVisiteByKey(string key)
{
var vvs = ent.OP_VISITE_VISITEUR.SingleOrDefault(v => v.OPVVS_CLE_LIEN == key);
if (vvs == null)
{
throw new ExceptionNotFoundApi("Clé invalide");
}
var visiteur = vvs.OP_VISITEUR;
var visite = vvs.OP_VISITE;
var odh = visite.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID);
if (odh == null || vvs == null)
{
throw new ExceptionNotFoundApi("Erreur: Cette visite n'existe pas");
}
return new VisiteCourante
{
archive = vvs.OP_VISITE.OPV_ARCHIVE,
collabUsername = visite.OPV_COLLAB_USERNAME,
confirmee = vvs.OPVVS_CONFIRMEE,
overtime = vvs.OPVVS_OVERTIME,
badge = vvs.OPVVS_BADGE,
parking = vvs.OPVVS_PARKING,
dateDebut = odh.OPDH_DATE_DEBUT,
heureDebut = odh.OPDH_HEURE_ARRIVEE,
heureDebutPrev = odh.OPDH_HEURE_DEBUT_PREV,
dateDebutPrev = odh.OPDH_DATE_DEBUT_PREV,
dateFinPrev = odh.OPDH_DATE_FIN_PREV,
heureFinPrev = odh.OPDH_HEURE_FIN_PREV,
description = visite.OPV_DESCRIPTION,
donneeReponse = vvs.OPVVS_DONNEE_REPONSE,
horaireId = odh.OPDH_ID,
idVvs = vvs.OPVVS_ID,
idVisite = visite.OPV_ID,
idVisiteur = visiteur.OPVS_ID,
email = visiteur.OPVS_EMAIL,
nom = visiteur.OPVS_NOM,
prenom = visiteur.OPVS_PRENOM,
telephone = visiteur.OPVS_TELEPHONE,
site = visite.OPV_SITE,
status = visite.OPV_STATUS,
titre = visite.OPV_TITRE,
typeVisite = visite.OPV_TYPE_VISITE,
duree = odh.OPDH_DUREE.HasValue ? odh.OPDH_DUREE.Value : 0,
};
}
/// <summary>
/// Crée une visite
/// </summary>
/// <param name="valeur"></param>
/// <returns>Identifiant de la visite crée</returns>
public VisiteVisiteur CreerVisite(VisiteVisiteur valeur)
{
if (valeur.visiteurs.Count <= 0)
{
throw new Exception("Au moins un visiteur est requis");
}
var visite = new OP_VISITE
{
OPV_ARCHIVE = false,
OPV_DESCRIPTION = valeur.visite.description,
OPV_SITE = valeur.visite.site,
OPV_STATUS = valeur.visite.status,
OPV_SUJET = valeur.visite.sujet,
OPV_TITRE = valeur.visite.titre,
OPV_TYPE_VISITE = valeur.visite.type,
OPV_COLLAB_USERNAME = valeur.visite.initiateur,
OPV_NOM_CONTACT = valeur.visite.contact.nom,
OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone
};
var dateHoraire = new OP_DATE_HORAIRE
{
OPDH_DATE_DEBUT = valeur.visite.dateDebut,
OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee,
OPDH_DUREE = valeur.visite.duree,
OPDH_SITE = valeur.visite.site,
OP_VISITE = visite,
};
var index = 0;
Random rnd = new Random();
valeur.visiteurs.ForEach((payloadVisiteur) =>
{
OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR
{
// données globales
OPVVS_BADGE = valeur.badge,
OPVVS_OVERTIME = valeur.overtime,
OP_VISITE = visite,
OPVVS_PARKING = payloadVisiteur.parking,
OPVVS_PLAQUE_IMMATRICUL = payloadVisiteur.plaqueImmatriculation,
};
var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == payloadVisiteur.id);
if (visiteurExistant != null)
{
visiteCourrante.OP_VISITEUR = visiteurExistant;
}
else
{
visiteCourrante.OP_VISITEUR = new OP_VISITEUR
{
OPVS_EMAIL = payloadVisiteur.email,
OPVS_NOM = payloadVisiteur.nom,
OPVS_PRENOM = payloadVisiteur.prenom,
OPVS_TELEPHONE = payloadVisiteur.telephone,
};
}
string hash = UtilHelpers.GenSHA512($"{rnd.Next()}{visiteCourrante.OP_VISITEUR.OPVS_EMAIL}");
visiteCourrante.OPVVS_CLE_LIEN = hash;
valeur.visiteurs[index].hashKey = hash;
ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante);
index++;
});
ent.OP_DATE_HORAIRE.AddObject(dateHoraire);
ent.SaveChanges();
return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs };
}
/// <summary>
/// Modifier une visite
/// </summary>
/// <param name="id"></param>
/// <param name="valeur"></param>
/// <returns></returns>
///
public VisiteVisiteur ModifierVisite(int id, VisiteVisiteur valeur)
{
var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id);
if (visite == null)
{
throw new ExceptionDataConstraint("La visite n'existe pas");
}
visite.OPV_ARCHIVE = valeur.visite.archive;
visite.OPV_DESCRIPTION = valeur.visite.description;
visite.OPV_SITE = valeur.visite.site;
visite.OPV_STATUS = valeur.visite.status;
visite.OPV_SUJET = valeur.visite.sujet;
visite.OPV_TITRE = valeur.visite.titre;
visite.OPV_TYPE_VISITE = valeur.visite.type;
visite.OPV_COLLAB_USERNAME = valeur.visite.initiateur;
visite.OPV_NOM_CONTACT = valeur.visite.contact.nom;
visite.OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone;
var dateHoraire = ent.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID);
if (dateHoraire == null)
{
throw new ExceptionDataConstraint("La date de la visite n'existe pas");
}
dateHoraire.OPDH_DATE_DEBUT = valeur.visite.dateDebut;
dateHoraire.OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee;
dateHoraire.OPDH_DUREE = valeur.visite.duree;
ent.SaveChanges();
return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs };
}
//Add Visitors To Visit
public VisiteVisiteur AddVisitorsToVisit(int idVisite, VisiteVisiteur visiteurs)
{
var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == idVisite);
if (visite == null)
{
throw new ExceptionDataConstraint("La visite n'existe pas");
}
var dateHoraire = ent.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID);
if (dateHoraire == null)
{
throw new ExceptionDataConstraint("La date de la visite n'existe pas");
}
var index = 0;
visiteurs.visiteurs.ForEach((payloadVisiteur) =>
{
OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR
{
// données globales
OPVVS_BADGE = visiteurs.badge,
OPVVS_OVERTIME = visiteurs.overtime,
OP_VISITE = visite,
OPVVS_PARKING = payloadVisiteur.parking,
OPVVS_PLAQUE_IMMATRICUL = payloadVisiteur.plaqueImmatriculation,
};
var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == payloadVisiteur.id);
if (visiteurExistant != null)
{
visiteCourrante.OP_VISITEUR = visiteurExistant;
}
else
{
visiteCourrante.OP_VISITEUR = new OP_VISITEUR
{
OPVS_EMAIL = payloadVisiteur.email,
OPVS_NOM = payloadVisiteur.nom,
OPVS_PRENOM = payloadVisiteur.prenom,
OPVS_TELEPHONE = payloadVisiteur.telephone,
};
}
ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante);
index++;
});
ent.SaveChanges();
return new VisiteVisiteur() { id = visite.OPV_ID, visite = visiteurs.visite, visiteurs = visiteurs.visiteurs };
}
/// <summary>
///
/// </summary>
/// <param name="nom"></param>
/// <param name="prenom"></param>
/// <param name="username"></param>
/// <param name="sortindex"></param>
/// <param name="sortdir"></param>
/// <param name="page"></param>
/// <param name="count"></param>
/// <returns></returns>
public ListePaginee<Visiteur> ListeVisiteur(string nom = null, string prenom = null, string username = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10)
{
var req = ent.OP_VISITEUR
.Join(ent.OP_VISITE_VISITEUR,
ov => ov.OPVS_ID,
ovv => ovv.OPVVS_OPVS_ID,
(ov, ovv) => new Visiteur
{
nom = ov.OPVS_NOM,
prenom = ov.OPVS_PRENOM,
email = ov.OPVS_EMAIL,
telephone = ov.OPVS_TELEPHONE,
id = ov.OPVS_ID
})
.Where(ov =>
(string.IsNullOrEmpty(nom) || ov.nom.StartsWith(nom)) &&
(string.IsNullOrEmpty(prenom) || ov.prenom.StartsWith(prenom)))
.Distinct()
.AsEnumerable();
#region système de pagination
int total = req.Count();
IEnumerable<Visiteur> elems = Enumerable.Empty<Visiteur>();
if (string.IsNullOrEmpty(sortindex))
{
elems = req;
}
else
{
var nomPropriete = typeof(Visiteur).GetProperty(sortindex, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase))
{
elems = req.OrderBy(x => nomPropriete.GetValue(x, null));
}
else
{
elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null));
}
}
var res = elems.Skip((page - 1) * count).Take(count);
#endregion
return new ListePaginee<Visiteur> { count = count, elements = res.ToList(), page = 0, total = total };
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="valeur"></param>
/// <returns></returns>
public VisiteVisiteur ModifierVisiteur(int id, VisiteVisiteur valeur)
{
var visiteur = ent.OP_VISITEUR.SingleOrDefault(v => v.OPVS_ID == id);
if (visiteur == null)
{
throw new ExceptionDataConstraint("Le visiteur n'existe pas");
}
visiteur.OPVS_NOM = valeur.visiteurs[0].nom;
visiteur.OPVS_PRENOM = valeur.visiteurs[0].prenom;
visiteur.OPVS_EMAIL = valeur.visiteurs[0].email;
visiteur.OPVS_TELEPHONE = valeur.visiteurs[0].telephone;
ent.SaveChanges();
return new VisiteVisiteur() { id = visiteur.OPVS_ID, visite = valeur.visite, visiteurs = valeur.visiteurs };
}
public VisiteVisiteur EnvoieReponseVisite(int visiteId, int visiteurId, VisiteReponse valeur)
{
var result = GetVisiteCourante(visiteId, visiteurId);
var visiteCourante = result.Item1;
if (visiteCourante.OPVVS_DONNEE_REPONSE == true)
{
throw new ExceptionDataConstraint("Le visiteur à déja repondu à la visite");
}
visiteCourante.OPVVS_DONNEE_REPONSE = true;
if ((bool)valeur.refus)
{
visiteCourante.OPVVS_REFUS = valeur.refus;
visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus;
}
visiteCourante.OPVVS_PLAQUE_IMMATRICUL = valeur.plaqueImmat;
visiteCourante.OPVVS_PARKING = valeur.parking;
var estCurrVisiteRefusee = estVisiteRefusee(result.Item2);
var estVisiteInitie = !estCurrVisiteRefusee && estVisiteInitiee(result.Item2);
if (estCurrVisiteRefusee)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE;
}
if (estVisiteInitie) // si tous les visiteurs ont repondu
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.CONFIRMATION_INITIATEUR;
}
ent.SaveChanges();
return new VisiteVisiteur();
}
public VisiteVisiteur EnvoieRefusVisiteur(int visiteId, int visiteurId, VisiteReponse valeur)
{
var result = GetVisiteCourante(visiteId, visiteurId);
var visiteCourante = result.Item1;
if (!visiteCourante.OPVVS_DONNEE_REPONSE)
{
throw new ExceptionDataConstraint("Le visiteur n'a pas encore donnée sa réponse");
}
if (valeur.refus.HasValue && valeur.refus.Value)
{
visiteCourante.OPVVS_REFUS = valeur.refus;
visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus;
}
visiteCourante.OPVVS_CONFIRMEE = true;
bool isVisitRefusee = estVisiteRefusee(result.Item2);
bool isVisitProgramme = !isVisitRefusee && estVisiteProgramme(result.Item2);
if (estVisiteRefusee(result.Item2))
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE;
}
if (isVisitProgramme) // si tous les visiteurs ont repondu
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE;
}
ent.SaveChanges();
return new VisiteVisiteur { };
}
public HttpResponseExtension SignalerPresenceVisiteur(int visiteId, int visiteurId)
{
var result = GetVisiteCourante(visiteId, visiteurId);
HttpResponseExtension reponse = new HttpResponseExtension();
var visiteCourante = result.Item1;
if (!visiteCourante.OPVVS_DONNEE_REPONSE ||
!visiteCourante.OPVVS_CONFIRMEE ||
(visiteCourante.OPVVS_REFUS.HasValue && visiteCourante.OPVVS_REFUS.Value))
{
throw new ExceptionDataConstraint("Erreur: L'Etat du visiteur n'est pas valide");
}
visiteCourante.OPVVS_PRESENT = true;
var estCurrVisiteEnCours = estVisiteEnCours(result.Item2);
if (estCurrVisiteEnCours)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.EN_COURS;
reponse.statusUpdated = true;
}
ent.SaveChanges();
reponse.message = "Le visiteur à été signalé comme entré";
return reponse;
}
public Tuple<OP_VISITE_VISITEUR, List<OP_VISITE_VISITEUR>> GetVisiteCourante(int visiteId, int visiteurId)
{
var visiteVisiteurs = ent.OP_VISITE_VISITEUR.Where(vvs => vvs.OP_VISITE.OPV_ID == visiteId).ToList();
var dataVisiteCourante = visiteVisiteurs.Where(visiteur => visiteur.OP_VISITEUR.OPVS_ID == visiteurId).SingleOrDefault();
if (dataVisiteCourante == null || dataVisiteCourante == null)
{
throw new ExceptionDataConstraint("Aucun visiteur ou aucune visite existante");
}
return Tuple.Create(dataVisiteCourante, visiteVisiteurs);
}
public bool estVisiteRefusee(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_REFUS == true).Count() == ovvs.Count();
}
public bool estVisiteProgramme(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_CONFIRMEE == true).Count() == ovvs.Count();
}
public bool estVisiteInitiee(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_DONNEE_REPONSE == true).Count() == ovvs.Count();
}
public bool estVisiteEnCours(List<OP_VISITE_VISITEUR> ovvs)
{
return ovvs.Where(v => v.OPVVS_PRESENT == true).Count() == ovvs.Count();
}
public bool ConfirmationVisiteur(int visiteId, int visiteurId)
{
var result = GetVisiteCourante(visiteId, visiteurId);
var visiteCourante = result.Item1;
visiteCourante.OPVVS_CONFIRMEE = true;
bool estCurrVisiteRefuse = estVisiteRefusee(result.Item2);
bool estCurrVisiteProgramme = estVisiteProgramme(result.Item2);
if (estCurrVisiteRefuse)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE;
}
if (estCurrVisiteProgramme)
{
visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE;
}
ent.SaveChanges();
return true;
}
public List<Visiteur> GetListeVisiteurFromVisite(int visiteId)
{
var visiteurQuery = ent.OP_VISITE
.Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh })
.Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID, (joined, ovv) => new { joined.ov, joined.odh, ovv })
.Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID, (joined, ovvs) => new { joined.ovv, ovvs })
.Where(joined => joined.ovv.OPVVS_OPV_ID == visiteId)
.Select(result => new
{
result.ovvs.OPVS_NOM,
result.ovvs.OPVS_PRENOM,
result.ovvs.OPVS_EMAIL,
result.ovvs.OPVS_TELEPHONE,
result.ovvs.OPVS_ID,
result.ovv.OPVVS_PLAQUE_IMMATRICUL,
result.ovv.OPVVS_PARKING,
result.ovv.OPVVS_DONNEE_REPONSE,
result.ovv.OPVVS_CONFIRMEE,
result.ovv.OPVVS_RAISON_REFUS,
result.ovv.OPVVS_REFUS,
result.ovv.OPVVS_PRESENT
});
var visiteurListe = visiteurQuery.ToList();
if (visiteurListe.Count == 0) throw new DataNotFoundException("Les données demandées n'existent pas");
List<Visiteur> listeVisiteur = new List<Visiteur>();
visiteurListe.ForEach((OP_VISITEUR) =>
{
listeVisiteur.Add(new Visiteur
{
nom = OP_VISITEUR.OPVS_NOM,
prenom = OP_VISITEUR.OPVS_PRENOM,
telephone = OP_VISITEUR.OPVS_TELEPHONE,
email = OP_VISITEUR.OPVS_EMAIL,
plaqueImmatriculation = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL,
id = OP_VISITEUR.OPVS_ID,
parking = OP_VISITEUR.OPVVS_PARKING,
donneeReponse = OP_VISITEUR.OPVVS_DONNEE_REPONSE,
confirmer = OP_VISITEUR.OPVVS_CONFIRMEE,
present = OP_VISITEUR.OPVVS_PRESENT,
reponse = new VisiteReponse
{
raisonRefus = OP_VISITEUR.OPVVS_RAISON_REFUS,
refus = OP_VISITEUR.OPVVS_REFUS,
plaqueImmat = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL
}
});
});
return listeVisiteur;
}
/// <summary>
/// Créer une date horaire
/// </summary>
/// <param name="valeur"></param>
/// <returns></returns>
public DateHoraire CreeHoraire(DateHoraire valeur)
{
return new DateHoraire() { };
}
/// <summary>
/// Création d'un visiteur
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Visiteur CreerVisiteur(Visiteur value)
{
return new Visiteur { };
}
public Visite ArchiveVisite(int id)
{
var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id);
if (visite == null)
{
return null;
}
visite.OPV_ARCHIVE = true;
ent.SaveChanges();
return new Visite { id = id };
}
}
}
|
2d6555fb5e5e824980b61da664e087cb
|
{
"intermediate": 0.34747663140296936,
"beginner": 0.4042559266090393,
"expert": 0.24826745688915253
}
|
46,278
|
I did some tweeking to the default KDE plasma desktop and added a top status bar like macos and moved the system tray up there. However, now my battery status indicator isnt showing up. How do I fix it?
|
b83b172fe08d702a0234f553542fd262
|
{
"intermediate": 0.41281723976135254,
"beginner": 0.37336915731430054,
"expert": 0.21381361782550812
}
|
46,279
|
what is arm dynarec?
|
df8061b36b484d6b0f9add25aec8a35e
|
{
"intermediate": 0.3458457887172699,
"beginner": 0.1643836498260498,
"expert": 0.4897705614566803
}
|
46,280
|
I want to write a python script that reads from and writes to a csv file. The script must output text into every row of specific column by means of a loop and sacve the file every time it is run. What is the simplest way to achieve this?
|
b2738886f4d2def5dfa77fc6f7365f0a
|
{
"intermediate": 0.33743470907211304,
"beginner": 0.37991276383399963,
"expert": 0.28265252709388733
}
|
46,281
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему? я предпологаю что это из-за перезаписи изображений, можешь предоставить код который это исправит
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
var localPageNumber = pageNumber; // Локальная переменная для каждой итерации цикла
var pageTask = Task.Run(() =>
{
// Использование localPageNumber вместо pageNumber
CallExternalProcess(pdfConverterPath, file + PathImage + localPageNumber.ToString());
return dataApplicationPath + PathImageFull; // Возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
public void CallExternalProcess(string processPath, string arguments)
{
var myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = processPath;
myProcess.StartInfo.Arguments = arguments;
myProcess.EnableRaisingEvents = true;
try
{
myProcess.Start();
}
catch (InvalidOperationException ex)
{
UnityEngine.Debug.LogError(ex);
}
myProcess.WaitForExit();
var ExitCode = myProcess.ExitCode;
}
|
302750ceabbf264955041ca78e88bbf5
|
{
"intermediate": 0.44535815715789795,
"beginner": 0.40057969093322754,
"expert": 0.1540621668100357
}
|
46,282
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему? я предпологаю что это из-за перезаписи изображений, можешь предоставить код который это исправит
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
var localPageNumber = pageNumber; // Локальная переменная для каждой итерации цикла
var pageTask = Task.Run(() =>
{
// Использование localPageNumber вместо pageNumber
CallExternalProcess(pdfConverterPath, file + PathImage + localPageNumber.ToString());
return dataApplicationPath + PathImageFull; // Возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
}
|
8b045b9234c79d27a41f6e68cd49f233
|
{
"intermediate": 0.4318719208240509,
"beginner": 0.3214372992515564,
"expert": 0.2466907948255539
}
|
46,283
|
привет у меня есть скрипт который я делал чтобы pdf прочитать и получить в витде картинок и без много поточсности все хорошо работает но когда я добавил многопоток то получил что в книге везде 1 и таже страница почему? я предпологаю что это из-за перезаписи изображений, можешь предоставить код который это исправит
private async Task ProcessPdfFileAsync(string file)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
var button = Instantiate(_buttonPrefab, _contentButton);
button.Initialized(fileNameWithoutExtension, file);
var pageCount = 0;
using (PdfReader reader = new PdfReader(file))
{
pageCount = reader.NumberOfPages;
}
var imageGroup = new Image[pageCount];
var tasks = new List<Task<string>>();
for (int pageNumber = 0; pageNumber < pageCount; pageNumber++)
{
var localPageNumber = pageNumber; // Локальная переменная для каждой итерации цикла
var pageTask = Task.Run(() =>
{
// Использование localPageNumber вместо pageNumber
CallExternalProcess(pdfConverterPath, file + PathImage + localPageNumber.ToString());
return dataApplicationPath + PathImageFull; // Возврат пути
});
tasks.Add(pageTask);
}
var imagePaths = await Task.WhenAll(tasks); // Дожидаемся выполнения всех задач и получаем пути к изображениям
UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
for (int i = 0; i < imagePaths.Length; i++)
{
imageGroup[i] = ApplyTextureToUI(imagePaths[i]); // Теперь это выполняется в главном потоке
}
allImageGroups.Add(imageGroup);
button.Button.onClick.AddListener(() => AllImagesOn(imageGroup));
buttonToImagesMapping[button.Button] = imageGroup;
});
}
}
public void CallExternalProcess(string processPath, string arguments)
{
var myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = processPath;
myProcess.StartInfo.Arguments = arguments;
myProcess.EnableRaisingEvents = true;
try
{
myProcess.Start();
}
catch (InvalidOperationException ex)
{
UnityEngine.Debug.LogError(ex);
}
myProcess.WaitForExit();
var ExitCode = myProcess.ExitCode;
}
|
a4970bf2b94d27acfcdde69de6bc4aa3
|
{
"intermediate": 0.3928266167640686,
"beginner": 0.42408856749534607,
"expert": 0.18308480083942413
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.