instruction stringlengths 0 30k ⌀ |
|---|
I have 2 worksheets. The first one is for the working file and the second is for the master file sheet. The master file sheet has 3 columns which are as follows Fund Number, Name, Portfolio Number. In the working file sheet, specifically in column 2, it has the values in the Fund Number Column of the master file sheet. What I would like to do is to perform vlook up function in the working file sheet column 2, that will get the corresponding values in Portfolio Number Column in the master file sheet and autofill it till the last row. Is vlookup function appropriate for this matter?
Any help will be highly appreciated.
Sub VLOOKUP_Formula_1()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Working File")
Dim lr As Integer
lr = sh.Range("B" & Application.Rows.Count).End(xlUp).Row
sh.Range("B2").Value = "=VLOOKUP(B2,Database!A:C,3,0)"
sh.Range("B2" & lr).FillDown
sh.Range("B2" & lr).Copy
sh.Range("B2" & lr).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End Sub |
|excel|vba| |
I decided to use this method, but, as people in the comments said, iterations also works.
Author of this answer is: @eccs0103 (Cant find him on the SO EN sadly)
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const object = {
["_reactFiber$dsadadasda"]: 0,
["__reactProps$dsadadasda"]: 1,
["reactSomethingElse$dsadadasda"]: 2,
};
function detectReactProps(dictionary) {
const regex = /^\w*reactProps\$\w+$/;
for (const property in dictionary) {
if (regex.test(property)) return property;
}
}
const keyReactProps = detectReactProps(object);
console.log(object[keyReactProps]); // read
object[keyReactProps] = 5; // write
<!-- end snippet -->
|
/**
* Get the top dialog of the stack when there are nested dialogs
* @returns
*/
function getTopDialog()
{
/* Get open dialogs on page, by definition they should be nested because
you should only open a child dialog if a dialog is already open, no
siblings or cousins */
const dialogs = document.querySelectorAll("dialog[open]");
if(dialogs == null || dialogs.length == 0)
{
return null;
}
// Create return field
let topDialog = null;
// Loop over open dialogs
dialogs.forEach(dialog => {
const childDialog = dialog.querySelector("dialog[open]");
if(childDialog == null)
{
topDialog = dialog;
}
});
return topDialog;
} |
Here is example code using .map with simplified data:
import pandas as pd
df = pd.DataFrame({'x1': [65, 66, 67],
'x2': [68, 69, 70],
'x3': [71, 72, 73],
'y': [10, 11, 12]
})
x_list = ['x1', 'x2', 'x3']
df[x_list] = df[x_list].map(lambda x: chr(x))
print(df)
gives
x1 x2 x3 y
0 A D G 10
1 B E H 11
2 C F I 12 |
This problem happens when 'Player' goes in and out of sightRadius of 'Enemy' multiple times.
here is the bug code
```
bool FoundPlayer()
{
int numColliders = Physics.OverlapSphereNonAlloc(transform.position, sightRadius, colliders);
Debug.Log(numColliders);
for (int i = 0; i < numColliders; i++)
{
var target = colliders[i];
if (target.CompareTag("Player"))
{
attackTarget = target.gameObject;
return true;
}
}
attackTarget = null;
return false;
}
```
And here is the setting of Player, with both collider, rigidbody, layer and tag.
[enter image description here][1]
When Player is in the sightRadius of enemy, I get log: '3'; the enemy chase my player
[enter image description here](https://i.stack.imgur.com/qWPgA.png)
When Player is out of the sightRadius of enemy, I get log: '2';
[enter image description here](https://i.stack.imgur.com/uzR9l.png)
After I control the Player to go in and out of sightRadius several times.
[enter image description here](https://i.stack.imgur.com/cf3KG.png)
I get log '2' . And my enemy will not chase my Player anymore. But if I replay in the editor, Physics.OverlapSphere work well again.
This problem happens both in unity 2020 and 2022.
My code used OverlapSphereNonAlloc but I met the same problem, trying both OverlapSphereNonAlloc and OverlapSphere.
Here is the full code of enemy
```
using UnityEngine;
using UnityEngine.AI;
enum EnemyStatus
{
GURAD,
PATROL,
CHASE, DEAD
}
[RequireComponent(typeof(NavMeshAgent))]
[RequireComponent(typeof(BoxCollider))]
public class EnemyController : MonoBehaviour
{
private EnemyStatus enemyStates;
private NavMeshAgent agent;
private Animator animator;
[Header("Basic Settings")]
public float sightRadius;
private GameObject attackTarget;
// enermy will find 10 max players at one frame
const int maxColliders = 10;
private Collider[] colliders = new Collider[maxColliders];
// speed set in agent.speed, but patrol, chase and return from chase have different speed
private float speed;
// is GUARD or PATROL when no enemy
public bool isGuard;
[Header("Patrol State")]
public float patrolRange;
private Vector3 wayPoint;
private Vector3 centerPosition;
// animator
bool isWalk;
// entry of Chase Layer
bool isChase;
//
bool isFollow;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
speed = agent.speed;
wayPoint = centerPosition = transform.position;
}
private void Start()
{
if (isGuard)
{
enemyStates = EnemyStatus.GURAD;
}
else
{
enemyStates = EnemyStatus.PATROL;
}
}
private void Update()
{
SwitchStates();
SwitchAnimation();
}
void SwitchAnimation()
{
animator.SetBool("Walk", isWalk);
animator.SetBool("ChaseState", isChase);
animator.SetBool("Follow", isFollow);
}
private void SwitchStates()
{
if (FoundPlayer())
{
enemyStates = EnemyStatus.CHASE;
}
switch(enemyStates)
{
case EnemyStatus.GURAD:
break;
case EnemyStatus.PATROL:
// this is error, when enemy reach wayPoint, it will stop walking
// isWalk = true;
isChase = false;
isFollow = false;
if (Vector3.Distance(transform.position, wayPoint) <= agent.stoppingDistance )
{
wayPoint = GetNewWayPoint();
agent.destination = wayPoint;
agent.speed = speed * 0.5f;
isWalk = false;
}
else
{
isWalk = true;
}
break;
case EnemyStatus.CHASE:
//TODO: back to gurad or patrol if player far away
//TODO: attack player
//TODO: attack animator
isWalk = false;
isChase = true;
if (FoundPlayer())
{
//TODO: chase player
agent.destination = attackTarget.transform.position;
agent.speed = speed;
isFollow = true;
}
else
{
isFollow = false;
// stop at the current when lost target
agent.destination = transform.position;
}
break;
case EnemyStatus.DEAD:
break;
}
}
bool FoundPlayer()
{
int numColliders = Physics.OverlapSphereNonAlloc(transform.position, sightRadius, colliders);
Debug.Log(numColliders);
for (int i = 0; i < numColliders; i++)
{
var target = colliders[i];
if (target.CompareTag("Player"))
{
attackTarget = target.gameObject;
return true;
}
}
attackTarget = null;
return false;
}
Vector3 GetNewWayPoint ()
{
Vector3 wayPoint = new Vector3(centerPosition.x + Random.Range(-patrolRange, patrolRange), centerPosition.y, centerPosition.z + Random.Range(-patrolRange, patrolRange));
NavMeshHit hit;
// sample the nearnet reachable point for enemy to go.
// if can not find any point, SamplePosition will retturn false and enemy will stand there for next sample next frame.
wayPoint = NavMesh.SamplePosition(wayPoint, out hit, patrolRange, 1) ? hit.position : transform.position;
return wayPoint;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, sightRadius);
Vector3 size = new Vector3(patrolRange, patrolRange, patrolRange);
Gizmos.DrawWireCube(centerPosition, size);
}
}
```
I try different API and different version of unity
[1]: https://i.stack.imgur.com/NpPbh.png |
"""hello.
this code is runing,
versions:
Python==3.11.1
opencv-contrib-python==4.9.0.80
opencv-python==4.9.0.80
in this case we have this aruco of 7x7 "DICT_7X7_100" but you can change to "DICT_5X5_100", you must to change in 3 lines of this program"""
import numpy as np
import cv2
import sys
import time
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DICT_4X4_250": cv2.aruco.DICT_4X4_250,
"DICT_4X4_1000": cv2.aruco.DICT_4X4_1000,
"DICT_5X5_50": cv2.aruco.DICT_5X5_50,
"DICT_5X5_100": cv2.aruco.DICT_5X5_100,
"DICT_5X5_250": cv2.aruco.DICT_5X5_250,
"DICT_5X5_1000": cv2.aruco.DICT_5X5_1000,
"DICT_6X6_50": cv2.aruco.DICT_6X6_50,
"DICT_6X6_100": cv2.aruco.DICT_6X6_100,
"DICT_6X6_250": cv2.aruco.DICT_6X6_250,
"DICT_6X6_1000": cv2.aruco.DICT_6X6_1000,
"DICT_7X7_50": cv2.aruco.DICT_7X7_50,
"DICT_7X7_100": cv2.aruco.DICT_7X7_100,
"DICT_7X7_250": cv2.aruco.DICT_7X7_250,
"DICT_7X7_1000": cv2.aruco.DICT_7X7_1000,
"DICT_ARUCO_ORIGINAL": cv2.aruco.DICT_ARUCO_ORIGINAL,
"DICT_APRILTAG_16h5": cv2.aruco.DICT_APRILTAG_16h5,
"DICT_APRILTAG_25h9": cv2.aruco.DICT_APRILTAG_25h9,
"DICT_APRILTAG_36h10": cv2.aruco.DICT_APRILTAG_36h10,
"DICT_APRILTAG_36h11": cv2.aruco.DICT_APRILTAG_36h11
}
def aruco_display(corners, ids, rejected, image):
if len(corners) > 0:
ids = ids.flatten()
for (markerCorner, markerID) in zip(corners, ids):
corners = markerCorner.reshape((4, 2))
(topLeft, topRight, bottomRight, bottomLeft) = corners
topRight = (int(topRight[0]), int(topRight[1]))
bottomRight = (int(bottomRight[0]), int(bottomRight[1]))
bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))
topLeft = (int(topLeft[0]), int(topLeft[1]))
cv2.line(image, topLeft, topRight, (0, 255, 0), 2)
cv2.line(image, topRight, bottomRight, (0, 255, 0), 2)
cv2.line(image, bottomRight, bottomLeft, (0, 255, 0), 2)
cv2.line(image, bottomLeft, topLeft, (0, 255, 0), 2)
cX = int((topLeft[0] + bottomRight[0]) / 2.0)
cY = int((topLeft[1] + bottomRight[1]) / 2.0)
cv2.circle(image, (cX, cY), 4, (0, 0, 255), -1)
cv2.putText(image, str(markerID),(topLeft[0], topLeft[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 255, 0), 2)
print("[Inference] ArUco marker ID: {}".format(markerID))
return image
def pose_estimation(frame, aruco_dict_type, matrix_coefficients, distortion_coefficients):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_7X7_100) # cv2.aruco.DICT_4X4_250 seleccion del modelo Aruco
parameters = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(dictionary, parameters)
corners, ids, rejected_img_points = detector.detectMarkers(gray)
if len(corners) > 0:
for i in range(0, len(ids)):
rvec, tvec, markerPoints = cv2.aruco.estimatePoseSingleMarkers(corners[i], 0.02, matrix_coefficients, distortion_coefficients)
cv2.aruco.drawDetectedMarkers(frame, corners)
cv2.drawFrameAxes(frame, matrix_coefficients, distortion_coefficients, rvec, tvec, 0.01)
return frame
aruco_type = "DICT_7X7_100"
arucoDict = cv2.aruco.DICT_7X7_100
arucoParams = cv2.aruco.DetectorParameters()
intrinsic_camera = np.array(((933.15867, 0, 657.59),(0,933.1586, 400.36993),(0,0,1)))
distortion = np.array((-0.43948,0.18514,0,0))
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
while cap.isOpened():
ret, img = cap.read()
output = pose_estimation(img, ARUCO_DICT[aruco_type], intrinsic_camera, distortion)
cv2.imshow('Estimated Pose', output)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|
I installed Posgresql 16 server on a Debian 11 host that I access through SSH, and all works as expected when I use PSQL cli.
Then I installed and configured PGAdmin4 Web, and I configured NGINX with reverse proxy so I can access to PGAdmin4 web interface from a browser.
The firewall is correctly configured.
The NGINX directives are as follow:
```
location /pgadmin4/ {
proxy_pass http://127.0.0.1:80/pgadmin4/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Script-Name /pgadmin4;
proxy_buffering off;
}
```
I can access to PGAdmin4 web interface through an URL:
https://<mydomain_name>/pgadmin4/
The problem is that I am unable to connect to the Postgresql server through the Server Dialog, I systematically get an error message:
Unable to connect to server: connection timeout expired.
In file /usr/pgadmin4/web/config.py, I replaced DEFAULT_SERVER = '127.0.0.1' by DEFAULT_SERVER = '0.0.0.0'.
In file /etc/postgresql/16/main/pg_hba.conf, I added the below line:
```
host all all 0.0.0.0/0 md5
```
host all all 0.0.0.0/0 md5
In the PGAdmin4 Dialog box I configured the following options (let's assume that the host name is example.tld):
Connection tab:
- Host name/address: example.tld
- Maintenance database: postgres
- Username: postgres
SSH Tunnel tab:
- Tunnel host: example.tld
- Tunnel port: 22
- Username: pgadmin (regular Unix user)
- Authentication: Password
I also created a new database (bookstore) with that I can access directly under user 'pgadmin' from a shell with the below command, and modified the connection tab accordingly:
psql -U pgadmin -d bookstore -h 127.0.0.1 -p 5432 -W
I read countless documentation online but still no luck.
I am stuck and any help would be appreciated.
I tried the configuration with different databases and users in the Connection tab where I have no issue with PSQL.
When I try to use the port 5432, I immediately get an error message, see below:
[Cannot use port 5432 because behind a reverse proxy on port 80](https://i.stack.imgur.com/5mK9M.png)
In the SSH Tunnel tab, when I use a non-existent user (e.g. test) or a wrong password, I have a different error message:[Error when a wrong user or wrong password is used](https://i.stack.imgur.com/JfOui.png) |
PGAdmin4 configured behind a reverse proxy but unable to connect to Postgresql server |
|postgresql|reverse-proxy|pgadmin| |
null |
Best regard every one and hope to be your time good, I could solve the issue was have by my self, the issue was I didnt installed full needed files for it(I hope my solve assist any one want to begaine on this program).
Hope you have a good time.
Mohammad HAJJAR.
|
If you're writing something that does "the same thing, with just one thing changing at each step", that's a loop. You don't use separate `if` statements. Not even "when you're lazy": being lazy is an _excellent_ property to have when you're a programmer, because it means you want to do as little work as possible. Of course, in this case that means "why am I even doing this, [`npm install marked`](https://www.npmjs.com/package/marked), oh look I'm done", but even if you insist on implementing a markdown parser yourself (because sometimes you just want to write code to see if you can do it) you don't use a sequence of `if` statements because it takes more time to write, and will takes more time to fix or update (as you discovered).
Lazy is excellent. Sloppy is your worst enemy.
However, even if you _do_ use `if` statements, resolve them either such that you handle "the largest thing first", to ensure there's no fall-through, _or_ with if-else statements, so there's no fall-though. (And based on your question about whether to use a switch: why stop there? Why not just use a mapping object with `#` sequences as keys instead so the lookup runs in O(1)?)
However, you don't need any of this, because what you're really doing is simple text matching, so you can use the best tool in the toolset for that: you can trivially get both the `#` sequence and "remaining text" with a dead simple regex, and then generate the replacement HTML [using the captured data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#replacement):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function markdownToHTML(doc) {
return convertMultiLineMD(doc.split(`\n`)).join(`\n`);
}
function convertMultiLineMD(lines) {
// convert tables, lists, etc, while also making sure
// to perform inline markup conversion for any content
// that doesn't span multiple lines. For the purpose of
// this answer, we're going to ignore multi-line entirely:
return convertInlineMD(lines);
}
function convertInlineMD(lines) {
return lines.map((line) => {
// convert headings
line = line.replace(
// two capture groups, one for the markup, and one for the heading,
// with a third optional group so we don't capture EOL whitespace.
/^(#+)\s+(.+?)(\s+)?$/,
// and we extract the first group's length immediately
(_, { length: h }, text) => `<h${h}>${text}</h${h}>`
);
// then wrap bare text in <p>, convert bold, italic, etc. etc.
return line;
});
}
// And a simple test based on what you indicated:
const docs = [`## he#llo\nthere\n# yooo `, `# he#llo\nthere\n## yooo`];
docs.forEach((doc, i) => console.log(`[doc ${i + 1}]\n`, markdownToHTML(doc)));
<!-- end snippet -->
However, this is also a naive approach to writing a transpiler, and will have dismal runtime performance compared to writing a DFA based on the markdown grammar (the "markup language specification" grammar, i.e. the rules that say which tokens can follow which other tokens), where you run through your document by tracking what kind of token we're dealing with, and convert on the fly as we pass token terminations.
(This is, in fact, how regular expressions work: they generate a DFA from the [regular grammar](https://en.wikipedia.org/wiki/Regular_grammar) pattern you specify, then run the input through that DFA, achieving near-perfect runtime performance)
That's wildly beyond the scope of this answer, but worth digging into if you're doing this just to see if you can do it: anyone can write code "that works" but is extremely inefficient, so that's not an exercise that's going to improve your skill as a programmer. |
How do I print a JTable in the form: Image + header + table in a single page (Java Swing) |
|java|swing|printing|jtable| |
null |
In a Python project that uses pyproject.toml (and setuptools), I want to have a custom version number provider. I want it to work like `setuptools_scm`, but use my own logic to determine the version (and preferably other fields such as description and author). I know it can be accomplished by using dynamic metadata, but I would like it to work just by including the module in `[build-system]`. How do I do that? How does `setuptools` knows where to get the metadata from? |
Custom dynamic version provider for Python projects |
|python|setuptools|build-system|pyproject.toml| |
{"Voters":[{"Id":5389997,"DisplayName":"Shadow"},{"Id":839601,"DisplayName":"gnat"},{"Id":2670892,"DisplayName":"greg-449"}]} |
I just converted my existing project to a maven project. I have added dependencies like selenium-java, selenium-serve, selenium-chrome-driver, testing, and JUnit.
It is a TestNG project that contains many packages and classes. It gives me an error as below:
```
Exception in thread "main" java.lang.AbstractMethodError: Receiver class org.openqa.selenium.chrome.ChromeDriverService$Builder does not define or inherit an implementation of the resolved method 'abstract void loadSystemProperties()' of abstract class org.openqa.selenium.remote.service.DriverService$Builder.
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:504)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:162)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:52)
```
Dependencies I have added;
```xml
<dependencies>
<!--
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.9.0</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver-->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>4.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>
org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>
junit</groupId>
<artifactId>junit</artifactId>
<version>4.6</version>
<scope>test</scope>
</dependency>
<!--
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-support -->
<dependency>
<groupId>
org.seleniumhq.selenium</groupId>
<artifactId>selenium-support</artifactId>
<version>
4.10.0</version>
</dependency>
<!--
https://mvnrepository.com/artifact/ru.stqa.selenium/webdriver-expected-conditions -->
<dependency>
<groupId>ru.stqa.selenium</groupId>
<artifactId>
webdriver-expected-conditions</artifactId>
<version>1.0.41</version>
</dependency>
</dependencies>
```
Also I have added this line in my cod,
```java
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver = new ChromeDriver();
```
Can anyone help me how to solve this error. What should I do? |
Can you programmatically generate a link to open a Word document and navigate to a particular location within it (preferably a comment)? |
|c#|sharepoint|ms-word|office365|office-js| |
I have created a new project at Intellji Idea Ultimate with version 2024.1. This version supports the new Java 22 (openjdk-22) version. But when i reload my Gradle Project, than it shows this error:
```´
Unsupported Gradle JVM.
Your build is currently configured to use Java 22 and Gradle 8.7.
Possible solutions:
- Use Java 21 as Gradle JVM: Open Gradle settings
- Upgrade to Gradle 8.5 and re-sync
```
AND THIS:
```
FAILURE: Build failed with an exception.
* What went wrong:
BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 66
> Unsupported class file major version 66
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
CONFIGURE FAILED in 69ms
```
At the "project structure" i have selected the installed java 22 SDK. Also all Modules are of the SDK Default Language Level.
That is my gradle properties:
```
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```
and this my build.kts:
```
plugins {
id("java")
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_22
targetCompatibility = JavaVersion.VERSION_22
}
dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
}
tasks.test {
useJUnitPlatform()
}
``` |
Gradle doesn't found installed JDK 22 at Intellji |
|java|windows|gradle|intellij-idea|build| |
null |
I’m trying to send string of 13 ascii characters from js to php session using ajax, but up on receving string is not the same as i send it, using json.stringyfy and jsondecode does nothing.
```
console.log(plik_T[click])
jQuery.ajax({
type: "POST",
url: './Setyb.php',
dataType: 'text',
data: {send: plik_T[click]},
success: function (obj) {
console.log(obj)
}
});
```
```
<?php
var_dump($_POST['send']);
?>
```
[console output][1]
i tried using json.stringify or changing meta UTF-8 to older versions non of this resolved my problem. Then i tried checking type of variables witch both were string, so that lead my to nothing. what i'm trying to accomplish is to set my Session variable up on user click and use it in next php page
[1]: https://i.stack.imgur.com/evOMn.png |
Here is a response I found from Google: [Google's Response][1]
Pasting text here for convenience and incase it gets "disabled" LOL!
*"If an account is closed because of inactivity then I am afraid there is no way to recover it. A number of warnings are sent to the account owner before the account is closed.
The dormant account policy does allows you to open a new account: https://support.google.com/googleplay/android-developer/answer/9899234 but you will need to use a different account/email address."*
[1]: https://support.google.com/googleplay/android-developer/thread/208102688/my-developer-account-was-closed-due-to-inactivity-but-we-have-an-active-app-how-do-i-get-access?hl=en |
null |
We have a NoSQL Database in Azure Cosmos DB. We also have a Synapse connector to use this database with PowerBi.
This allows us to use a simple SQL script to fetch the data in PowerBi. Something like:
SELECT logs.Field1, logs.Field2 from logs
The data is mostly structured, but we recently added a new field (say Field3) to the new documents in cosmos.
But now, if we run this:
SELECT logs.Field1, logs.Field2, logs.Field3 from logs
We get an error saying that the column name is invalid.
How should we fetch this field using the SQL script in Power Bi? We want a NULL value when the document does not contain this new field.
In cosmos, we have the IS_DEFINED function built-in the SQL language, and we can use it to query unstructured data using SQL. But this does not work in the PowerBi query editor (I believe it is a Synapse problem). The error reads: IS_DEFINED is not a built in function. |
I have the attached image below of tables I have created in MySQL Workbench. The tables shows a one-to-one connection between a donor and its contact.
[![enter image description here][1]][1]
My challenge is that anytime I create the relationship, it creates another column as seen circled red in the image. This does not allow me to insert data into the contact table and it gives me an error of an unknown column in the execution of my insert syntax.
I want to know why I do have that column created and also is there a way I can work around it to allow me inset data to the table without any errors cos i have read that they are indexes and are thus good for speedy searches throughout the tables created. Or better still can i hide it and insert data with no errors thrown at me?
Thanks
[1]: https://i.stack.imgur.com/Y9krp.jpg |
Creating Relationship Creates Additional Columns in MySQL Workbench |
|mysql-workbench|relational-database| |
I came across a workaround that was suggested in an unofficial capacity by someone at AppDynamics during their local lab explorations. While this solution isn't officially supported by AppDynamics, it has proven to be effective for adjusting the log levels for both the Proxy and the Watchdog components within my AppDynamics setup. I'd like to share the steps involved, but please proceed with caution and understand that this is not a sanctioned solution. Here's a summary of the steps:
- **Proxy Log Level:** The `log4j2.xml` file controls this. You can find it within the appdynamics_bindeps module. For example, in my WSL setup, it's located at `/home/wsl/.pyenv/versions/3.11.6/lib/python3.11/site-packages/appdynamics_bindeps/proxy/conf/logging/log4j2.xml`. In the Docker image python:3.9, the path is `/usr/local/lib/python3.9/site-packages/appdynamics_bindeps/proxy/conf/logging/log4j2.xml`. Modify the <AsyncLogger> level within the <Loggers> section to one of the following: debug, info, warn, error, or fatal.
- **Watch Dog Log Level:** This can be adjusted in the `proxy.py` file found within the appdynamics Python module. For example, in my WSL setup, it's located at `/home/wsl/.pyenv/versions/3.11.6/lib/python3.11/site-packages/appdynamics/scripts/pyagent/commands/proxy.py`. In the Docker image python:3.9, the path is `/usr/local/lib/python3.9/site-packages/appdynamics/scripts/pyagent/commands/proxy.py`. You will need to hardcode the log level in the configure_proxy_logger and configure_watchdog_logger functions by changing the level variable.
## My versions
```bash
$ pip freeze | grep appdynamics
appdynamics==24.2.0.6567
appdynamics-bindeps-linux-x64==24.2.0
appdynamics-proxysupport-linux-x64==11.68.3
```
## Original files
### log4j2.xml
```
<Loggers>
<!-- Modify each <AsyncLogger> level as needed -->
<AsyncLogger name="com.singularity" level="info" additivity="false">
<AppenderRef ref="Default"/>
<AppenderRef ref="RESTAppender"/>
<AppenderRef ref="Console"/>
</AsyncLogger>
</Loggers>
```
### proxy.py
```python
def configure_proxy_logger(debug):
logger = logging.getLogger('appdynamics.proxy')
level = logging.DEBUG if debug else logging.INFO
pass
def configure_watchdog_logger(debug):
logger = logging.getLogger('appdynamics.proxy')
level = logging.DEBUG if debug else logging.INFO
pass
```
## My Script to create environment variables to log4j2.xml and proxy.py
### update_appdynamics_log_level.sh
```bash
#!/bin/sh
# Check if PYENV_ROOT is not set
if [ -z "$PYENV_ROOT" ]; then
# If PYENV_ROOT is not set, then set it to the default value
export PYENV_ROOT="/usr/local/lib"
echo "PYENV_ROOT was not set. Setting it to default: $PYENV_ROOT"
else
echo "PYENV_ROOT is already set to: $PYENV_ROOT"
fi
echo "=========================== log4j2 - appdynamics_bindeps module ========================="
# Find the appdynamics_bindeps directory
APP_APPD_BINDEPS_DIR=$(find "$PYENV_ROOT" -type d -name "appdynamics_bindeps" -print -quit)
if [ -z "$APP_APPD_BINDEPS_DIR" ]; then
echo "Error: appdynamics_bindeps directory not found."
exit 1
fi
echo "Found appdynamics_bindeps directory at $APP_APPD_BINDEPS_DIR"
# Find the log4j2.xml file within the appdynamics_bindeps directory
APP_LOG4J2_FILE=$(find "$APP_APPD_BINDEPS_DIR" -type f -name "log4j2.xml" -print -quit)
if [ -z "$APP_LOG4J2_FILE" ]; then
echo "Error: log4j2.xml file not found within the appdynamics_bindeps directory."
exit 1
fi
echo "Found log4j2.xml file at $APP_LOG4J2_FILE"
# Modify the log level in the log4j2.xml file
echo "Modifying log level in log4j2.xml file"
sed -i 's/level="info"/level="${env:APP_APPD_LOG4J2_LOG_LEVEL:-info}"/g' "$APP_LOG4J2_FILE"
echo "log4j2.xml file modified successfully."
echo "=========================== watchdog - appdynamics module ==============================="
# Find the appdynamics directory
APP_APPD_DIR=$(find "$PYENV_ROOT" -type d -name "appdynamics" -print -quit)
if [ -z "$APP_APPD_DIR" ]; then
echo "Error: appdynamics directory not found."
exit 1
fi
echo "Found appdynamics directory at $APP_APPD_DIR"
# Find the proxy.py file within the appdynamics directory
APP_PROXY_PY_FILE=$(find "$APP_APPD_DIR" -type f -name "proxy.py" -print -quit)
if [ -z "$APP_PROXY_PY_FILE" ]; then
echo "Error: proxy.py file not found within the appdynamics directory."
exit 1
fi
echo "Found proxy.py file at $APP_PROXY_PY_FILE"
# Modify the log level in the proxy.py file
echo "Modifying log level in proxy.py file"
sed -i 's/logging.DEBUG if debug else logging.INFO/os.getenv("APP_APPD_WATCHDOG_LOG_LEVEL", "info").upper()/g' "$APP_PROXY_PY_FILE"
echo "proxy.py file modified successfully."
```
## Dockerfile
Dockerfile to run pyagent with FastAPI and run this script
```dockerfile
# Use a specific version of the python image
FROM python:3.9
# Set the working directory in the container
WORKDIR /app
# First, copy only the requirements file and install dependencies to leverage Docker cache
COPY requirements.txt ./
RUN python3 -m pip install --no-cache-dir -r requirements.txt
# Now copy the rest of the application to the container
COPY . .
# Make the update_log4j2.sh and update_watchdog.sh scripts executable and run them
RUN chmod +x update_appdynamics_log_level.sh && \
./update_appdynamics_log_level.sh
# Set environment variables
ENV APP_APPD_LOG4J2_LOG_LEVEL="warn" \
APP_APPD_WATCHDOG_LOG_LEVEL="warn"
EXPOSE 8000
# Command to run the FastAPI application with pyagent
CMD ["pyagent", "run", "uvicorn", "main:app", "--proxy-headers", "--host","0.0.0.0", "--port","8000"]
```
## Files changed by the script
### log4j2.xml
```xml
<Loggers>
<!-- Modify each <AsyncLogger> level as needed -->
<AsyncLogger name="com.singularity" level="${env:APP_APPD_LOG4J2_LOG_LEVEL:-info}" additivity="false">
<AppenderRef ref="Default"/>
<AppenderRef ref="RESTAppender"/>
<AppenderRef ref="Console"/>
</AsyncLogger>
</Loggers>
```
### proxy.py
```python
def configure_proxy_logger(debug):
logger = logging.getLogger('appdynamics.proxy')
level = os.getenv("APP_APPD_WATCHDOG_LOG_LEVEL", "info").upper()
pass
def configure_watchdog_logger(debug):
logger = logging.getLogger('appdynamics.proxy')
level = os.getenv("APP_APPD_WATCHDOG_LOG_LEVEL", "info").upper()
pass
```
## Warning
Please note, these paths and methods may vary based on your AppDynamics version and environment setup. Always backup files before making changes and be aware that updates to AppDynamics may overwrite your customizations.
I hope this helps! |
[Per my top comment], building with `-Wall -O0 -g -fsanitize=address`, a few issues ...
1. With `-Wall`, arguments `col` and `row` are `char` and compiler complains about that (converted to `int`)
1. `row` and `col` are unitialized (in `main`) but the _values_ are never used by `computerMove` or `UserMove` (set to zero to eliminate warning). They do _not_ need to be arguments.
1. After fixing the warnings (which one should _always_ do), the address sanitizer is detecting a fault.
----------
With a board size of `8` and computer with `B`, in `computerMove`, the sanitizer complains about the `if`:
```
for (int i = 0; i < counter; i++) {
for (int j = 0; j < n; j++) {
dbgprt("i=%d j=%d tracker=%d\n",i,j,tracker);
if ((movesrow[duplicates[i]] < movesrow[duplicates[i + j]]) &&
movescol[duplicates[i]] < movescol[duplicates[i + j]]) {
rowtemp = movesrow[duplicates[i]];
coltemp = movescol[duplicates[i]];
}
else {
rowtemp = movesrow[duplicates[i + j]];
coltemp = movescol[duplicates[i + j]];
}
}
}
```
The debug `printf` I added shows:
```
i=0 j=0 tracker=4
i=0 j=1 tracker=4
i=0 j=2 tracker=4
i=0 j=3 tracker=4
i=0 j=4 tracker=4
```
The array `duplicates` is of dimension `tracker` (which is 4), so `i + j` is becoming too large and overflows `duplicates`. This is UB (undefined behavior).
Further, `duplicates` is initialized starting at index of 1. But, in the loop that follows, `duplicates[i]` is being fetched, so when `i` is 0, the array value is _random_ (this is, again, UB).
----------
Here is the refactored code. It is annotated:
```
#include <stdio.h>
#include <stdlib.h>
#if 0
#include "lab8part1.h"
#else
#include <stdbool.h>
#endif
#if DEBUG
#define dbgprt(_fmt...) \
printf(_fmt)
#else
#define dbgprt(_fmt...)
do { } while (0)
#endif
void printBoard(char board[][26], int n);
bool positionInBounds(int n, int row, int col);
bool checkLegalInDirection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol);
bool validMove(char board[][26], int n, int row, int col, char colour);
#if 0
bool computerMove(char board[][26], int n, char colour, char row, char col);
bool UserMove(char board[][26], int n, char colour, char row, char col);
#else
bool computerMove(char board[][26], int n, char colour, int row, int col);
bool UserMove(char board[][26], int n, char colour, int row, int col);
#endif
int checkBestMoves(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol);
bool checkifmove(char board[][26], int n, char color);
int
main(void)
{
#if 0
char board[26][26], color, row, col;
#else
char board[26][26], color;
int row, col;
#endif
printf("Enter the board dimension: ");
int n;
scanf(" %d", &n);
int start = n / 2;
for (int m = 0; m < n; m++) {
for (int j = 0; j < n; j++) {
if ((m == start - 1 && j == start - 1) ||
(m == start && j == start)) {
board[m][j] = 'W';
}
else if ((m == start - 1 && j == start) ||
(m == start && j == start - 1)) {
board[m][j] = 'B';
}
else {
board[m][j] = 'U';
}
}
}
printf("Computer plays (B/W): ");
scanf(" %c", &color);
char color1;
if (color == 'B') {
color1 = 'W';
}
else {
color1 = 'B';
}
printBoard(board, n);
printf("\n");
char turn = 'B';
bool validmove = true;
// NOTE/BUG: these are unitialized, but the neither computerMove nor UserMove
// use them. they do _not_ need to be arguments
#if 1
row = 0;
col = 0;
#endif
while ((checkifmove(board, n, color) == true) ||
(checkifmove(board, n, color1) == true)) {
validmove = true;
if (turn == color) {
validmove = computerMove(board, n, color, row, col);
}
else {
UserMove(board, n, color1, row, col);
}
if (validmove == false) {
break;
}
if (turn == 'W') {
turn = 'B';
}
else {
turn = 'W';
}
}
int whitwin = 0;
int blacwin = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'W') {
whitwin += 1;
}
else {
blacwin += 1;
}
}
}
if (whitwin > blacwin) {
printf("W player wins.");
}
else if (whitwin < blacwin) {
printf("B player wins.");
}
else {
printf("Draw.");
}
return 0;
}
#if 0
bool
computerMove(char board[][26], int n, char colour, char row, char col)
#else
bool
computerMove(char board[][26], int n, char colour, int row, int col)
#endif
{
int movesrow[100] = { 0 };
int movescol[100] = { 0 };
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'U') {
if (checkLegalInDirection(board, n, i, j, colour, -1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
}
}
count += 1;
}
int bestMoves[600] = { 0 };
int tracker = 0;
int tot = 0;
for (int i = 0; i < count; i++) {
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
}
// if computer runs out of moves
if (bestMoves[0] == 0) {
printf("%c player has no valid move.", colour);
return false;
}
int counter = 0;
int bigNum = bestMoves[0];
int duplicates[tracker];
for (int i = 1; i < tracker; i++) {
if (bestMoves[i] > bigNum) {
bigNum = bestMoves[i];
duplicates[0] = i;
counter = 1;
}
else if (bestMoves[i] == bigNum) {
duplicates[counter] = i;
counter++;
}
}
int rowtemp = 0,
coltemp = 0;
for (int i = 0; i < counter; i++) {
for (int j = 0; j < n; j++) {
dbgprt("i=%d j=%d tracker=%d\n",i,j,tracker);
// NOTE/BUG: i + j will exceed tracker -- this is UB
if ((movesrow[duplicates[i]] < movesrow[duplicates[i + j]]) &&
movescol[duplicates[i]] < movescol[duplicates[i + j]]) {
rowtemp = movesrow[duplicates[i]];
coltemp = movescol[duplicates[i]];
}
else {
rowtemp = movesrow[duplicates[i + j]];
coltemp = movescol[duplicates[i + j]];
}
}
}
row = rowtemp;
col = coltemp;
if (validMove(board, n, (row), (col), colour)) {
board[row][col] = colour;
printf("\nComputer places %c at %c%c\n", colour, (row + 'a'), (col + 'a'));
printBoard(board, n);
return true;
}
else {
return false;
}
}
#if 0
bool
UserMove(char board[][26], int n, char colour, char row, char col)
#else
bool
UserMove(char board[][26], int n, char colour, int row, int col)
#endif
{
int movesrow[100] = { 0 };
int movescol[100] = { 0 };
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'U') {
if (checkLegalInDirection(board, n, i, j, colour, -1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
}
}
count += 1;
}
int bestMoves[100] = { 0 };
int tracker = 0;
int tot = 0;
for (int i = 0; i < count; i++) {
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
}
// if player runs out of moves
if (bestMoves[0] == 0) {
printf("%c player has no valid move.", colour);
return false;
}
printf("\nEnter a move for colour %c (RowCol): ", colour);
#if 0
scanf(" %c%c", &row, &col);
#else
char c_row, c_col;
scanf(" %c%c", &c_row, &c_col);
row = c_row;
col = c_col;
#endif
if (validMove(board, n, (row - 'a'), (col - 'a'), colour)) {
board[row - 'a'][col - 'a'] = colour;
printBoard(board, n);
}
return true;
}
bool
validMove(char board[][26], int n, int row, int col, char colour)
{
int score = 0;
if (checkLegalInDirection(board, n, row, col, colour, -1, -1)) {
score++;
int i = 1;
while (board[row + (i * -1)][col + (i * -1)] != colour) {
board[row + (i * -1)][col + (i * -1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, -1, 0)) {
score++;
int i = 1;
while (board[row + (i * -1)][col + (i * 0)] != colour) {
board[row + (i * -1)][col + (i * 0)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, -1, 1)) {
score++;
int i = 1;
while (board[row + (i * -1)][col + (i * 1)] != colour) {
board[row + (i * -1)][col + (i * 1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 0, -1)) {
score++;
int i = 1;
while (board[row + (i * 0)][col + (i * -1)] != colour) {
board[row + (i * 0)][col + (i * -1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 0, 1)) {
score++;
int i = 1;
while (board[row + (i * 0)][col + (i * 1)] != colour) {
board[row + (i * 0)][col + (i * 1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 1, -1)) {
score++;
int i = 1;
while (board[row + (i * 1)][col + (i * -1)] != colour) {
board[row + (i * 1)][col + (i * -1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 1, 0)) {
score++;
int i = 1;
while (board[row + (i * 1)][col + (i * 0)] != colour) {
board[row + (i * 1)][col + (i * 0)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 1, 1)) {
score++;
int i = 1;
while (board[row + (i * 1)][col + (i * 1)] != colour) {
board[row + (i * 1)][col + (i * 1)] = colour;
i++;
}
}
if (score > 0) {
return true;
}
else {
return false;
}
}
void
printBoard(char board[][26], int n)
{
printf(" ");
for (int i = 0; i < n; i++) {
printf("%c", 'a' + i);
}
for (int m = 0; m < n; m++) {
printf("\n%c ", 'a' + m);
for (int j = 0; j < n; j++) {
printf("%c", board[m][j]);
}
}
}
bool
positionInBounds(int n, int row, int col)
{
if (row >= 0 && row < n && col >= 0 && col < n) {
return true;
}
else {
return false;
}
}
bool
checkLegalInDirection(char board[][26], int n, int row, int col, char colour,
int deltaRow, int deltaCol)
{
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] != 'U') {
return false;
}
row += deltaRow;
col += deltaCol;
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] == colour || board[row][col] == 'U') {
return false;
}
while ((positionInBounds(n, row, col)) == true) {
if (board[row][col] == colour) {
return true;
}
if (board[row][col] == 'U') {
return false;
}
row += deltaRow;
col += deltaCol;
}
return false;
}
int
checkBestMoves(char board[][26], int n, int row, int col, char colour,
int deltaRow, int deltaCol)
{
int tiles = 0;
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] != 'U') {
return false;
}
row += deltaRow;
col += deltaCol;
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] == colour || board[row][col] == 'U') {
return false;
}
while ((positionInBounds(n, row, col)) == true) {
if (board[row][col] == colour) {
return tiles;
}
if (board[row][col] == 'U') {
return false;
}
tiles += 1;
row += deltaRow;
col += deltaCol;
}
return false;
}
bool
checkifmove(char board[][26], int n, char color)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'U') {
if (checkLegalInDirection(board, n, i, j, color, -1, -1) ||
checkLegalInDirection(board, n, i, j, color, -1, 0) ||
checkLegalInDirection(board, n, i, j, color, -1, 1) ||
checkLegalInDirection(board, n, i, j, color, 0, -1) ||
checkLegalInDirection(board, n, i, j, color, 0, 1) ||
checkLegalInDirection(board, n, i, j, color, 1, -1) ||
checkLegalInDirection(board, n, i, j, color, 1, 0) ||
checkLegalInDirection(board, n, i, j, color, 1, 1)) {
return true;
}
}
}
}
return false;
}
```
----------
In the code above, I've used `cpp` conditionals to denote old vs. new code:
```
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
```
Note: this can be cleaned up by running the file through `unifdef -k`
|
c_cpp_properties.json. give the correct value for compilerPath and intelliSenseMode
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"~/android-ndk-r25c",
"~/android-ndk-r25c/toolchains/llvm/prebuilt/linux-x86_64/**"
],
"defines": [],
"compilerPath": "~/android-ndk-r25c/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-clang ",
"cStandard": "c17",
"cppStandard": "gnu++17",
"intelliSenseMode": "linux-clang-arm64"
}
],
"version": 4
} |
So, I have a little tricky assignment to solve and I am entirely new to functional programming.
There is a list of boolean variables (neither strings nor chars cuz the algorithm only takes boolean variables so they were converted)
vars = [p;q;r] and there are 2 algorithms say A and B and one boolean equation eq1 = p & q
The loop should perform something like this:
**Step1 :let x = A ((B vars[0]) eq1)** (The algorithm B works on vars[0] and then algorithm A works together on this and eq1)
**Step2 : let x1 = A ((B vars[1]) x)** (In the next step, eq1 should be replaced with the answer from the previous step and algo B should work on vars[1]
**Step3: let x2 = A ((B vars[2]) x1)**
In other languages, this can be written as a loop with the logic
foreach (i in vars){
x = (A (B vars[i]) eq1)
eq1 = x }
Not sure how such a loop can be written in f# |
I have JSON Rows which can change key and type of values
changing keys in examples are
`015913d2e43d41ef98e6e5c8dc90cd09_2_1` and
`e8c93befe4a34bcabbf604e352a41a2d_2_1`
changing types of values are
list (Row 1):
```
"answer": [
"<i>GET</i>\n",
"<i>PUT</i>\n",
"<i>POST</i>\n",
"<i>TRACE</i>\n",
"<i>HEAD</i>\n",
"<i>DELETE</i>\n"
],
```
text (Row 2):
```
"answer": "Может быть во всех",
```
Examples of rows:
row 1
```
{
"event": {
"submission": {
"015913d2e43d41ef98e6e5c8dc90cd09_2_1": {
"question": "Какие виды <i>HTTP</i> запросов могут внести изменения на сервере (в общем случае)?",
"answer": [
"<i>GET</i>\n",
"<i>PUT</i>\n",
"<i>POST</i>\n",
"<i>TRACE</i>\n",
"<i>HEAD</i>\n",
"<i>DELETE</i>\n"
],
"response_type": "choiceresponse",
"input_type": "checkboxgroup",
"correct": false,
"variant": "",
"group_label": ""
}
}
}
}
```
row 2
```
{
"event": {
"submission": {
"e8c93befe4a34bcabbf604e352a41a2d_2_1": {
"question": "В запросах какого типа может быть использована <i>RCE</i>?",
"answer": "Может быть во всех",
"response_type": "multiplechoiceresponse",
"input_type": "choicegroup",
"correct": true,
"variant": "",
"group_label": ""
}
}
}
}
```
[Here is the Image in Power Query](https://i.stack.imgur.com/cKe3i.jpg)
How can extract data from the List in Direct Power Query?
If I write this
`= Table.AddColumn(#"Duplicated Column", "answer_s", each Record.Field([raw_event][event][submission],[question_id])[answer]{0})`
I get error with text types answers
[image, error with text types](https://i.stack.imgur.com/Lg3rS.jpg)
If i write this:
`= Table.AddColumn(#"Duplicated Column", "answer_s", each Record.Field([raw_event][event][submission],[question_id])[answer])`
[I get Lists](https://i.stack.imgur.com/5ByC8.jpg)
I have already asked the question with parsing JSON
https://stackoverflow.com/questions/78205099/json-parsing-with-changing-keys/78206024#78206024
the result I would like to receive should be looks like
[this][1]
thanks!
[1]: https://i.stack.imgur.com/aC02l.png |
I'm currently in the process of transitioning from using Terraform for managing my GitLab CI/CD pipelines to using OpenTofu. In this migration, I also need to integrate OIDC (OpenID Connect) authentication into my GitLab pipelines.
Previously, my .gitlab-ci.yml file looked something like this with Terraform:
`#You should upgrade to the latest version. You can find the latest version at https://gitlab.com/gitlab-com/gl-security/security-operations/infrastructure-security-public/oidc-modules/-/releases
include:
- remote: 'https://gitlab.com/gitlab-com/gl-security/security-operations/infrastructure-security-public/oidc-modules/-/raw/3.1.2/templates/gcp_auth.yaml'
- template: "Terraform/Base.gitlab-ci.yml"
variables:
WI_POOL_PROVIDER: //iam.googleapis.com/projects/$GCP_PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_IDENTITY_POOL/providers/$WORKLOAD_IDENTITY_POOL_PROVIDER
SERVICE_ACCOUNT: $SERVICE_ACCOUNT
TF_ROOT: infrastructure
TF_STATE_NAME:tfstate
stages:
- validate
- test
- build
- deploy
validate:
extends: .terraform:validate
needs: []
build:
extends:
- .google-oidc:auth
- .terraform:build
deploy:
extends:
- .google-oidc:auth
- .terraform:deploy
dependencies:
- build
`
Now, I want to replace the Terraform-based setup with OpenTofu, while also incorporating OIDC authentication into my pipeline. However, I'm unsure about how to structure the .gitlab-ci.yml file and configure OpenTofu to achieve this.
Could someone provide guidance on how to migrate from Terraform to OpenTofu for GitLab CI/CD pipelines, particularly focusing on integrating OIDC authentication into the pipeline setup? Any examples, tips, or resources would be greatly appreciated. Thank you! |
This is really a general question, so I do not have a reprex. Using [CellEdit](https://github.com/ejbeaty/CellEdit/tree/master), does anyone know how to replace the options of an 'list' input with dynamic dropdown options.
```
"table.MakeCellsEditable({",
" onUpdate: onUpdate,",
" inputCss: 'my-input-class',",
" confirmationButton: {",
" confirmCss: 'my-confirm-class',",
" cancelCss: 'my-cancel-class'",
" },",
" inputTypes: [",
" {",
" column: 0,",
" type: 'list',",
" options: [",
" {value: 'Keep data', display: 'Keep data'},",
" {value: 'Pass', display: 'Pass'},",
" {value: 'Delete', display: 'Delete'}",
" ]",
" }",
" ]",
"});"
```
I am referencing the code from this [question](https://stackoverflow.com/questions/66004405/access-updated-datatable-edited-with-celledit-in-r-shiny/66007497#66007497) on SO. |
Datatables row editable with CellEdit dynamic options in R Shiny |
|javascript|r|shiny|datatables|dt| |
null |
I'm working with CodeIgniter, passing an object to a view within a `foreach` loop. I've noticed that 'view2' prints the number '2' during the first iteration of the loop, but I can't determine why it also continues to print '2' during the second iteration.
Is this behavior due to the objects sharing memory addresses, or is it an issue with the variables used within the loop?
**Controller**
```php
function controller() {
$result = (object) [
(object) [ "a" => 1, "b" => 2 ],
(object) [ "a" => 3 ]
];
$this->load->view("view1", $result);
}
```
**view1**
```php
<?php
foreach($result as $index => $res) {
if($index == 0) {
$this->load->view("view2", $res);
} else {
$this->load->view("view2");
}
}
?>
```
**view2**
```php
echo $b
```
|
passing object to a view within a foreach loop in CodeIgniter |
|php|for-loop|codeigniter|foreach| |
Largest product in a grid
Input
89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
Output
73812150
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] in = new int[20][20];
// Taking user input for the grid
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
in[i][j] = sc.nextInt();
}
}
int max = Integer.MIN_VALUE;
int tmp = 0;
// Calculate maximum product
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (i < 17) {
tmp = in[i][j] * in[i + 1][j] * in[i + 2][j] * in[i + 3][j];
if (tmp > max) max = tmp;
}
if (j < 17) {
tmp = in[i][j] * in[i][j + 1] * in[i][j + 2] * in[i][j + 3];
if (tmp > max) max = tmp;
}
if (j < 17 && i < 17) {
tmp = in[i][j] * in[i + 1][j + 1] * in[i + 2][j + 2] * in[i + 3][j + 3];
if (tmp > max) max = tmp;
}
if (i < 17 && j > 2) {
tmp = in[i][j] * in[i + 1][j - 1] * in[i + 2][j - 2] * in[i + 3][j - 3];
if (tmp > max) max = tmp;
}
}
}
System.out.println(max);
}}
|
|r|fixed-width| |
null |
null |
```Bot is ready
/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py:464: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/client.py", line 703, in _run_event
await coro(*args, **kwargs)
File "/home/runner/BattleEx/main.py", line 13, in on_ready
await bot.load_extensions("cogz")
TypeError: object NoneType can't be used in 'await' expression
```
This is my redis.py
I don unnderstand why this is hapenning there is nothin that can be Nonetype here ig.
redis.py
```
import aioredis,asyncio
from disnake.ext import commands
import os
from disnake.ext import commands
import os
class Redis(commands.Cog):
"""For Redis."""
def __init__(self, bot: commands.Bot):
self.bot = bot
self.pool = None
self._reconnect_task = self.bot.loop.create_task(self.connect())
#all funcs here
async def setup(bot: commands.Bot):
print("Here")
redis_cog = Redis(bot)
print("Setting up Redis cog...")
await redis_cog.connect()
await bot.add_cog(redis_cog)
```
i tried it with discord.py using bot.load_extensino("cogz,redis") still getting same error. |
Bot.load_Extension is returning this error for disnake and discord.py library both |
|python|discord|bots|disnake| |
null |
"""hello.
this code is runing,
versions:
Python==3.11.1
opencv-contrib-python==4.9.0.80
opencv-python==4.9.0.80
in this case we have this aruco of 7x7 "DICT_7X7_100" but you can change to "DICT_5X5_100", you must to change in 3 lines of this program"""
to generate Aruco images:
https://chev.me/arucogen/
import numpy as np
import cv2
import sys
import time
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DICT_4X4_250": cv2.aruco.DICT_4X4_250,
"DICT_4X4_1000": cv2.aruco.DICT_4X4_1000,
"DICT_5X5_50": cv2.aruco.DICT_5X5_50,
"DICT_5X5_100": cv2.aruco.DICT_5X5_100,
"DICT_5X5_250": cv2.aruco.DICT_5X5_250,
"DICT_5X5_1000": cv2.aruco.DICT_5X5_1000,
"DICT_6X6_50": cv2.aruco.DICT_6X6_50,
"DICT_6X6_100": cv2.aruco.DICT_6X6_100,
"DICT_6X6_250": cv2.aruco.DICT_6X6_250,
"DICT_6X6_1000": cv2.aruco.DICT_6X6_1000,
"DICT_7X7_50": cv2.aruco.DICT_7X7_50,
"DICT_7X7_100": cv2.aruco.DICT_7X7_100,
"DICT_7X7_250": cv2.aruco.DICT_7X7_250,
"DICT_7X7_1000": cv2.aruco.DICT_7X7_1000,
"DICT_ARUCO_ORIGINAL": cv2.aruco.DICT_ARUCO_ORIGINAL,
"DICT_APRILTAG_16h5": cv2.aruco.DICT_APRILTAG_16h5,
"DICT_APRILTAG_25h9": cv2.aruco.DICT_APRILTAG_25h9,
"DICT_APRILTAG_36h10": cv2.aruco.DICT_APRILTAG_36h10,
"DICT_APRILTAG_36h11": cv2.aruco.DICT_APRILTAG_36h11
}
def aruco_display(corners, ids, rejected, image):
if len(corners) > 0:
ids = ids.flatten()
for (markerCorner, markerID) in zip(corners, ids):
corners = markerCorner.reshape((4, 2))
(topLeft, topRight, bottomRight, bottomLeft) = corners
topRight = (int(topRight[0]), int(topRight[1]))
bottomRight = (int(bottomRight[0]), int(bottomRight[1]))
bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))
topLeft = (int(topLeft[0]), int(topLeft[1]))
cv2.line(image, topLeft, topRight, (0, 255, 0), 2)
cv2.line(image, topRight, bottomRight, (0, 255, 0), 2)
cv2.line(image, bottomRight, bottomLeft, (0, 255, 0), 2)
cv2.line(image, bottomLeft, topLeft, (0, 255, 0), 2)
cX = int((topLeft[0] + bottomRight[0]) / 2.0)
cY = int((topLeft[1] + bottomRight[1]) / 2.0)
cv2.circle(image, (cX, cY), 4, (0, 0, 255), -1)
cv2.putText(image, str(markerID),(topLeft[0], topLeft[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 255, 0), 2)
print("[Inference] ArUco marker ID: {}".format(markerID))
return image
def pose_estimation(frame, aruco_dict_type, matrix_coefficients, distortion_coefficients):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_7X7_100) # cv2.aruco.DICT_4X4_250 seleccion del modelo Aruco
parameters = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(dictionary, parameters)
corners, ids, rejected_img_points = detector.detectMarkers(gray)
if len(corners) > 0:
for i in range(0, len(ids)):
rvec, tvec, markerPoints = cv2.aruco.estimatePoseSingleMarkers(corners[i], 0.02, matrix_coefficients, distortion_coefficients)
cv2.aruco.drawDetectedMarkers(frame, corners)
cv2.drawFrameAxes(frame, matrix_coefficients, distortion_coefficients, rvec, tvec, 0.01)
return frame
aruco_type = "DICT_7X7_100"
arucoDict = cv2.aruco.DICT_7X7_100
arucoParams = cv2.aruco.DetectorParameters()
intrinsic_camera = np.array(((933.15867, 0, 657.59),(0,933.1586, 400.36993),(0,0,1)))
distortion = np.array((-0.43948,0.18514,0,0))
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
while cap.isOpened():
ret, img = cap.read()
output = pose_estimation(img, ARUCO_DICT[aruco_type], intrinsic_camera, distortion)
cv2.imshow('Estimated Pose', output)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|
I am trying to perform a side-channel attack on a GPU, and I am trying to find out if there is a way to profile a "victim" GPU kernel from a "spy" GPU kernel. It could be anything, like execution time, memory allocation, etc. So, I want a method to get statistics about another kernel in CUDA C++. Is this possible? I want it to be within my code, and not by seeing results from Nsight Compute. |
Is there a way to profile a CUDA kernel from another CUDA kernel |
|c++|cuda|gpu|side-channel-attacks| |
I am making `MultiVector` class for Entity Componen System. It is used for storing objects of different types for iterating over them efficiently.
I use vectors of bytes as raw storage and `reinterpret_cast` it to whichever type I need. Basic functionality (`push_back` by const reference and `pop_back`) seems to work.
However, when I try to implement move semantics for `push_back` (commented lines), clang gives me incomprehensible 186 lines error message, something about 'allocate is declared as pointer to a reference type'. As I understand, vector tries to `push_back` reference to T, which it cannot do because it must own contained objects.
How am I supposed to do it?
```
#include <iostream>
#include <vector>
using namespace std;
int g_class_id { 0 };
template <class T>
const int get_class_id()
{
static const int id { g_class_id++ };
return id;
}
class MultiVector {
public:
MultiVector() : m_vectors(g_class_id + 1) {}
template <typename T>
vector<T>& vector_ref() {
const int T_id { get_class_id<T>() };
if (T_id >= m_vectors.size()) {
m_vectors.resize(T_id + 1);
}
vector<T>& vector_T { *reinterpret_cast<vector<T>*>(&m_vectors[T_id]) };
return vector_T;
}
template<typename T>
void push_back(const T& value) {
vector_ref<T>().push_back(value);
}
// Move semantics, take rvalue reference
template<typename T>
void push_back(T&& value) {
vector_ref<T>().push_back(std::move(value));
}
template <typename T>
void pop_back() {
vector_ref<T>().pop_back();
}
private:
vector<vector<byte>> m_vectors;
};
template<typename T>
void show(const vector<T>& vct)
{
for (const auto& item : vct) cout << item << ' ';
cout << '\n';
}
int main(int argc, const char *argv[])
{
string hello = "hello";
string world = "world";
MultiVector mv;
mv.push_back(10);
mv.push_back(20);
mv.push_back(2.7);
mv.push_back(3.14);
mv.push_back(hello);
mv.push_back(world);
show(mv.vector_ref<int>());
show(mv.vector_ref<double>());
show(mv.vector_ref<string>());
mv.vector_ref<int>().pop_back();
show(mv.vector_ref<int>());
return 0;
}
```
Tried to replace rvalue reference `T&&` to just value `T`, does not compile too because call to `push_back` becomes ambiguous. |
I ended up adding `methods` field to the vercel.json routes array and the deployment worked!
I found this configuration on this [blog][1] and by the looks of it, it should work on other typescript based backend server that you want to deploy on vercel.
{
"version": 2,
"builds": [
{
"src": "dist/src/index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/src/index.js",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
}
]
}
[1]: https://www.todayunboxed.com/deploy-your-nestjs-app-like-a-pro-with-vercel-in-2024-step-by-step-guide |
I encountered a error
```
PS C:\\Users\\91789\\Desktop\\Underwater-Image-Enhancement\\WPFNet\> python Underwater_test.py C:\\Users\\91789\\Desktop\\input C:\\Users\\91789\\Desktop\\New folder ./checkpoint/generator_600.pth
C:\\Users\\91789\\AppData\\Local\\Programs\\Python\\Python312\\python.exe: can't open file 'C:\\\\Users\\\\91789\\\\Desktop\\\\Underwater-Image-Enhancement\\\\WPFNet\\\\Underwater_test.py': \[Errno 2\] No such file or directory
```
How can i solve it and run it and this is the github link : [https://github.com/LiuShiBen/WPFNet.git] |
null |
To filter IPv6 addresses (as you have asked), use the `filter_var` function with the `FILTER_FLAG_IPV4` flag for IPv4 addresses and `FILTER_FLAG_IPV6` for IPv6 respectively:
if ( filter_var($client_ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4) )
// use legacy filter method
} elseif ( filter_var($client_ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) )
// use new module for white-listing IPv6 addresses
}
[Here's the PHP documentation on filters.][1] I hope it helps.
[1]: https://www.php.net/manual/en/filter.filters.validate.php |
`driver.find_element(By.XPATH,'//body/div/div/div/div/div/div/div/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/input').send_keys(country)`
This is the xpath for sending text in the dropdown of the facebook ad library report. It works well in window but when I run this selenium script in Linux machine (ec2-**-**-\*\*.us-east-2.compute.amazonaws.com) it shows error in this line:
`selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:`
`{"method":"xpath","selector":"//body/div/div/div/div/div/div/div/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/input"} `` `
```python
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
options.add_argument('--no-sandbox')
options.add_argument("--silent")
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
options.add_argument('start-maximized')
options.add_argument("--window-size=1519.200,5471.890")
options.add_argument("--window-position=0,0")
options.add_argument('--disable-dev-shm-usage')
```
These are the arguments used.
Kindly given the solution for this |
I'm recently trying to learn the tanstack table v8 react table.
it renders the columns and data in the table correctly however i'm getting an error that says
"Hydration failed because the initial UI does not match what was rendered on the server"
"Warning: Expected server HTML to contain a matching <tr> in <table>."
I also checked the closing tags of my tables but it is correct
Code:
"use client";
import {
useReactTable,
getCoreRowModel,
flexRender,
} from "@tanstack/react-table";
import { useMemo } from "react";
const Table = ({ data, columns }) => {
const dataTable = useMemo(() => data, [data])
const table = useReactTable({
data: dataTable,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div>
BasicTable
<table>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id}>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Table;
|
Migrating .gitlab-ci.yml from Terraform to OpenTofu with OIDC Setup |
|terraform|gitlab-ci|openid-connect|opentofu| |
null |
In my app, users can write in English as well as Arabic. So for English, I want to use "Poppins" as font style, and for Arabic, I want to use "sfArabic". I did not find any proper solution for that.
**Below is my expected output -**
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/1jpxv.png |
Multiple textstyles in Textfield in Flutter |
|flutter|dart|user-interface|textfield|textstyle| |
I looking-for solution to order/sort by relation (hasMany) fields, with max value of two columns.
I prepare starter kit: https://www.db-fiddle.com/f/m371fzUJuQp9dX1yKm4yEm/3
```
SELECT
GREATEST(
MAX(COALESCE(`to`, 0)),
MAX(COALESCE(`from`, 0))
),
`parent_id`
FROM salaries
GROUP BY `parent_id`;
```
The question is, how to display results from `parents` table, with GREATEST(MAX, MAX) value from two fields, order of course from high to low in Laravel Eloquent ORM?
Expected results:
```
11 / jedenastka / 56
13 / trzynastka / 44
7 / siodemka / 23
12 / dwunastka / 14
10 / dyszka / 11
9 / dziewiatka. / 9
33 / trzydziestktrojka / 1
``` |
|c++|c++23| |
I tried many options to install bundle but nothing helped. Here is my dockerfile:
ERROR: failed to solve: process "/bin/sh -c gem bundle install" did not complete successfully: exit code: 1
```
`FROM gitlab.akb-it.ru:4567/academy/devops/ruby-image:3.2.2-ubuntu-22.04 as builder
WORKDIR /usr/src/app
RUN apt-get update && apt-get install -y \
git curl autoconf bison build-essential \
libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libpq-dev libncurses5-dev \
apt-utils libffi-dev libgdbm6 libgdbm-dev libdb-dev gcc g++ make
COPY Gemfile Gemfile.lock ./
RUN gem bundle install
#########################################
# #
#########################################
FROM gitlab.akb-it.ru:4567/academy/devops/ruby-image:3.2.2-ubuntu-22.04
ENV TZ=Europe/Moscow
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN apt-get update && \
apt-get upgrade -y && \
apt-get install -y libyaml-dev zlib1g-dev libpq-dev libyaml-dev libreadline6-dev && \
apt purge build-essential linux-libc-dev git-core openssh-client make -y && \
apt-get autoclean
WORKDIR /usr/src/app
COPY --from=builder /usr/local/bundle/ /usr/local/bundle/
COPY . /usr/src/app
EXPOSE 3000`
```
I tried this, but it didn't help
```
`RUN gem install -N bundler -v 2.4.0 && \
bundle config set no-cache 'true' && \
bundle install && \`
`RUN gem install bundler -v '2.2.28' && bundle install`
`RUN rm -rf /usr/local/bundle/cache`
```
|
bundle install in dockerfile |
|dockerfile|bundle| |
null |
To access the custom field in your data through the context menu, you could use the `listen()` method with event type `contextMenu` and a custom item provider for the context menu as shown in the sample below.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
anychart.onDocumentReady(function () {
// create data
var data = getData();
// create a chart and set the data
var chart = anychart.treeMap(data, "as-tree");
// find index of a clicked point
var clickedPointIndex;
chart.listen('contextMenu', (e) => {
clickedPointIndex = e.pointIndex - 1 //indexes in data are 0 based
});
// replace menu items provider
chart.contextMenu().itemsProvider(function() {
var items = {
'menu-item-1': {
'text': 'Log custom field to console',
'action': () => {
var parent = data[0];
var child = parent.children[clickedPointIndex];
var customField = child.customField
if (customField){
console.log(customField);
} else {
console.log("No custom field found");
}
}
}
}
return items;
});
// set the container id
chart.container("container");
// initiate drawing the chart
chart.draw();
});
const getData = () => {
return [
{name: "European Union", children: [
{name: "Belgium", value: 11443830, customField: "Yes"},
{name: "France", value: 64938716},
{name: "Germany", value: 80636124},
{name: "Greece", value: 10892931},
{name: "Italy", value: 59797978},
{name: "Netherlands", value: 17032845},
{name: "Poland", value: 38563573},
{name: "Romania", value: 19237513},
{name: "Spain", value: 46070146},
{name: "United Kingdom", value: 65511098}
]}
];
}
<!-- language: lang-css -->
html, body, #container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<!-- language: lang-html -->
<link href="https://cdn.anychart.com/releases/8.12.0/css/anychart-ui.min.css" rel="stylesheet"/>
<script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-base.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
<script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-treemap.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
<script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-exports.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
<script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-ui.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
<div id="container"></div>
<!-- end snippet -->
|
I use shader in phaserjs to change the color of characters and also for rain
But the game renders correctly in Google Chrome, but I have a rendering problem in Capacitor, in such a way that the rain is displayed in the form of a ruler.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/uKNif.jpg |
I have a data structure in Firestore that contains nested arrays, as shown in the following JSON example:
```
{
"courses": [
{
"name_courses": "ECONOMIC",
"schedule": [
{
"date": "22-01-2024",
"time": "14.00 - 15.40 ",
}
],
},
{
"name_courses": "STATISTIC",
"schedule": [
{
"date": "23-01-2024",
"time": "14.30 - 15.40 ",
}
],
}
]
}
```
I want to query Firestore to retrieve documents that have a specific date value within the nested array courses.schedule.date. For example, if I want to retrieve documents that have the date value of 23-01-2024, I want to get all documents that have an element in the courses.schedule array with the matching date value.
I am using Python with the firebase_admin module to interact with Firestore. I have tried using the array_contains and array_contains_any methods, but I have been unsuccessful in retrieving the desired documents.
I so confusing in understanding how to query nested arrays in Firestore using Firebase Admin Python. Thank you for your help and time in assisting me with this question. |
How to Querying Nested Arrays in Firestore with Firebase Admin Python |
|google-cloud-firestore|firebase-admin| |
Likely some issue with initialization order that you are missing.
Add an event into your agent type, make it trigger 0.1 sec after model start and execute your code (applying proper links back to `main` where needed).
If that does not work, do some tracelns of the code. Does it recognize everything? |
|anylogic| |
Please find below event viewer log,can anyone help me why am getting this error(sometimes)
Environment details:
* Django framework
* IIS application
* Python 3.7
```
Faulting application name: python.exe, version: 3.7.3150.1013, time stamp: 0x5c9954fa
Faulting module name: _ctypes.pyd, version: 3.7.3150.1013, time stamp: 0x5c9954c9
Exception code: 0xc0000005
Fault offset: 0x000000000000f365
Faulting process id: 0x1938
Faulting application start time: 0x01d839ca6dc31b14
Faulting application path: D:\qm_env\Scripts\python.exe
Faulting module path: d:\python37\DLLs\_ctypes.pyd
Report Id: 8701a9d7-3cc9-4a91-b8c5-ff04fb2b2a59**
Faulting package full name:
Faulting package-relative application ID:
``` |
to address your requirements, we can try with a systematic approach to ensure replicability, meet your filtering criteria, and maintain performance efficiency.
The key here is to manage the random seed progression in such a way that it allows for reproducible results across different runs while also enabling the generation of additional samples if needed.
We need to deal with the ```seed``` to ensure replicability and avoid unwanted correlations, we will use a base seed and increment it in a deterministic manner for each new block of generations :
```
base_seed = 12345
```
Now, we need to deal with efficient filtering and sampling to handle the performance aspect, especially when we are not sure how many samples to generate initially, we can use a loop that generates a certain number of samples, filters them according to your criteria, and checks if the desired number of samples has been met. If not, it continues with a new seed.
```
def generate_and_filter_samples(seed, a, num_samples_needed):
np.random.seed(seed)
samples_meet_criteria = []
while len(samples_meet_criteria) < num_samples_needed:
# Generate samples for X_1 to X_10
samples = np.random.randn(100000, 10) # Adjust size as needed
# Filter samples based on your criteria
filtered = samples[(samples[:, 0] < a) & np.all(samples[:, 1:] > a, axis=1)]
# Append to the list
if filtered.size > 0:
samples_meet_criteria.extend(filtered.tolist())
return np.array(samples_meet_criteria[:num_samples_needed])
```
Finally, we have a last problem to deal with : parallelization and performance
For performance, especially with such a large number of samples and the need for filtering, using libraries like NumPy is crucial due to its efficient array operations.
While NumPy does not directly support parallelization in the way we might run multiple processes or threads, it's highly optimized for vectorized operations, making it very fast for operations like generating and filtering large arrays of random numbers. For true parallelization, especially across multiple blocks of generation, we could consider managing separate processes with multiprocessing, each with its seed. However, combining NumPy with Numba for just-in-time compilation can significantly speed up the filtering process if it becomes complex.
```
@jit(nopython=True)
def generate_and_filter_samples(seed, a, num_samples_needed):
```
- Here, is the final code :
```
import numpy as np
from numba import jit
# Setting a base seed for reproducibility
base_seed = 12345
# Function to generate and filter samples
@jit(nopython=True)
def generate_and_filter_samples(seed, a, num_samples_needed):
np.random.seed(seed)
samples_meet_criteria = []
while len(samples_meet_criteria) < num_samples_needed:
# Generate samples for X_1 to X_10
samples = np.random.randn(100000, 10) # Adjust size as needed
# Filter samples based on your criteria
filtered = samples[(samples[:, 0] < a) & np.all(samples[:, 1:] > a, axis=1)]
if filtered.size > 0:
samples_meet_criteria.extend(filtered.tolist())
return np.array(samples_meet_criteria[:num_samples_needed])
# Criterion
a = 0.5
num_samples_needed = 5000
# Generate our samples
final_samples = generate_and_filter_samples(base_seed, a, num_samples_needed)
print(final_samples.shape)
``` |
How do I write a loop in F# such that the value of a in the previous step is now assigned to b and so on? |
|loops|f#|f#-interactive| |
null |
Because it's actually a fun problem, I wrote an algorithm that doesn't rely on building then counting permutations, but rather on mathematically calculating them;
the `count_permutations_beginning_with` function literally does what its name says, and the `build_x` function recursively builds the rank-th combination.
```
from collections import Counter
lst = [2, 2, 2, 2, 4, 4, 5, 5, 5, 6, 6, 6, 8, 8]
expected_diff = 5_617_961
initial_digits = Counter(str(d) for d in lst)
def fac(n):
return n * fac(n-1) if n else 1
def count_permutations_beginning_with(n):
digits = initial_digits.copy()
digits.subtract(n)
prod = 1
for c in digits.values():
prod *= fac(c)
return fac(digits.total()) // prod
def build_x(rank, root='', remaining_digits=None):
if remaining_digits is None:
remaining_digits = initial_digits.copy()
print (rank, root, remaining_digits)
if not remaining_digits.total():
return root
for d in remaining_digits:
if not remaining_digits[d]:
continue
if (d_quantity := count_permutations_beginning_with(root + d)) < rank:
rank -= d_quantity
else:
break
remaining_digits.subtract(d)
return build_x(rank, root + d, remaining_digits)
x_rank = (count_permutations_beginning_with('') + 1 + expected_diff) // 2
print(build_x(x_rank))
# '58225522644668'
```
|
So, if data in ***Column A*** is true date then use-
=FILTER(B2:B,A2:A>=EOMONTH(D2,-1)+1,A2:A<=EOMONTH(D2,0))
=FILTER(B2:B,A2:A>=EOMONTH(E2,-1)+1,A2:A<=EOMONTH(E2,0))
If you don't want to use cell reference then direct use `TODAY()` function inside formula so that it changes everyday.
=FILTER(B2:B,A2:A>=EOMONTH(TODAY(),-1)+1,A2:A<=EOMONTH(TODAY(),0))
And if the values are just text string in ***Column A*** then could use-
=FILTER(B2:B,MAP(A2:A,LAMBDA(x,IF(x="",,INDEX(SPLIT(x,"/"),1))))=MONTH(TODAY()))
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/YLPHY.png |
The game works fine, but its using rectangle shapes and I want to render the snake parts using Sprites. Here is the code (Yeah It's not that clean I just wanted to get this working):
```
#include <SFML/Graphics.hpp> // Graphics module
#include <SFML/Audio.hpp> // Sound module
#include <iostream> // Basic input/output (for errors)
#include <vector> // Dynamic arrays (for snake body)
#include <random> // For random food positions
class Game {
private:
sf::Vector2u windowSize; // Size of the game window
int a, b; // Length and width of a block
sf::RenderWindow window; // Window object for drawing
sf::Font font; // Text font
sf::Clock clock; // For time measurement
std::vector<sf::Vector2i> body; // Snake body (segments as coordinates)
sf::Vector2i food; // Food position
sf::Vector2i direction; // Snake direction
int score; // Player's score
bool gameOver; // Game state: finished or not
int n, m; // Number of rows and columns
float delay, timer; // Update delay and elapsed time
sf::Music eat; // Sound effect for eating
public:
Game(unsigned short x, unsigned short y); // Constructor
void start(); // Start the game
private:
void loop(); // Main game loop
void events(); // Process events (keyboard, etc.)
void update(); // Update game logic
void render(); // Render elements on screen
void gameOverScreen(); // Show "Game Over" screen
sf::Vector2i getFoodPosition(); // Generate new food position
};
int WinMain() {
Game game(800, 600);
game.start();
}
int main() {
Game game(800, 600); // Create object with window size 800x600
game.start(); // Call the start function
}
Game::Game(uint16_t x, uint16_t y) {
windowSize = { x, y }; // Save window width and height
window.create(sf::VideoMode(windowSize.x, windowSize.y, 1), "Snake");
// Create the window
a = 50; // Set block width
b = 50; // Set block height
n = windowSize.x / a; // Calculate number of horizontal blocks
m = windowSize.y / b; // Calculate number of vertical blocks
font.loadFromFile("resources/Fonts/sfpro_bold.OTF"); // Load font for text
eat.openFromFile("resources/Audio/eating_apple.mp3");
}
void Game::start() {
body.clear(); // Clear the snake body
body.push_back({ 5,3 }); // Head
body.push_back({ 4,3 }); // Body segment
body.push_back({ 3,3 }); // Tail
direction = { 0, 0 }; // Direction
food = { getFoodPosition() }; // Initial food position
gameOver = false; // Game not over (false)
score = 0; // Start score from 0
loop(); // Main loop
}
void Game::loop() {
timer = 0.f; // Accumulated time
delay = 0.125f; // Game update delay
while (window.isOpen()) {
events(); // Handle user inputs (keyboard and mouse)
timer += clock.getElapsedTime().asSeconds(); // Add elapsed time in seconds to the timer
if (timer > delay) {
update(); // Update the game (move snake, etc.)
render(); // Render the screen (blocks, snake, food, text, etc.)
timer = 0; // Reset timer
}
clock.restart(); // Restart the clock for the next cycle
}
}
void Game::events() {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape) window.close();
else if (event.key.code == sf::Keyboard::Up && (direction.y != 1)) direction = { 0, -1 };
else if (event.key.code == sf::Keyboard::Down && (direction.y != -1)) direction = { 0, 1 };
else if (event.key.code == sf::Keyboard::Left && (direction.x != 1)) direction = { -1, 0 };
else if (event.key.code == sf::Keyboard::Right && (direction.x != -1)) direction = { 1, 0 };
else if (event.key.code == sf::Keyboard::R) /*if (gameOver)*/ start();
}
}
}
void Game::update() {
if (gameOver || direction == sf::Vector2i{ 0,0 }) return;
sf::Vector2i newHead = body[0] + direction;
for (size_t i = 1; i < body.size(); i++) {
if (newHead == body[i]) {
gameOver = true;
return;
}
}
if (newHead.x > n - 1 || newHead.x < 0 || newHead.y > m - 1 || newHead.y < 0) {
gameOver = true;
return;
}
if (newHead == food) {
body.insert(body.begin(), newHead);
food = getFoodPosition();
score++;
eat.play();
}
else {
body.insert(body.begin(), newHead);
body.pop_back();
}
}
void Game::render() {
window.clear();
sf::RectangleShape block(sf::Vector2f(a, b));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
block.setPosition(i * a, j * b);
int p = (i + j) % 2;
block.setFillColor(sf::Color(172 - p * 7, 214 - p * 7, 67 - p * 7, 255));
window.draw(block);
}
}
block.setPosition(food.x * a, food.y * b);
block.setFillColor(sf::Color::Red);
window.draw(block);
for (int i = 0; i < body.size(); i++) {
if (i == 0)
block.setFillColor(sf::Color::Magenta);
else
block.setFillColor(sf::Color(0, 71, 181));
block.setPosition(body[i].x * a, body[i].y * b);
window.draw(block);
}
sf::Text scr("Score: " + std::to_string(score), font, 32);
scr.setFillColor(sf::Color::White);
scr.setPosition(4, 0);
window.draw(scr);
if (gameOver) gameOverScreen();
window.display();
}
void Game::gameOverScreen() {
eat.stop();
sf::RectangleShape screen({ float(windowSize.x), float(windowSize.y) });
screen.setPosition({ 0,0 });
screen.setFillColor(sf::Color(0, 0, 0, 100));
sf::Text gameOverText(" Game over!\nPress R to restart", font, 38);
gameOverText.setFillColor(sf::Color::White);
gameOverText.setPosition((windowSize.x / 2) - 150, (windowSize.y / 2) - 20);
window.draw(screen);
window.draw(gameOverText);
}
sf::Vector2i Game::getFoodPosition() {
std::random_device randomDevice;
std::mt19937 randomNumberGenerator(randomDevice());
std::uniform_int_distribution<int> distX(0, n - 1);
std::uniform_int_distribution<int> distY(0, m - 1);
sf::Vector2i position;
do {
position.x = distX(randomNumberGenerator);
position.y = distY(randomNumberGenerator);
if (std::find(body.begin(), body.end(), position) == body.end()) {
return position;
}
} while (true);
}
```
The code above does not have sprites functionality currently, but here is an approach I have tried (which worked for the rendering the sprites): Created a map of Textures and Sprites, loaded the textures from the files, mapped them to the Sprites, and then I had a map of Sprites ready. This part was not that hard I had flaws in my rendering logic most likely. Code was taken from when I had the sprite logic, Im basically using a string to determine which sprite I should load.
```
sf::Vector2i prev = body[i + 1]; //
sf::Vector2i next = body[i - 1]; //because i pop the tail and insert new part at the beginning
if (next.position.x == prev.position.x) {
spriteName = "body_vertical"; //vertical sprite |
}
else if (next.position.y == prev.position.y) {
spriteName = "body_horizontal"; // horizontal --
}
else {
if (prev.position.x < next.position.x) {
if (prev.position.y > next.position.y)
spriteName = "body_topright"; // start top curve right downwards
else
spriteName = "body_bottomleft"; // bottom -> left
}
else if (prev.position.y < next.position.y) {
spriteName = "body_topleft"; // top -> left
else
spriteName = "body_bottomright"; // bottom -> right
}
}
else{
if (prev.position.y > next.position.y) {
spriteName = "body_topleft"; // top -> left
else
spriteName = "body_bottomright"; // bottom -> right
}
else if (prev.position.y < next.position.y) {
spriteName = "body_topright"; // top -> right
else
spriteName = "body_bottomleft"; // bottom -> left
}
}
}
```
Link for sprites: [opengameart.org/content/snake-game-assets](https://opengameart.org/content/snake-game-assets). Basically, what I want is some feedback on how to choose the correct sprite to load and for which situation (head and tail would be appreciated too ). Thanks! |
I'm new to Docker, I want to use it with my VSCode but I found 2 extensions which are Docker and Dev Containers. To me, they're pretty similar that I couldn't find much differences between them.
Can anyone elaborate on their differences in terms of functionality and use cases?
Thank y'all.
Furthermore, I installed Docker Desktop. In its UI, there's a tab for creating Dev Environments and it lets me choose VScode as Editor for working with containers. This even confuses me more. |
what is the difference between Dev containers and Docker extension in VScode ? Also Dev Enviroments on Docker Desktop |
|docker|visual-studio-code|vscode-extensions|docker-desktop| |
null |
The game works fine, but its using rectangle shapes and I want to render the snake parts using Sprites. Here is the code (Yeah It's not that clean I just wanted to get this working):
```
#include <SFML/Graphics.hpp> // Graphics module
#include <SFML/Audio.hpp> // Sound module
#include <iostream> // Basic input/output (for errors)
#include <vector> // Dynamic arrays (for snake body)
#include <random> // For random food positions
class Game {
private:
sf::Vector2u windowSize; // Size of the game window
int a, b; // Length and width of a block
sf::RenderWindow window; // Window object for drawing
sf::Font font; // Text font
sf::Clock clock; // For time measurement
std::vector<sf::Vector2i> body; // Snake body (segments as coordinates)
sf::Vector2i food; // Food position
sf::Vector2i direction; // Snake direction
int score; // Player's score
bool gameOver; // Game state: finished or not
int n, m; // Number of rows and columns
float delay, timer; // Update delay and elapsed time
sf::Music eat; // Sound effect for eating
public:
Game(unsigned short x, unsigned short y); // Constructor
void start(); // Start the game
private:
void loop(); // Main game loop
void events(); // Process events (keyboard, etc.)
void update(); // Update game logic
void render(); // Render elements on screen
void gameOverScreen(); // Show "Game Over" screen
sf::Vector2i getFoodPosition(); // Generate new food position
};
int WinMain() {
Game game(800, 600);
game.start();
}
int main() {
Game game(800, 600); // Create object with window size 800x600
game.start(); // Call the start function
}
Game::Game(uint16_t x, uint16_t y) {
windowSize = { x, y }; // Save window width and height
window.create(sf::VideoMode(windowSize.x, windowSize.y, 1), "Snake");
// Create the window
a = 50; // Set block width
b = 50; // Set block height
n = windowSize.x / a; // Calculate number of horizontal blocks
m = windowSize.y / b; // Calculate number of vertical blocks
font.loadFromFile("resources/Fonts/sfpro_bold.OTF"); // Load font for text
eat.openFromFile("resources/Audio/eating_apple.mp3");
}
void Game::start() {
body.clear(); // Clear the snake body
body.push_back({ 5,3 }); // Head
body.push_back({ 4,3 }); // Body segment
body.push_back({ 3,3 }); // Tail
direction = { 0, 0 }; // Direction
food = { getFoodPosition() }; // Initial food position
gameOver = false; // Game not over (false)
score = 0; // Start score from 0
loop(); // Main loop
}
void Game::loop() {
timer = 0.f; // Accumulated time
delay = 0.125f; // Game update delay
while (window.isOpen()) {
events(); // Handle user inputs (keyboard and mouse)
timer += clock.getElapsedTime().asSeconds(); // Add elapsed time in seconds to the timer
if (timer > delay) {
update(); // Update the game (move snake, etc.)
render(); // Render the screen (blocks, snake, food, text, etc.)
timer = 0; // Reset timer
}
clock.restart(); // Restart the clock for the next cycle
}
}
void Game::events() {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape) window.close();
else if (event.key.code == sf::Keyboard::Up && (direction.y != 1)) direction = { 0, -1 };
else if (event.key.code == sf::Keyboard::Down && (direction.y != -1)) direction = { 0, 1 };
else if (event.key.code == sf::Keyboard::Left && (direction.x != 1)) direction = { -1, 0 };
else if (event.key.code == sf::Keyboard::Right && (direction.x != -1)) direction = { 1, 0 };
else if (event.key.code == sf::Keyboard::R) /*if (gameOver)*/ start();
}
}
}
void Game::update() {
if (gameOver || direction == sf::Vector2i{ 0,0 }) return;
sf::Vector2i newHead = body[0] + direction;
for (size_t i = 1; i < body.size(); i++) {
if (newHead == body[i]) {
gameOver = true;
return;
}
}
if (newHead.x > n - 1 || newHead.x < 0 || newHead.y > m - 1 || newHead.y < 0) {
gameOver = true;
return;
}
if (newHead == food) {
body.insert(body.begin(), newHead);
food = getFoodPosition();
score++;
eat.play();
}
else {
body.insert(body.begin(), newHead);
body.pop_back();
}
}
void Game::render() {
window.clear();
sf::RectangleShape block(sf::Vector2f(a, b));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
block.setPosition(i * a, j * b);
int p = (i + j) % 2;
block.setFillColor(sf::Color(172 - p * 7, 214 - p * 7, 67 - p * 7, 255));
window.draw(block);
}
}
block.setPosition(food.x * a, food.y * b);
block.setFillColor(sf::Color::Red);
window.draw(block);
for (int i = 0; i < body.size(); i++) {
if (i == 0)
block.setFillColor(sf::Color::Magenta);
else
block.setFillColor(sf::Color(0, 71, 181));
block.setPosition(body[i].x * a, body[i].y * b);
window.draw(block);
}
sf::Text scr("Score: " + std::to_string(score), font, 32);
scr.setFillColor(sf::Color::White);
scr.setPosition(4, 0);
window.draw(scr);
if (gameOver) gameOverScreen();
window.display();
}
void Game::gameOverScreen() {
eat.stop();
sf::RectangleShape screen({ float(windowSize.x), float(windowSize.y) });
screen.setPosition({ 0,0 });
screen.setFillColor(sf::Color(0, 0, 0, 100));
sf::Text gameOverText(" Game over!\nPress R to restart", font, 38);
gameOverText.setFillColor(sf::Color::White);
gameOverText.setPosition((windowSize.x / 2) - 150, (windowSize.y / 2) - 20);
window.draw(screen);
window.draw(gameOverText);
}
sf::Vector2i Game::getFoodPosition() {
std::random_device randomDevice;
std::mt19937 randomNumberGenerator(randomDevice());
std::uniform_int_distribution<int> distX(0, n - 1);
std::uniform_int_distribution<int> distY(0, m - 1);
sf::Vector2i position;
do {
position.x = distX(randomNumberGenerator);
position.y = distY(randomNumberGenerator);
if (std::find(body.begin(), body.end(), position) == body.end()) {
return position;
}
} while (true);
}
```
The code above does not have sprites functionality currently, but here is an approach I have tried (which worked for the rendering the sprites): Created a map of Textures and Sprites, loaded the textures from the files, mapped them to the Sprites, and then I had a map of Sprites ready. This part was not that hard I had flaws in my rendering logic most likely. Code was taken from when I had the sprite logic, Im basically using a string to determine which sprite I should load.
```
sf::Vector2i prev = body[i + 1]; //
sf::Vector2i next = body[i - 1]; //because i pop the tail and insert new part at the beginning
if (next.x == prev.x) {
spriteName = "body_vertical"; //vertical sprite |
}
else if (next.y == prev.y) {
spriteName = "body_horizontal"; // horizontal --
}
else {
if (prev.x < next.x) {
if (prev.y > next.y)
spriteName = "body_topright"; // start top curve right downwards
else
spriteName = "body_bottomleft"; // bottom -> left
}
else if (prev.y < next.y) {
spriteName = "body_topleft"; // top -> left
else
spriteName = "body_bottomright"; // bottom -> right
}
}
else{
if (prev.y > next.y) {
spriteName = "body_topleft"; // top -> left
else
spriteName = "body_bottomright"; // bottom -> right
}
else if (prev.y < next.y) {
spriteName = "body_topright"; // top -> right
else
spriteName = "body_bottomleft"; // bottom -> left
}
}
}
```
Link for sprites: [opengameart.org/content/snake-game-assets](https://opengameart.org/content/snake-game-assets). Basically, what I want is some feedback on how to choose the correct sprite to load and for which situation (head and tail would be appreciated too ). Thanks! |
Hydration failed because the initial UI does not match what was rendered on the server: Next js Tanstack table |
|reactjs|next.js|react-table|tanstack-table| |