instruction
stringlengths
0
30k
null
The only thing that comes to mind using height and overflow on exact same elements as you is `line clamp` <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> .parent { margin: 5px; max-height: 100px; max-width: 400px; background: pink; } .details { width: 100%; text-align: center; font-size: 14pt; display: grid; grid-template-rows: 1fr 1fr; } .detail1 { grid-row: 1; } .detail2 { grid-row: 2; } .common { line-height: 25px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } <!-- language: lang-html --> <div class="parent"> <div class="details"> <div class="detail1 common"> lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext </div> <div class="detail2 common"> lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext </div> </div> </div> <!-- end snippet -->
I was trying handle message from server by using rsocket-dart package in Flutter A Server send me message by fireAndForget Server is Spring boot Server Code: `@Scheduled(fixedRate = 10000) public void push() { rSocketRequester .route("api.push") .data("some push message with id " + RandomUtil.getPositiveInt()) .send() .block(); }` Is it possible handle messages like this? Or is there analog Spring annotation @MessageMapping in dart?
RSocket: How to handle fireAndForget message from server in Flutter
|spring|flutter|dart|rsocket|spring-rsocket|
null
`(a == b) & (c == d)` will return true if all of the conditions are true. Another way to express this is with [`pl.all_horizontal()`](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.all_horizontal.html#polars.all_horizontal) ```python pl.all_horizontal(a == b, c == d) ``` - [`pl.any_horizontal()`](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.any_horizontal.html#polars.any_horizontal) can be used for "logical OR" One way to pass in multiple conditions is using a comprehension: ```python predicate = pl.all_horizontal( pl.col(name) == value for name, value in row_index.items() ) df.row(by_predicate=predicate) ```
{"OriginalQuestionIds":[13618233],"Voters":[{"Id":4108803,"DisplayName":"blackgreen"}]}
I have Map in Java: Map<Pair<String, String>, MyClass> myMap; I need the Pair to **NOT** be case sensitive. The solution in case of regular string key is simple: TreeMap<String, MyClass> myMap= new TreeMap(String.CASE_INSENSITIVE_ORDER); But, what about case of strings-pair key? I need to compare `first` (left) value *case-sensitive* and then `second` (right) *case-insensitive*.
|python|deep-learning|neural-network|recurrent-neural-network|
## tl;dr Call [`List#reversed`][1] for a reversed-encounter-order view onto the original list, without changing the original. ```java Double l = lat.reversed().get(i); // A different encounter order, but *not* changing the list’s original encounter order. Double ll = lng.reversed().get(i); ``` ## `SequencedCollection#reversed` As of Java 21+, the [`List`][2] interface is a sub-interface of the new [`SequencedCollection`][3] interface. See [*JEP 431: Sequenced Collections*](https://openjdk.org/jeps/431) for details. As an implementation of `List` & `SequencedCollection`, [`ArrayList`][4] now offers the [`reversed`][1] method. This method returns a `List` object which is really a *view* onto the original list. So calling `List#reversed` does *not* alter the original list’s sequence (encounter order), in contrast to `Collections.reverse` which *does* alter the original. ```java List < Double > oneTwoThree = List.of( 1d , 2d , 3d ); List < Double > threeTwoOne = oneTwoThree.reversed( ); System.out.println( "oneTwoThree = " + oneTwoThree ); System.out.println( "threeTwoOne = " + threeTwoOne ); System.out.println( "oneTwoThree = " + oneTwoThree ); ``` When run: ```none oneTwoThree = [1.0, 2.0, 3.0] threeTwoOne = [3.0, 2.0, 1.0] oneTwoThree = [1.0, 2.0, 3.0] ``` [1]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html#reversed() [2]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html [3]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/SequencedCollection.html [4]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/ArrayList.html
Alright, so you want to: 1. Rotate the weapon in the mouse direction 2. Shoot the bullets from the weapon 3. Add a recoil force from the shot There're indeed many methods to implement this, so let me show you how I'd do it my way. I assume you haven't done it yet, so I'll try to explain as clear as I can. --- # 1. Create a player I assume you have already implemented this logic, so that's how my player looks like [![Player hierarchy][1]][1] * `Player` has a `Rigidbody2D` * `Body`, `Arm` and `Weapon` all have a `BoxCollider2D` * `Handle` is an `empty GameObject`, which has a `Weapon` inside of it. Changing the `Handle`'s `Z` rotation, rotates the `Weapon` as you want [![Player's handle][2]][2] --- # 2. Rotate the weapon in the mouse direction [![Rotate the weapon in the mouse direction][3]][3] The `α` (alpha) represents the `Z` rotation of our `handle` in `degrees`, that's the value we need to get. First, we get the `mouse position` and convert it from `screen` to `world` space. ```cs Vector2 mousePos = Input.mousePosition; Vector2 worldMousePos = _mainCamera.ScreenToWorldPoint(screenMousePos); // from screen to world space ``` `_mainCamera` will be our `Camera.main`, assigned in the `Start` method. ```cs private void Start() { _mainCamera = Camera.main; } ``` To ensure we don't have issues with performance, we store the previous mouse position as `_prevMousePos` and check if our current isn't the same. This way we don't make any useless calculations, which affect the performance. ```cs Vector2 mousePos = Input.mousePosition; if (mousePos != _prevMousePos) { // any further calculations are performed here _prevMousePos = mousePos; } ``` As I drew on the image above, we first have to calculate the `offset` between the `mouse` and `handle` positions. This gives us the `x` and `y` sides of the imaginary triangle. ```cs Vector2 offset = worldMousePos - (Vector2)transform.position; ``` Now, according to the [tangent ratio](https://www.google.com/search?sca_esv=919db838b2730857&q=tangent+ratio&source=lnms&uds=AMwkrPuGmGHzVOyOb5Id-xnvNDHTy3n3x5T-GCNPwfF-Y7VZoiqzD79MLC6-o7--582te2pqIH5K4gLFcsqjZEAmgtucpG-gSTjF7ChbVcxsqDpZJgFhb929So1H_wyQjfq2axX7bxCRee8JvuDe7r9_A-7e8zTpFcDBeXAvJOvVMSjeu0jvAZdQ2tGcrU3dwuvOeYoER3jm2yoe1n_SrfDRk2T7V639_CVw-j5FHmrgAKJrIrburlCxdEmsa72C62E1Ig7hxL8RVmJXBvvd9i702QMHMvnWElIyKkOc9N97-o64WO6oRvc&sa=X&ved=2ahUKEwiUtZOS_J6FAxUIQ_EDHWpuAHsQ0pQJegQIEhAB&biw=1536&bih=730&dpr=1.25), our formula looks like this, where `x` is `offset.x` and `y` is `offset.y`. [![tangent formula][4]][4] `tan^{-1}` is called `arc-tangent`, and there are 2 similar methods to do this. The explanations are taken from this methods' summaries. ```cs Mathf.Atan(offset.y / offset.x); // Returns the arc-tangent of f - the angle in radians whose tangent is f Mathf.Atan2(offset.y, offset.x); // Returns the angle in radians whose Tan is y/x ``` I'd suggest using `Atan2`. It returns an angle in `radians`, so we have to convert it to `degrees`, as this is what Unity's rotation eulers use. We can use `Mathf.Rad2Deg` (Unity's radians-to-degrees conversion constant). ```cs Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg; ``` Now, we can create a method which returns the distance angle in `degrees`. ```cs private float GetDistanceAngle(Transform transform, Vector2 screenMousePos) { Vector2 worldMousePos = _mainCamera.ScreenToWorldPoint(screenMousePos); Vector2 offset = worldMousePos - (Vector2)transform.position; return Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg; } ``` We rotate the `weapon` just around the `Z` axis, so we have to assign just it. This isn't possible setting `transform.rotation.z` directly, unless you know how to translate it (which you don't really need to know). We use `Quaternion.Euler` method with `Vector3.forward` multiplied by the angle, which is the same as `new Vector3(0f, 0f, angle)`, but more readable, as for me. Let's create a method out of it. ```cs private void RotateTransform(Transform transform, float angle) => transform.rotation = Quaternion.Euler(Vector3.forward * angle); ``` We can clamp the `angle` we get between the `mininum` and `maximum` values serialized in the `Inspector` as `weaponRotMin` and `weaponRotMax`. ```cs public float weaponRotMin = -90f; public float weaponRotMax = 90f; ``` ```cs float angle = Mathf.Clamp(GetDistanceAngle(weaponHandle, mousePos), weaponRotMin, weaponRotMax); ``` And so our current logic, which rotates the `weapon` in the direction of the `mouse`, looks like this. ```cs private void Update() { Vector2 mousePos = Input.mousePosition; if (mousePos != _prevMousePos) { float angle = Mathf.Clamp(GetDistanceAngle(weaponHandle, mousePos), weaponRotMin, weaponRotMax); RotateTransform(weaponHandle, angle); _prevMousePos = mousePos; } } private void RotateTransform(Transform transform, float angle) => transform.rotation = Quaternion.Euler(Vector3.forward * angle); private float GetDistanceAngle(Transform transform, Vector2 screenMousePos) { Vector2 worldMousePos = _mainCamera.ScreenToWorldPoint(screenMousePos); Vector2 offset = worldMousePos - (Vector2)transform.position; return Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg; } ``` --- # 3. Shoot the bullets from the weapon ## 3.1 Instantiate a bullet [![Shoot the bullets from the weapon][5]][5] We have to shoot, which means spawning the bullet, when the player presses the `left mouse button`. ```cs if (Input.GetMouseButtonDown(0)) // ... ``` This can be also implemented with other keys like `Space`, for instance. ```cs if (Input.GetKeyDown(KeyCode.Space)) // ... ``` We have to serialize the `bullet` and `bullet holder`, where the `bullets` are spawned, in the `Inspector`. ```cs [Header("Bullet")] [SerializeField] private Transform bullet; [SerializeField] private Transform bulletHolder; ``` We spawn the `bullet` prefab using `Instantiate` method, the 2nd parameter is the `parent` the `bullet` is spawned in. ```cs Transform newBullet = Instantiate(bullet, bulletHolder); ``` Then we have to get an `offset`, as shown on the image above. We get the `angle`, which is the `Z` position of the `bullet` and translate it from `degrees` to `radians`, as we'll have to pass it into `sin` and `cos`. Note that the it's not `rotation.z`, for the reason I've mentioned above, in the 1st header. ```cs float angle = weaponHandle.eulerAngles.z * Mathf.Deg2Rad; ``` The `diagonal`, named `PC` on the image, is the half of the `weapon` and `bullet` `lossyScales`, which, unlike the `localScale`, is in `global` coordinates. ```cs float diagonal = (weapon.lossyScale.x + bullet.lossyScale.x) * .5f; ``` Now, according to the [`cosine`](https://www.google.com/search?q=cosine+ratio&sca_esv=62807fa8b11614b1&biw=1536&bih=730&ei=RrgJZpCuKKWCxc8PxoaZoAk&ved=0ahUKEwiQ6dCAnZ-FAxUlQfEDHUZDBpQQ4dUDCBA&uact=5&oq=cosine+ratio&gs_lp=Egxnd3Mtd2l6LXNlcnAiDGNvc2luZSByYXRpbzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzIKEAAYRxjWBBiwAzINEAAYgAQYigUYQxiwAzINEAAYgAQYigUYQxiwA0jxIFD8BFj0HnADeAGQAQCYAZIBoAH7BqoBAzMuNbgBA8gBAPgBAZgCB6AC6wPCAgYQABgHGB7CAgsQABiABBiKBRiRAsICChAAGIAEGIoFGEOYAwCIBgGQBgqSBwM0LjOgB4Iq&sclient=gws-wiz-serp) and [`sine ratio`](https://www.google.com/search?q=sine+ratio&sca_esv=62807fa8b11614b1&biw=1536&bih=730&ei=S7gJZrSuM4DBxc8P8qK5uAM&ved=0ahUKEwj0_4yDnZ-FAxWAYPEDHXJRDjcQ4dUDCBA&uact=5&oq=sine+ratio&gs_lp=Egxnd3Mtd2l6LXNlcnAiCnNpbmUgcmF0aW8yBhAAGAcYHjIGEAAYBxgeMgYQABgHGB4yBhAAGAcYHjIGEAAYBxgeMgYQABgHGB4yChAAGIAEGIoFGEMyBRAAGIAEMgUQABiABDIFEAAYgARI6EhQpkNYi0hwA3gBkAEAmAFuoAHHA6oBAzQuMbgBA8gBAPgBAZgCBqAChwLCAgoQABhHGNYEGLADwgINEAAYgAQYigUYQxiwA5gDAIgGAZAGCpIHATagB4Ab&sclient=gws-wiz-serp), out formulas look like this. [![cosine formula][6]][6] [![sine formula][7]][7] And as we multiply them both by the `diagonal`, our `offset` is gotten this way. ```cs Vector2 offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * diagonal ``` In order to get position of the instantiated `bullet`, we have to add the `offset` to the `position` of the `weapon`, as shown on the image. Let us create a method for the `offset`. ```cs private Vector2 GetBulletOffset(Transform bullet, float direction) { float angle = direction * Mathf.Deg2Rad; float diagonal = (weapon.lossyScale.x + bullet.lossyScale.x) * .5f; return new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * diagonal; } ``` And now assign the new `position` of the `bullet` to the `weapon`'s `position` added to the method's result. ```cs Vector2 offset = GetBulletOffset(newBullet, direction); newBullet.position = (Vector2)weapon.position + offset; ``` Now, in order to make a `bullet` that's not a perfect circle be shot correctly, we have to rotate it as shown on the image. The `rotation` is the same as that of the `weapon`, and we can use previously created `RotateTransform` method. ```cs RotateTransform(newBullet, weaponHandle.eulerAngles.z); ``` Let's create a full method of out it, which takes the `rotation` of the `weapon` as the parameter. ```cs private void Shoot(float direction) { Transform newBullet = Instantiate(bullet, bulletHolder); Vector2 offset = GetBulletOffset(newBullet, direction); newBullet.position = (Vector2)weapon.position + offset; RotateTransform(newBullet, direction); } ``` And now the full `bullet spawn` logic looks like this. ```cs private void Update() { if (Input.GetMouseButtonDown(0)) Shoot(weaponHandle.eulerAngles.z); } private void Shoot(float direction) { Transform newBullet = Instantiate(bullet, bulletHolder); Vector2 offset = GetBulletOffset(newBullet, direction); newBullet.position = (Vector2)weapon.position + offset; RotateTransform(newBullet, direction); AddRecoilForce(offset); } private Vector2 GetBulletOffset(Transform bullet, float direction) { float angle = direction * Mathf.Deg2Rad; float diagonal = (weapon.lossyScale.x + bullet.lossyScale.x) * .5f; return new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * diagonal; } ``` ## 3.2 Make the bullet fly I assume, you already have a `bullet` `GameObject` and there's nothing hard in its creation. Just make sure not to assign a `Rigidbody2D` with the gravity enabled. We have to create a script for the `bullet`, which can be called `BulletController`. Let's assign its `speed` in the `Inspector`. ```cs public float speed = 10f; ``` Now, there are lots of ways to make it fly, so let's just use `transform.Translate` method in `Update`. The `bullet` will fly e.g. to the right, which we multiply with the `speed` and `Time.deltaTime`, to make the bullet fly with the same `speed`, regardless of the `frames per second`. ```cs private void Update() { transform.Translate(speed * Time.deltaTime * Vector2.right); } ``` It doesn't really matter, but we can add a `lifetime` field to destroy the `bullet` after the certain amount of seconds, but I am sure you can implement the desired logic yourself. With the added `BulletController` script, the `bullet` flies as soon as it is spawned in the `PlayerController` script. So an example of the `bullet` script might look like this. ```cs public class BulletController : MonoBehaviour { public float speed = 10f; public float lifetime = 3f; private void Start() => StartCoroutine(Destroy()); private void Update() { transform.Translate(speed * Time.deltaTime * Vector2.right); } private IEnumerator Destroy() { yield return new WaitForSeconds(lifetime); Destroy(gameObject); } } ``` --- # 4. Add a recoil force from the shot [![Add a recoil force from the shot][8]][8] The `recoil force` usually happens in the opposite direction of the shot. The `force` is usually applied with `Rigidbody2D.AddForce(Vector2 force)` method, so we have to assign the `Rigidbody2D` in the `Start` method first. ```cs private Rigidbody2D _rigidbody; ``` ```cs private void Start() { _rigidbody = GetComponent<Rigidbody2D>(); } ``` * If we have an `angle` of `45` `degrees`, both `x` and `y` sides of the `triangle` are `equal`, which should give us a `Vector` of `(.5, .5)`. This way, the `force` applied to the `x` and `y` axes is **the same**. * If we have an `angle` of `90` `degrees`, which `triangle` is basically a **straight line** (although it's not even a triangle), the `Vector` of `(0, 1)` is returned, giving us the `force` fully on the `y` axis, which makes the `player` jump upward (downward, in our case, as the direction is opposite) Now, I have great news for you. We have already calculated the `direction` of the `force` with this line in the `Shoot` method. ```cs Vector2 offset = GetBulletOffset(newBullet, direction); ``` Although there's a problem: the `offset` may be both: * `(10, 20)`, with a ratio of `10 / 20 = .5` * `(100, 200)`, with a ratio of `100 / 200 = .5` And even though the `ratios` are the same, the applied `force` will be 10 times greater in the second variant. That's why we use `Vector2.normalized`, which returns the `Vector` with the same `ratio`, but the maximum value of `1` (meaning 100%). So in both variants the same `Vector` of `(.5, 1)` is returned. This allows us to apply the same force to the player, regardless of the `offset`. Let's serialize the `recoilForce` field in the `Inspector`, for us to easily adjust it. ```cs public float recoilForce = 10f; ``` And create an `AddRecoilForce` method, which adds the `normalized force` multipled by `recoilForce` and `10`, to not make `recoilForce` too big. ```cs private void AddRecoilForce(Vector2 direction) => _rigidbody.AddForce(10f * recoilForce * -direction.normalized); ``` The method should be called directly in `Shoot` method with the previously assigned `offset` parameter, so it'll look like this. ```cs private void Shoot(float direction) { Transform newBullet = Instantiate(bullet, bulletHolder); Vector2 offset = GetBulletOffset(newBullet, direction); newBullet.position = (Vector2)weapon.position + offset; RotateTransform(newBullet, direction); AddRecoilForce(offset); } private void AddRecoilForce(Vector2 direction) => _rigidbody.AddForce(10f * recoilForce * -direction.normalized); ``` --- # Full code Now, the full code, with some `regions` for readability, looks like this. The `PlayerController` is assigned to the `Player`, and `BulletController` to the `Bullet` prefab. ```cs using UnityEngine; public class PlayerController : MonoBehaviour { #region Fields [Header("Values")] public float recoilForce = 10f; public float weaponRotMin = -90f; public float weaponRotMax = 90f; [Header("Body")] [SerializeField] private Transform weaponHandle; [SerializeField] private Transform weapon; private Camera _mainCamera; private Rigidbody2D _rigidbody; private Vector2 _prevMousePos; [Header("Bullet")] [SerializeField] private Transform bullet; [SerializeField] private Transform bulletHolder; #endregion private void Start() { _mainCamera = Camera.main; _rigidbody = GetComponent<Rigidbody2D>(); } private void Update() { #region Aim Vector2 mousePos = Input.mousePosition; if (mousePos != _prevMousePos) { float angle = Mathf.Clamp(GetDistanceAngle(weaponHandle, mousePos), weaponRotMin, weaponRotMax); RotateTransform(weaponHandle, angle); _prevMousePos = mousePos; } #endregion #region Shoot if (Input.GetMouseButtonDown(0)) Shoot(weaponHandle.eulerAngles.z); #endregion } /// <summary> /// Rotates the transform around its Z axis /// </summary> private void RotateTransform(Transform transform, float angle) => transform.rotation = Quaternion.Euler(Vector3.forward * angle); /// <returns> /// The angle between the transform and mouse positions /// </returns> private float GetDistanceAngle(Transform transform, Vector2 screenMousePos) { Vector2 worldMousePos = _mainCamera.ScreenToWorldPoint(screenMousePos); Vector2 offset = worldMousePos - (Vector2)transform.position; return Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg; } /// <summary> /// Spawns a bullet and applies the recoil force to the player /// </summary> private void Shoot(float direction) { Transform newBullet = Instantiate(bullet, bulletHolder); Vector2 offset = GetBulletOffset(newBullet, direction); newBullet.position = (Vector2)weapon.position + offset; RotateTransform(newBullet, direction); AddRecoilForce(offset); } /// <returns> /// The offset between the weapon and bullet positions /// </returns> private Vector2 GetBulletOffset(Transform bullet, float direction) { float angle = direction * Mathf.Deg2Rad; float diagonal = (weapon.lossyScale.x + bullet.lossyScale.x) * .5f; return new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * diagonal; } /// <summary> /// Adds a recoil force in the opposite direction /// </summary> private void AddRecoilForce(Vector2 direction) => _rigidbody.AddForce(10f * recoilForce * -direction.normalized); } ``` ```cs using UnityEngine; using System.Collections; public class BulletController : MonoBehaviour { public float speed = 10f; public float lifetime = 3f; private void Start() => StartCoroutine(Destroy()); private void Update() { transform.Translate(speed * Time.deltaTime * Vector2.right); } /// <summary> /// Destroys the bullet after lifetime seconds /// </summary> private IEnumerator Destroy() { yield return new WaitForSeconds(lifetime); Destroy(gameObject); } } ``` [1]: https://i.stack.imgur.com/5Ja2f.png [2]: https://i.stack.imgur.com/kI1DIm.png [3]: https://i.stack.imgur.com/StdA1h.png [4]: https://i.stack.imgur.com/mkW5W.png [5]: https://i.stack.imgur.com/AmdId.png [6]: https://i.stack.imgur.com/8rgTl.png [7]: https://i.stack.imgur.com/TPEoB.png [8]: https://i.stack.imgur.com/tIOi9.png
I added the following to my theme. It may also apply when using styled() MuiSnackbar: { styleOverrides: { root: { "& .MuiSnackbar-root": { padding: 0, }, "&.MuiSnackbar-root.MuiSnackbar-anchorOriginTopRight": { maxWidth: "500px", top: 76 }, "& .MuiSnackbarContent-root": { padding: 0 }, "& .MuiSnackbarContent-message": { padding: 0 } } } },
It should work like this ``` library(terra) # do not make a list red <- list.files(pattern = "red") nir <- list.files(pattern = "nir") calc_ndvi <- function(nir, red) { (nir-red)/(nir+red) } ndvi <- list() for (i in 1:9){ ndvi[[i]] <- calc_ndvi(rast(nir[i]), rast(red[i])) } ndvi <- rast(ndvi) ``` But you can also do them all at once like this ``` ndvi <- calc_ndvi(rast(nir), rast(red)) ``` Or like this ``` s <- sds(rast(red), rast(nir)) ndvi <- lapp(s, calc_ndvi) ```
Vite on production is taking assets from `http` despite APP_URL is set to `https://`. [![enter image description here][1]][1] How to resolve this in the Vite config? I can't change Laravel AppServiceProvider to force to use https because this would cause other issues. I use `@vite` directive to get resources, I can change that if needed: @vite('resources/js/app.js') I tried `vite build -- --https` but this doesn't seem to work. [1]: https://i.stack.imgur.com/iLjQX.png
I'm doing some experiments with direct manipulation of pointers to `PyObject` (and its derivated types) from Cython. Is there a tool or debugging technique that I could use to check I didn't mess up with the reference counting mechanism? Especially, I would like to know when a program terminates if I forget to `Py_DECREF` some object, causing potential memory leaks.
How to check reference counting issues when doing direct manipulations of CPython objects?
|debugging|cython|cpython|reference-counting|
Build failed. Error: Expected content key 8e22976280a5d25d to exist Error: Expected content key 8e22976280a5d25d to exist at nullthrows (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\nullthrows\nullthrows.js:7:15) at AssetGraph.getNodeIdByContentKey (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\graph\lib\ContentGraph.js:67:38) at C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\SymbolPropagation.js:52:82 at Array.map (<anonymous>) at propagateSymbols (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\SymbolPropagation.js:52:61) at AssetGraphBuilder.build (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\requests\AssetGraphRequest.js:174:62) at async Object.run (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\requests\AssetGraphRequest.js:62:37) at async RequestTracker.runRequest (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\RequestTracker.js:673:20) at async Object.run (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\requests\BundleGraphRequest.js:106:11) at async RequestTracker.runRequest (C:\Users\sonuh\OneDrive\Desktop\PetPuja\node_modules\@parcel\core\lib\RequestTracker.js:673:20) How can I solve this?
6 While creating a react app from scratch (without using create-react-app) using parcel bundler, the parcel throws the following error:
|reactjs|
null
There is some additional setup for Reanimated.You can follow steps in doc https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/getting-started/ I think you're missing ```babel.config.js``` configuration.
I use quasar framework for development. In child windows, I cannot call the code of my myWindowAPI, do you know why? In electron-preload.ts I have this function createWindow() { let x, y; const currentWindow = BrowserWindow.getFocusedWindow(); if (currentWindow) { const [currentWindowX, currentWindowY] = currentWindow.getPosition(); x = currentWindowX + 24; y = currentWindowY + 24; } let newWindow: Electron.CrossProcessExports.BrowserWindow | undefined; newWindow = new BrowserWindow({ show: false, width: 1000, height: 600, x, y, frame: false, webPreferences: { //nodeIntegration: true, contextIsolation: true, } }); //newWindow.loadURL(`file://${__dirname}/app.html`); newWindow.loadURL(process.env.APP_URL); newWindow.webContents.openDevTools(); newWindow.webContents.on('did-finish-load', () => { if (!newWindow) { throw new Error('"newWindow" is not defined'); } if (process.env.START_MINIMIZED) { newWindow.minimize(); } else { newWindow.show(); newWindow.focus(); } }); newWindow.on('closed', () => { //windows.delete(newWindow); newWindow = undefined; }); /*newWindow.on('focus', () => { const menuBuilder = new MenuBuilder(newWindow); menuBuilder.buildMenu(); });*/ //windows.add(newWindow); return newWindow; } contextBridge.exposeInMainWorld('myWindowAPI', { ajouterFenetre () { createWindow() }, envoi (data: unknown) { //BrowserWindow.getFocusedWindow()?.webContents.send('ping', data) console.log('envoi', data) ipcRenderer.send('ping', data) }, on: () => { // Deliberately strip event as it includes `sender` ipcRenderer.on('ping2', (event, data) => { console.log('recoi 1', data) }) }, recoi: (func:(data: unknown) => void) => { //if (validChannels.includes(channel)) { // Deliberately strip event as it includes `sender` return ipcRenderer.on('ping2', (event, data) => { console.log('recoi 1', data) }) //ipcRenderer.on('ping', (event, data) => func(data)) //} }, /*recoi: () => new Promise((res) => { ipcRenderer.on('ping', (ev, data) => { console.log('recoi 1', data) res(data); }); }),*/ minimize () { console.log('minimize2') //BrowserWindow.getFocusedWindow()?.minimize() }, toggleMaximize () { const win = BrowserWindow.getFocusedWindow() if (win?.isMaximized()) { win.unmaximize() } else { win?.maximize() } }, close () { BrowserWindow.getFocusedWindow()?.close() } }) In the main window, the methods myWindowAPI working but not in another window created by method createWindow. I call in my vue component the method window.myWindowAPI?.ajouterFenetre() Why is working only in main window ?
Image needs to maintain width between 50-100% and scroll if aspect ratio is greater than 2:1
|css|
I wrote code to call a function from PostgreSQL. In the pgAdmin, I call the function and it works fine. This is my code in C#: _db.Database.SqlQuery<CreateOrderInfo>($"select * from Asset_CreateOrderInfo('{request.Data!.UserId}',{request.Data!.SymbolId})") The generated command is like this: select * from Asset_CreateOrderInfo('00000001-0000-0000-0000-000000000000',2) When I run the above code in the pgAdmin, it works right. But when I send through the EF Core and C#, It doesn't work and raises this error: > Npgsql.PostgresException (0x80004005): 22P02: invalid input syntax for type uuid: "@p0" Could you help me understand what the problem is?
|c#|postgresql|entity-framework-core|
**For the bank transfer (bacs) payment method**, since the store manager manually confirms that the order is paid by changing the order status, you need to use the special ```woocommerce_order_status_changed``` hook. The status of successful orders can be changed from 1. On Hold to Processing, 2. On Hold to Completed, or 3. On Hold to Processing to Completed. **However, the action should only be fired once for each successful order.** --- I tried to achieve this by checking the payment date of the orders ```&& ! $order->get_date_paid('edit')```, but it seems not to be a working solution because a payment date is always received. ```PHP add_action( 'woocommerce_order_status_changed', 'bacs_payment_complete', 10, 4 ); function bacs_payment_complete( $order_id, $old_status, $new_status, $order ) { // 1. For Bank wire and cheque payments if( in_array( $order->get_payment_method(), array('bacs') && in_array( $new_status, array('processing', 'completed') && ! $order->get_date_paid('edit') ) { // Do something } } ```
Fire woocommerce_order_status_changed only once
|php|wordpress|woocommerce|hook-woocommerce|orders|
Whenever I run my `authorize` callback in NextAuth from my `signIn` function in my page, the result is undefined regardless of what I do. The page also refreshes immediately with the `callbackUrl` query. - I am using the [Credentials Provider](https://next-auth.js.org/configuration/providers/credentials) from NextAuth. - I am using the [App Router](https://nextjs.org/docs/app) from NextJs **This is my auth route:** ```js // app/api/auth/[...nextauth]/route.js import NextAuth from 'next-auth' import Credentials from 'next-auth/providers/credentials' const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) const handler = NextAuth({ providers: [ Credentials({ name: 'Credentials', credentials: { username: { label: 'username', type: 'text' }, password: { label: 'password', type: 'password' } }, }) ], callbacks: { async authorize(credentials) { // const { username, password } = credentials; // mocking API request (doesn't work, just refreshes immediately) await delay(3000); try { return { user: "Shiawase" }; } catch (error) { throw new Error('Failed to authenticate user'); } }, }, pages: { signIn: '/auth/login' } }); export { handler as GET, handler as POST }; ``` **And this is my login logic within my page:** ```tsx // app/auth/login/page.tsx async function onSubmit(data: z.infer<typeof FormSchema>) { setIsLoading(true); const result = await signIn('Credentials', { username: data.username, password: data.password, redirect: false }); // result is undefined console.log(result) if (result) { setIsLoading(false); console.log("Successfully logged in") setTimeout(() => { router.push('/user/dashboard/home'); }, 2000); } else { setIsLoading(false); console.log("Something unexpected occurred"); return; } } ``` - My NextJs version is `14.1.0` - My Node.Js version is `20.12.0` **I have tried:** - Upgrading my Node Version [[Here]](https://stackoverflow.com/questions/77027818/next-auth-login-not-working-with-next-js-13/77141293#77141293)
When using a Room database on an Android application, is it possible to pre-populate data
|android|kotlin|sqlite|android-room|
null
I am the admin on our Heroku account and broke my phone (MFA device). I have been locked out of our Heroku account for 2 weeks and can't get any response from Heroku support? Does anyone know a different way to contact them? Note: the support website says: "If you have lost your MFA device or are receiving "Account Not Found" when trying to log in, please email support@heroku.com from your Heroku username. Thanks in advance Nigel
How to get Heroku Support to answer an email?
|heroku|
I have a ViewPager 2 inside a plannerFragment, which calls 2 fragments: one (localeChoosingFragment) contains a recyclerview for the user to choose a locale, and another to choose places within that locale (localeExploringFragment). A ViewModel (japanGuideViewModel) stores the data (as MutableLiveData), including the int currentLocaleBeingViewed. When the user chooses a locale, this is updated, and an observer in the plannerFragment causes one of the tabs in the PlannerFragment to update with the name of that locale. Clicking that tab the loads the localeExploringFragment for that locale. When the observer in the plannerFragment is triggered, the tab is updated. This causes the recyclerview in the localeChoosingFragment to reset to the first position. As a workaround I have tried using a Handler to automatically scroll the recyclerview to the correct place (according to the ViewModel) but I am confused and concerned about why this is happening. Before using the ViewPager2, I added both (localeChoosingFragment and localeExploringFragment) to a framelayout manually, and tried show/hide and attach/detach, but had the same problem (the recyclerview resetting to the first position). Does anyone know why this could be? It seems a small thing, but I am concerned that there is something going on I don't and should know about, especially this early in the project. That ViewPager 2 is actually part of a fragment that is selected from another ViewPager 2, but I don't think that's what's causing the problem. I will attach a cleaned up version of my code. Here is the plannerFragment: public class PlannerFragment extends Fragment { Context mContext; JapanGuideViewModel japanGuideViewModel; View plannerFragmentView; ViewPager2 plannerFragmentViewPager2; TabLayout tabLayout; public static final String TAG = "JapanGuideTAG"; public PlannerFragment() { Toast.makeText(mContext, "New Planner Fragment, empty constructor", Toast.LENGTH_SHORT).show(); } public PlannerFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) { this.japanGuideViewModel = japanGuideViewModel; this.mContext = mContext; Log.d(TAG, "New Planner Fragment, arguments passed"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "oncreate in planner fragment"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "oncreateview in planner fragment"); plannerFragmentView = inflater.inflate(R.layout.fragment_planner, container, false); return plannerFragmentView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.d(TAG, "onViewCreated in PlannerFragment"); plannerFragmentViewPager2 = plannerFragmentView.findViewById(R.id.plannerFragmentViewPager2); tabLayout = plannerFragmentView.findViewById(R.id.plannerFragmentTabLayout); PlannerFragmentViewPager2Adaptor plannerFragmentViewPager2Adaptor = new PlannerFragmentViewPager2Adaptor(getChildFragmentManager(), getLifecycle(), mContext, japanGuideViewModel); plannerFragmentViewPager2.setAdapter(plannerFragmentViewPager2Adaptor); plannerFragmentViewPager2.setUserInputEnabled(false); TabLayoutMediator.TabConfigurationStrategy tabConfigurationStrategy = new TabLayoutMediator.TabConfigurationStrategy() { @Override public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) { Log.d(TAG, "onConfigure in tabConfigurationStrategy"); if (position == 0) { Log.d(TAG, "Chooser"); tab.setText("Explore Prefectures"); } else if (position == 1) { tab.setText("Explore Chosen Prefecture"); } } }; Log.d(TAG, "attachingTabLayoutMediator"); new TabLayoutMediator(tabLayout, plannerFragmentViewPager2, tabConfigurationStrategy).attach(); Observer dataDownloadedObserver = new Observer() { @Override public void onChanged(Object o) { if (japanGuideViewModel.getDataDownloaded().getValue() > 0) { Log.d(TAG, "onChanged called in data downloaded observer. Value is " + japanGuideViewModel.getDataDownloaded().getValue()); japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(0); } } }; Observer localeToExploreChangedObserver = new Observer() { @Override public void onChanged(Object o) { Log.d(TAG, "localeChangedObserver in planner fragment"); TabLayout.Tab tab = tabLayout.getTabAt(1); if (tab != null) { Log.d(TAG, "the tab is" + tab.getPosition()); tab.setText(japanGuideViewModel.getLocaleNamesArray().getValue().get(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue())); } } }; japanGuideViewModel.getCurrentLocaleBeingViewed().observe(getViewLifecycleOwner(), localeToExploreChangedObserver); japanGuideViewModel.getDataDownloaded().observe(getViewLifecycleOwner(), dataDownloadedObserver); } //onViewCreated public class PlannerFragmentViewPager2Adaptor extends FragmentStateAdapter { Context mContext; JapanGuideViewModel japanGuideViewModel; public PlannerFragmentViewPager2Adaptor(FragmentManager fragmentManager, Lifecycle lifecycle, Context mContext, JapanGuideViewModel japanGuideViewModel) { super(fragmentManager, lifecycle); this.japanGuideViewModel = japanGuideViewModel; this.mContext = mContext; Log.d(TAG, "full constructor in planner fragment"); } @NonNull @Override public Fragment createFragment(int position) { Log.d(TAG, "createFragment called in plannerFragment. Position is "); switch (position) { case 0: Log.d(TAG, "planner fragment, case 0, localechoosingfragment"); LocaleChoosingFragment localeChoosingFragment = new LocaleChoosingFragment(mContext, japanGuideViewModel); return localeChoosingFragment; case 1: Log.d("planner fragment localeExploringFragmentTAG", "case 1"); LocaleExploringFragment localeExploringFragment = new LocaleExploringFragment(mContext, japanGuideViewModel); return localeExploringFragment; default: Log.d(TAG, "default constructor so returning localeChoosingFragment"); localeChoosingFragment = new LocaleChoosingFragment(mContext, japanGuideViewModel); return localeChoosingFragment; } } @Override public int getItemCount() { return 2; } } } And here is the localeChoosingFragment: public class LocaleChoosingFragment extends Fragment { JapanGuideViewModel japanGuideViewModel; Context mContext; View localeChoosingFragmentView; public static final String TAG = "JapanGuideTAG"; RecyclerView localeChoosingRecyclerView; LinearLayoutManager recyclerViewLayoutManager; LocaleChoosingRecyclerViewAdaptor localeChoosingAdaptor; SnapHelperOneByOne SnapHelper; public LocaleChoosingFragment() { Log.d(TAG, "EMPTY constructor called for localeChoosingFragment"); } public LocaleChoosingFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) { this.japanGuideViewModel = japanGuideViewModel; this.mContext = mContext; Log.d(TAG, "constructor called for localeChoosingFragment"); Toast.makeText(mContext, "Creating a new localeChoosingFragment", Toast.LENGTH_SHORT).show(); } @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate in localeChoosingFragment"); super.onCreate(savedInstanceState); Log.d(TAG, "creating a NEW LOCALECHOOSING RECYCLERVIEW"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment Log.d(TAG, "onCreateView called in LocalChoosingFragment"); localeChoosingFragmentView = inflater.inflate(R.layout.fragment_locale_choosing, container, false); localeChoosingRecyclerView = localeChoosingFragmentView.findViewById(R.id.localeChoosingRecyclerView); return localeChoosingFragmentView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.d(TAG, "onviewcreated in locale choosing fragment."); localeChoosingAdaptor = new LocaleChoosingRecyclerViewAdaptor(mContext, japanGuideViewModel); SnapHelper = new SnapHelperOneByOne(); recyclerViewLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false); localeChoosingRecyclerView.setLayoutManager(recyclerViewLayoutManager); localeChoosingRecyclerView.setAdapter(localeChoosingAdaptor); SnapHelper.attachToRecyclerView(localeChoosingRecyclerView); // localeChoosingRecyclerView.scrollToPosition(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue()); } public class LocaleChoosingRecyclerViewAdaptor extends RecyclerView.Adapter { Context mContext; JapanGuideViewModel japanGuideViewModel; Button exploreNowButton; Button wontGoHereButton; TextView localeNameTextView; TextView localeDescriptionTextView; ImageView localePhotoImageView; TextView localePhotoCaptionTextView; public LocaleChoosingRecyclerViewAdaptor() { Log.d(TAG, "localeChoosingAdaptor created with empty constructor"); } public LocaleChoosingRecyclerViewAdaptor(Context mContext, JapanGuideViewModel japanGuideViewModel) { this.mContext = mContext; this.japanGuideViewModel = japanGuideViewModel; Log.d(TAG, "localeChoosingAdaptor created with full constructor"); } @NonNull @Override public LocaleChoosingAdaptorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Log.d(TAG, "oncreateviewholder in localechoosingfragment"); View view = LayoutInflater.from(mContext).inflate(R.layout.locale_recyclerview_holder, parent, false); return new LocaleChoosingAdaptorHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { Log.d(TAG, "onBindViewHolder called in localeChoosingFragment. The position is " + position + " and the total size is " + getItemCount()); localeNameTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview); localeNameTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(position).getLocaleName()); localeDescriptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView); if (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription() != null) { localeDescriptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription()); } localePhotoImageView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderImageView); if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().size() != 0)) { if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL() != null) && (!(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL().equals("")))) { Glide.with(mContext).load(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL()).into(localePhotoImageView); } localePhotoCaptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderPhotoCaptionTextView); if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != null) && (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != "")) { localePhotoCaptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption()); } } exploreNowButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton); wontGoHereButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton); exploreNowButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "Explore now button clicked. Setting the locale to explore to " + japanGuideViewModel.getCurrentLocaleBeingViewed().getValue()); japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(holder.getAdapterPosition()); } }); } //bind @Override public int getItemCount() { return japanGuideViewModel.getLocalesDetailsArray().getValue().size(); } } //recyclerview adaptor public class LocaleChoosingAdaptorHolder extends RecyclerView.ViewHolder { TextView localeNameTextView; TextView localeDescriptionTextView; Button exploreNowButton; Button wontGoHereButton; public LocaleChoosingAdaptorHolder(@NonNull View itemView) { super(itemView); Log.d(TAG, "localechoosing recyclerview holder consructor called"); localeNameTextView = itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview); localeDescriptionTextView = itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView); exploreNowButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton); wontGoHereButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton); } } } And here is the localeChoosingFragment: public class LocaleChoosingFragment extends Fragment { JapanGuideViewModel japanGuideViewModel; Context mContext; View localeChoosingFragmentView; public static final String TAG = "JapanGuideTAG"; RecyclerView localeChoosingRecyclerView; LinearLayoutManager recyclerViewLayoutManager; LocaleChoosingRecyclerViewAdaptor localeChoosingAdaptor; SnapHelperOneByOne SnapHelper; public LocaleChoosingFragment() { Log.d(TAG, "EMPTY constructor called for localeChoosingFragment"); } public LocaleChoosingFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) { this.japanGuideViewModel = japanGuideViewModel; this.mContext = mContext; Log.d(TAG, "constructor called for localeChoosingFragment"); Toast.makeText(mContext, "Creating a new localeChoosingFragment", Toast.LENGTH_SHORT).show(); } @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate in localeChoosingFragment"); super.onCreate(savedInstanceState); Log.d(TAG, "creating a NEW LOCALECHOOSING RECYCLERVIEW"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment Log.d(TAG, "onCreateView called in LocalChoosingFragment"); localeChoosingFragmentView = inflater.inflate(R.layout.fragment_locale_choosing, container, false); localeChoosingRecyclerView = localeChoosingFragmentView.findViewById(R.id.localeChoosingRecyclerView); return localeChoosingFragmentView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.d(TAG, "onviewcreated in locale choosing fragment."); localeChoosingAdaptor = new LocaleChoosingRecyclerViewAdaptor(mContext, japanGuideViewModel); SnapHelper = new SnapHelperOneByOne(); recyclerViewLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false); localeChoosingRecyclerView.setLayoutManager(recyclerViewLayoutManager); localeChoosingRecyclerView.setAdapter(localeChoosingAdaptor); SnapHelper.attachToRecyclerView(localeChoosingRecyclerView); // localeChoosingRecyclerView.scrollToPosition(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue()); } public class LocaleChoosingRecyclerViewAdaptor extends RecyclerView.Adapter { Context mContext; JapanGuideViewModel japanGuideViewModel; Button exploreNowButton; Button wontGoHereButton; TextView localeNameTextView; TextView localeDescriptionTextView; ImageView localePhotoImageView; TextView localePhotoCaptionTextView; public LocaleChoosingRecyclerViewAdaptor() { Log.d(TAG, "localeChoosingAdaptor created with empty constructor"); } public LocaleChoosingRecyclerViewAdaptor(Context mContext, JapanGuideViewModel japanGuideViewModel) { this.mContext = mContext; this.japanGuideViewModel = japanGuideViewModel; Log.d(TAG, "localeChoosingAdaptor created with full constructor"); } @NonNull @Override public LocaleChoosingAdaptorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Log.d(TAG, "oncreateviewholder in localechoosingfragment"); View view = LayoutInflater.from(mContext).inflate(R.layout.locale_recyclerview_holder, parent, false); return new LocaleChoosingAdaptorHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { Log.d(TAG, "onBindViewHolder called in localeChoosingFragment. The position is " + position + " and the total size is " + getItemCount()); localeNameTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview); localeNameTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(position).getLocaleName()); localeDescriptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView); if (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription() != null) { localeDescriptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription()); } localePhotoImageView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderImageView); if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().size() != 0)) { if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL() != null) && (!(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL().equals("")))) { Glide.with(mContext).load(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL()).into(localePhotoImageView); } localePhotoCaptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderPhotoCaptionTextView); if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != null) && (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != "")) { localePhotoCaptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption()); } } exploreNowButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton); wontGoHereButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton); exploreNowButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "Explore now button clicked. Setting the locale to explore to " + japanGuideViewModel.getCurrentLocaleBeingViewed().getValue()); japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(holder.getAdapterPosition()); } }); } //bind @Override public int getItemCount() { return japanGuideViewModel.getLocalesDetailsArray().getValue().size(); } } //recyclerview adaptor public class LocaleChoosingAdaptorHolder extends RecyclerView.ViewHolder { TextView localeNameTextView; TextView localeDescriptionTextView; Button exploreNowButton; Button wontGoHereButton; public LocaleChoosingAdaptorHolder(@NonNull View itemView) { super(itemView); Log.d(TAG, "localechoosing recyclerview holder consructor called"); localeNameTextView = itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview); localeDescriptionTextView = itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView); exploreNowButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton); wontGoHereButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton); } } } I was not expecting the RecyclerView in LocaleChoosingFragment to reset to the first position when the observer in the plannerFragment is trigg`your text`ered by the observer on currentLocaleBeingViewed in the View model. Everything else works as expected.
You can add it to your PATH. First evaluate the node path: sudo which node In `~/.bashrc` or `~/.zshrc`, add the line with the evaluated node path: export PATH="node_path:$PATH" In the end, you need to restart a shell or source the file.
You can use scikit image. if its a normal tiff file ``` from skimage import io my_img = io.imread('myimage.tiff') ``` Alternatively if your tiff file is a georeferenced image. You can use gdal ``` from osgeo import gdal import numpy as np ds = gdal.Open("myimage.tiff") myarr1 = np.array(ds.GetRasterBand(1).ReadAsArray()) myarr2 = np.array(ds.GetRasterBand(2).ReadAsArray()) myarr3 = np.array(ds.GetRasterBand(3).ReadAsArray()) myimage = np.dstack([myarr1, myarr2, myarr3]) ```
I recently made a bot that can play music. Now I decided to add a new functionality to it and that is playing the radio. Everything works great on my PC, but as soon as I upload it to the server. The bot connects and immediately disconnects. I used `generateDependencyReport()` to generate report. on PC i get: ``` -------------------------------------------------- Core Dependencies - @discordjs/voice: [VI]{{inject}}[/VI] - prism-media: 1.3.5 Opus Libraries - @discordjs/opus: not found - opusscript: 0.0.8 Encryption Libraries - sodium-native: not found - sodium: not found - libsodium-wrappers: 0.7.11 - tweetnacl: not found FFmpeg - version: 6.0-essentials_build-www.gyan.dev - libopus: yes -------------------------------------------------- ``` on server i get: ``` -------------------------------------------------- Core Dependencies - @discordjs/voice: [VI]{{inject}}[/VI] - prism-media: 1.3.5 Opus Libraries - @discordjs/opus: not found - opusscript: 0.0.8 Encryption Libraries - sodium-native: not found - sodium: not found - libsodium-wrappers: 0.7.11 - tweetnacl: not found FFmpeg - version: 6.0-static https://johnvansickle.com/ffmpeg/ - libopus: yes -------------------------------------------------- ``` my package.json dependencies: ``` "dependencies": { "@discordjs/voice": "^0.15.0", "cron": "^2.1.0", "discord.js": "^14.8.0", "ffmpeg-static": "^5.2.0", "firebase": "^9.12.1", "firebase-admin": "^11.2.0", "libsodium-wrappers": "^0.7.11", "node-fetch": "^2.6.1", "opusscript": "^0.0.8", "play-dl": "^1.9.6" } ``` and my bot code: [here](https://pastebin.com/8gF1ZPZ7)
I'm developing a Python application aimed at appending data to a Google Sheet via the Google Sheets API. Despite ensuring public access through the sheet's sharing settings and verifying the service account's permissions, I'm faced with HttpError 403 and HttpError 500, indicating permission issues and internal errors, respectively. The problem arises when calling the spreadsheets.values.append method using the googleapiclient library in Python. Initially, the HttpError 403 suggests a permissions issue, which is perplexing since the spreadsheet is set to public. Following this, a HttpError 500 points to an internal server error. Attempts to Resolve: Confirmed the spreadsheet's public sharing settings. Regenerated and utilized a new service account key. Checked Google Sheets API quota limits, which are within acceptable bounds. Temporarily disabled proxy settings to eliminate potential network issues. Expected Outcome: The data is appended to the designated range within the spreadsheet seamlessly. Actual Outcome: Both HttpError 403 and HttpError 500 are encountered, obstructing the data appendage process. Question: What could be the root cause of these errors, and how can they be resolved to ensure successful data appendage to my Google Sheet via the service account? Is there a permissions or configuration step I might have overlooked?
Encountering HttpError 403 and 500 When Using Google Sheets API with Service Account
I just figured out how to make a sorted table! First, you have to make sure that you don’t need a primary key in that ordered table, which is very probably the case! What you do is you do your sekect statement into a temporary table then you select the first row in the temporary table and insert it in the ordered tablethen you delete that row from the temporary table. Make sure you have a primary key in the temporary table so you can delete the row easily. And then you do that until The temporary table is empty. Let me know if that works for you.
This is being done from the command line of macOS 14 (Sonoma). Can someone explain why a parameter doesn't seem to be processed correctly in the following function. First, note that the following works fine (called directly from the command lilne), so it's not a keychain problem: # [1] succeeds codesign -f -vvvv --strict --deep --timestamp -s "Developer ID Application: My Company Inc. (123456)" --options runtime "/MyFolder/MyFile.dylib" I can also call it from a function if I hard-code the "-s" argument in the function: # [2] succeeds function myFunc() { codesign ${1} -s "Developer ID Application: My Company Inc. (123456)" ${2} } myFunc "-f -vvvv --strict --verbose --deep --timestamp --options runtime" "/MyFolder/MyFile.dylib" However, if I include the "-s" argument as a parameter, I get an error "Developer: no identity found": #[3] error: "Developer: no identity found function myFunc() { codesign ${1} ${2} echo {1} = "${1}" } myFunc "-f -vvvv --strict --verbose --deep --timestamp -s \"Developer ID Application: My Company Inc. (123456)\" --options runtime" "/MyFolder/MyFile.dylib" It's not a question of a keychain issue, because the `codesign` works in cases [1] and [2]. The result of the `echo` indicates that the parameter seems to be passed OK: {1} = -f -vvvv --strict --verbose --deep --timestamp -s "Developer ID Application: My Company Inc. (123456)" --options runtime I've tried backticks, escaping blanks, nada works. Any ideas? BTW I need this because there are many files that need to be signed & verified, I'm trying to cut down on duplication.
It's not quite "intersection over union". You care that the entire positive Ground Truth is also called positive by the model, and the same for the negative GT. So that requires "intersection over GT". ```python GT = cv.imread("GT.png", cv.IMREAD_GRAYSCALE) GT_negative = cv.inRange(GT, 100, 125) GT_positive = cv.inRange(GT, 25, 50) # GT_dontcare = cv.inRange(GT, 0, 25) subj = cv.imread("subject.png", cv.IMREAD_GRAYSCALE) (_, subj) = cv.threshold(subj, 128, 255, cv.THRESH_BINARY) def intersection_over_GT(GT, test): intersection = cv.bitwise_and(GT, test) return cv.countNonZero(intersection) / cv.countNonZero(GT) positive_ratio = intersection_over_GT(GT_positive, subj) # 0.99175 negative_ratio = intersection_over_GT(GT_negative, cv.bitwise_not(subj)) # 0.99997 ``` So there, near perfect. It's not perfect at least partly because you gave us screenshots that contain debris around the edges of the image. All those masking operations can also be accomplished with plain numpy and *boolean* arrays instead of uint8 containing 0 and 255.
Is this normal behaviour? I'm getting this with Angular 17.3 getProject is an aynchronous function that sets the projectSignal variable to project ID. But the ngOnInit is executing the if branch, and then later also the else branch, and then keeps executing the else branch 100+ times until there is a call stack failure. Shouldn't it just execute the if, or else branch just once? This wasn't an issue with Angular 17.0 **Here is the full code of the component class:** /***** Angular Imports *****/ import { Component, inject, Signal } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet, ActivatedRoute } from '@angular/router'; /***** RxJS Imports *****/ import { Subject, takeUntil } from 'rxjs'; /***** Services Imports *****/ import { SpringAPIService } from '../../services/spring-api/spring-api.service'; import { APIErrorService } from '../../services/api-error/api-error.service'; import { ProjectService } from '../../services/project-service/project.service'; /***** Child Component Imports *****/ import { AppHeaderComponent } from '../../top-navigation/app-header/app-header.component'; import { ProjectNavigationComponent } from '../../top-navigation/project-navigation/project-navigation.component'; import { ProjectDetailComponent } from '../project-detail/project-detail.component' /***** Data Transfer Object (DTO) Imports *****/ import { AnyProjectDTO } from '../../services/dto-service/dtos/ProjectDTO' /**********************************************************************************************************************/ /***************************************************** COMPONENT ******************************************************/ /**********************************************************************************************************************/ @Component({ selector: 'app-project', standalone: true, imports: [CommonModule, RouterOutlet, AppHeaderComponent, ProjectNavigationComponent, ProjectDetailComponent], templateUrl: './project-parent.component.html', styleUrl: './project-parent.component.scss', }) export class ProjectComponent { /**********************************************************************************************************************/ /***************************************************** SERVICES *******************************************************/ /**********************************************************************************************************************/ private activatedRoute: ActivatedRoute = inject(ActivatedRoute); private http: SpringAPIService = inject(SpringAPIService); private errorService = inject(APIErrorService); private projectService = inject(ProjectService) /**********************************************************************************************************************/ /***************************************************** PROPERTIES *****************************************************/ /**********************************************************************************************************************/ /* data properties */ private projectID = this.activatedRoute.snapshot.params['id']; protected isDataLoaded: boolean = false; /* subjects */ private ngUnsubscribe$: Subject<void> = new Subject<void>(); /* signal store */ protected hasErrorSignal: Signal<boolean> = this.errorService.getHasError(); protected projectSignal: Signal<AnyProjectDTO> = this.projectService.getProject() /**********************************************************************************************************************/ /************************************************** LIFE-CYCLE HOOKS **************************************************/ /**********************************************************************************************************************/ protected ngOnInit(){ // if signal store is not upto date, get project, and set it to the store if(this.projectSignal()._id != this.projectID) { console.log(this.projectSignal()._id) console.log(this.projectID) console.log("about to get project via API") this.getProject() } else { console.log("signal store already has project") console.log(this.projectSignal()._id) console.log(this.projectID) this.isDataLoaded = true; } } protected ngOnDestroy() { this.ngUnsubscribe$.next(); this.ngUnsubscribe$.complete(); } /**********************************************************************************************************************/ /****************************************************** FUNCTIONS *****************************************************/ /**********************************************************************************************************************/ // get project from API private getProject(): void { this.http.getProject(this.projectID) .pipe(takeUntil(this.ngUnsubscribe$)) .subscribe( (projectObject) => { if (projectObject != undefined){ this.projectService.setProject(projectObject) this.isDataLoaded = true; } } ) } } /**********************************************************************************************************************/ /*************************************************** END OF ANGULAR ***************************************************/ /**********************************************************************************************************************/ **Here is the template:** @defer(when isDataLoaded) { @if(!hasErrorSignal()){ <!-- app header bar --> <app-header [project]="projectSignal()"></app-header> <!-- project navigation menu --> <app-project-navigation></app-project-navigation> <!-- project page router --> <router-outlet></router-outlet> } @else { <p>Error in making Http request(s).</p> } } @placeholder { <div class="fadeIn"> <p>Initialising data fetch...</p> </div> } @loading (minimum 250ms) { <div class="fadeIn"> <p>Loading data...</p> </div> } @error { <div class="fadeIn"> <p>Something went wrong!</p> </div> } **Strange behaviour** Bizzarely, when I comment out `<router-outlet></router-outlet>,` from the template, the parent loads fine, and doesn't keep cycling through ngOnInit. OR When I comment out <!-- app header bar --> <app-header [project]="projectSignal()"></app-header> <!-- project navigation menu --> <app-project-navigation></app-project-navigation> but leave the `<router-outlet></router-outlet>,` in, then it also works. Any ideas? Sorry I don't know how to use StackBlitz. **UPDATE:** if inside getProject I do this, I still get the infinite looping private getProject(): void { console.log("test") this.isDataLoaded = true } **UPDATE - 2** What I've discovered: ngOnInit Infinite loops stops when: - include only, `<app-header [project]="projectSignal()"></app-header>` and `<app-project-navigation></app-project-navigation>` - include only, `<router-outlet></router-outlet>` - keep all three, but remove the deferrable view block. - replace the deferrable view, with an if block resolves the issue - It definitely looks like some change detection bug in Angular 17.3 **UPDATE - 3** - Infact, ignoring ngOnInit entirely, and setting isDataLoaded = true, instead of false, on initialisation, also causes the repetitive loading of the components: `<app-header [project]="projectSignal()"></app-header>` and `<app-project-navigation></app-project-navigation>`, when `<router-outlet></router-outlet>` is also there. (Commenting out `<router-outlet></router-outlet>`, or commenting out `<app-header [project]="projectSignal()"></app-header>` and `<app-project-navigation></app-project-navigation>`, but not `<router-outlet></router-outlet>`, still resolves the issue - but then I don't have the three components I need) **UPDATE STACKBLITZ** Here is what I managed to put onto Stackblitz All the code is there (though I have the issue on Angular 17.3) https://stackblitz.com/edit/stackblitz-starters-aeguwd?file=src%2Fproject-parent%2Fproject-parent.routes.ts **UPDATE - DEFER BLOCK*** This, I discovered also works with no issues, components in separate defer blocks, but it is far from ideal... @defer(when isDataLoaded) { <!-- app header bar --> <app-header [project]="projectSignal()"></app-header> } @defer(when isDataLoaded) { <!-- project navigation menu --> <app-project-navigation></app-project-navigation> } @defer(when isDataLoaded) { @if(!hasErrorSignal()){ <!-- project-parent page router --> <router-outlet></router-outlet> } @else { <p>Error in making Http request(s).</p> } } @placeholder { <div class="fadeIn"> <p>Initialising data fetch...</p> </div> } @loading (minimum 250ms) { <div class="fadeIn"> <p>Loading data...</p> </div> } @error { <div class="fadeIn"> <p>Something went wrong!</p> </div> }
|sqlclr|oracle-data-integrator|
Ansible facts (and variables - which are almost, but not exactly the same thing) are belonging to a host. There is no such concept as a global variable in Ansible (except the magic, or special, variables that behave in a different way) - in the end, all the variables are flattened to the host level. That means, that your `interval` is actually unique for each host, so you're incrementing the same variable, but in distinct manner for each host of `cluster` group. Your question doesn't contain enough information to suggest the solution, because it would depend on what you actually want to achieve. Just a couple of examples: - If you simply need different fixed values of the same variable for different hosts, you can set them in your inventory on host level. - If you need a variable to depend on the host order and the difference should be fixed somehow mathemacally, you can set `interval: "{{ groups['cluster'].index(inventory_hostname) * 10 }}` on `cluster` group level. But keep in mind that this order is not guaranteed to be the same on different executions of the playbook, or when the hosts are added/removed. - If you need to iterate over the list of hosts and generate some values based on the discovered facts, you will need to collect them first, and then process them in a different task/play, possibly on a different host (in example, `localhost` as the control node, using `delegate_to`, `delegate_facts`, or operating `hostvars['localhost']` if you need the variable to be single).
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 and to join the characters: df['x'] = pd.Series(map(''.join, df[x_list].values.astype(str).tolist())) giving: x1 x2 x3 y x 0 A D G 10 ADG 1 B E H 11 BEH 2 C F I 12 CFI
Bash function parameters conundrum
|bash|macos|command-line|
> Why am I getting this error ? error CS0103: The name 'EnhancedStackTrace' does not exist in the current context You are getting this error because the compiler/visual studio cannot locate a type named `EnhancedStackTrace` in your program code or within any referenced assembly (dll). If I assume that the maintainer of that repo keeps it in a working state, then I would suggest going through the steps in the [Developer Guide][1] and make sure you execute each of them. If you skipped any, or if any of them had a problem when running, then that could mean that some necessary assembly was not downloaded/built/installed which would cause the error you are seeing. Also, the `EnhancedStackTrace` in the C# code and the `EnhancedStackTrace` in the C++ code could be (and very likely are) two different type definitions that just share a name, like `integer` or `string`. [1]: https://github.com/citizenfx/fivem/blob/master/docs/building.md
use the following: python setup.py install --prefix=<path to where you want to install the package>
|cuda|gpu|side-channel-attacks|
The date format is `dd-mm-yyyy` (it's the format here in Portugal), and the hour is `hh:mm`. My code is this: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> struct DateTime { int day, month, year, hour, minute; }; // Function to convert date and time to minutes since midnight int minutes_since_midnight(struct DateTime dt) { return dt.hour * 60 + dt.minute; } // Function to calculate time difference int calculate_time_difference(char date_in[], char time_in[], char date_out[], char time_out[]) { struct DateTime dt1, dt2; sscanf(date_in, "%d-%d-%d", &dt1.day, &dt1.month, &dt1.year); sscanf(time_in, "%d:%d", &dt1.hour, &dt1.minute); sscanf(date_out, "%d-%d-%d", &dt2.day, &dt2.month, &dt2.year); sscanf(time_out, "%d:%d", &dt2.hour, &dt2.minute); // Convert date and time to minutes since midnight int minutes1 = minutes_since_midnight(dt1); int minutes2 = minutes_since_midnight(dt2); // Calculate total difference in minutes int time_difference = abs(minutes2 - minutes1); // Calculate day difference in minutes int day_difference = dt2.day - dt1.day; // If the date of departure is before the date of arrival, adjust the day difference if (day_difference < 0) { // Add a full day of minutes day_difference += 1; // Add the remaining hours of the departure day time_difference += (24 - dt1.hour) * 60 + (60 - dt1.minute); // Add the hours of the arrival day time_difference += dt2.hour * 60 + dt2.minute; } else { // If the date of departure is after the date of arrival, just add the remaining minutes time_difference += day_difference * 24 * 60; } return time_difference; } int main() { int time_diff = calculate_time_difference("01-01-2024", "19:05", "02-01-2024", "9:05"); printf("Time difference->%i\n", time_diff); return 0; } ``` As you can see from the example in `main`, in the case where input 1 = `"01-01-2024", "19:05"` and input 2 = `"02-01-2024", "9:05"` the time difference in minutes should be `840` (14 hours * 60 minutes). The code when I run it says: `Time difference->2040`. How can I fix this? Ignore leap years for this example.
|java|string|compare|case-insensitive|
I want to install Redis Vector DB in GCP running on GKE cluster. I am not sure on how to start the process and complete the installation. I have seen the steps shared in langchain framework to install and run the redis vector locally using this command. docker run -d -p 6379:6379 -p 8001:8001 redis/redis-stack:latest But I want to do the setup in a GKE cluster so that I can connect to the vector DB and store embeddings. Please share any step-by-step approach that I can follow to perform this setup.
Install redis vector database on GCP in a GKE cluster
|redis|vector-database|
null
Can you try `flush` to ensure the message is sent immediately and `close` function? import json from kafka import KafkaProducer def main(): bootstrap_servers = 'localhost:34715' topic = 'dev' message = {'message': 'Hello from the producer'} try: producer = KafkaProducer( bootstrap_servers=bootstrap_servers, value_serializer=lambda v: json.dumps(v).encode('utf-8') ) print("Successful connection to Kafka server at:", bootstrap_servers) producer.send(topic, value=message) print("Message sent successfully to topic:", topic) # Flush the producer to ensure the message is sent producer.flush() except Exception as e: print("Error sending message:", e) finally: # Close the producer producer.close() if __name__ == '__main__': main()
I faced the same problem while using Country Code Picker, In my case I need only 2 countries, so I created a static JSON export const CountryCodes = [ { label: "+91", value: "91", flag: INDIA_FLAG, name: "India", flag_string: "", }, { label: "+1", value: "1", flag: US_FLAG, name: "United States", flag_string: "", } ] and then I created a Custom Component `RadioButtonCountryCodeSelector` interface Item { label: string; value: string; flag: any; name: string; } interface RadioProps { value : string; disabled? : boolean; onPress?(value: any): void; style?: StyleProp<ViewStyle>; title: string; length?: number; item?: any; } const RadioButtonCountryCodeSelector: FC<RadioProps> = (props) => { const theme = setThemeJSON(); const { disabled = false, style, value, onPress, length = 0, item } = props; return ( <View style={[style, shadowStyle, { elevation: 10, width: '100%', opacity: disabled ? 0.4 : 1, borderWidth: 0, backgroundColor: '#ffffff', shadowColor: 'transparent', borderRadius: 0, marginTop: 0, borderColor: 'transparent', }]}> <TouchableWithoutFeedback disabled={disabled} onPress={() => onPress && onPress(value)} > <View style={{ paddingHorizontal: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', margin: 10 }}> <Image source={item?.flag} style={{ height: 25, width: 25 }} resizeMode={resizeMode.contain}/> <TextComponent fontSize={14} fontFamily={MontserratSemiBold} //checked ? MontserratSemiBold : MontserratMedium} color={theme?.theme?.DEFAULT_TEXT_COLOR } styles={{ letterSpacing: 1.1 }} value={item?.name}/> <TextComponent fontSize={14} fontFamily={MontserratSemiBold} //checked ? MontserratSemiBold : MontserratMedium} color={theme?.theme?.DEFAULT_TEXT_COLOR } styles={{ letterSpacing: 1.1 }} value={props.title}/> </View> </TouchableWithoutFeedback> </View> ) }; const styles = StyleSheet.create({ radio: { alignItems: 'center', justifyContent: 'center', }, item: { marginLeft: 5, alignItems: 'center', justifyContent: 'center', } }); export default RadioButtonCountryCodeSelector; and then Implemented the above component as <RadioGroup onValueChange={async (value) => { setSelected(value); if (value && value !== selected) { hideModel(value); } } } selectedValue={selected} > { CountryCodes && CountryCodes.map((item, index) => { return <RadioButtonCountryCodeSelector key={index} item={item} value={item?.value} title={item?.label} length={CountryCodes.length} /> }) } </RadioGroup>
Discord bot cannot play radio
|javascript|discord.js|
null
Here's another easy way to add truly empty columns to your query. [enter image description here][1] =query(A:E;"SELECT Col1, 1/0, Col2, 2/0 label 1/0 'blank', 2/0 'blank'";1) , where 1/0 and 2/0 (any number divided by zero) result in empty columns [1]: https://i.stack.imgur.com/BBgaa.png
Coding a two-dimensional, dynamically allocated array of `int` is a non-trivial task. If you use a _double pointer_, there are significant memory allocation details. In particular, you need to check every allocation attempt, and, if any one fails, back out of the ones that didn't fail, without leaking memory. And, finally, to take a term from the C++ lexicon, you need to provide some equivalent of the _Rule of Three_ functions used by a C++ _RAII_ class. A two-dimensional array of `int` with `n_rows` and `n_cols` should probably be allocated with a single call to `malloc`: ```lang-c int* data = malloc(n_rows * n_cols * sizeof int); ``` With this approach, you have to write indexing functions that accept both `row` and `col` subscripts. The program in the OP, however, takes the _double pointer_ route, and allocates an _array of pointers to int_. The elements in such an array are `int*`. Thus, the array is an _array of pointers to rows_, where each row is an _array of `int`_. The argument to the `sizeof` operator, therefore, must be `int*`. ```lang-c int** data = malloc(n_rows * sizeof (int*)); // step 1. ``` Afterwards, you run a loop to allocate the columns of each row. Conceptually, each row is an array of `int`, with `malloc` returning a pointer to the first element of each row. ```lang-c for (size_t r = 0; r < n_rows; ++r) data[r] = malloc(n_cols * sizeof int); // step 2. ``` The program in the OP errs in step 1. ```lang-c // from the OP: ret = (int **)malloc(sizeof(int) * len); // should be sizeof(int*) ``` Taking guidance from the [answer by @Eric Postpischil](https://stackoverflow.com/a/78248309/22193627), this can be coded as: ```lang-c int** ret = malloc(len * sizeof *ret); ``` The program below, however, uses (the equivalent of): ```lang-c int** ret = malloc(len * sizeof(int*)); ``` #### Fixing memory leaks The program in the OP is careful to check each call to `malloc`, and abort the allocation process if any one of them fails. After a failure, however, it does not call `free` to release the allocations that were successful. Potentially, therefore, it leaks memory. It should keep track of the row where a failure occurs, and call `free` on the preceding rows. It should also call `free` on the original array of pointers. There is enough detail to warrant refactoring the code to create a separate header with functions to manage a two-dimensional array. This separates the business of array management from the application itself. Header `tbx.int_array2D.h`, defined below, provides the following functions. - _Struct_ – `struct int_array2D_t` holds a `data` pointer, along with variables for `n_rows` and `n_cols`. - _Make_ – Function `make_int_array2D` handles allocations, and returns a `struct int_array2D_t` object. - _Free_ – Function `free_int_array2D` handles deallocations. - _Clone_ – Function `clone_int_array2D` returns a _deep copy_ of a `struct int_array2D_t` object. It can be used in initialization expressions, but, in general, should not be used for assignments. - _Swap_ – Function `swap_int_array2D` swaps two `int_array2D_t` objects. - _Copy assign_ – Function `copy_assign_int_array2D` replaces an existing `int_array2D_t` object with a _deep copy_ of another. It performs allocation and deallocation, as needed. - _Move assign_ – Function `move_assign_int_array2D` deallocates an existing `int_array2D_t` object, and replaces it with a _shallow copy_ of another. After assignment, it zeros-out the source. - _Equals_ – Function `equals_int_array2D` performs a _deep comparison_ of two `int_array2D_t` objects, returning `1` when they are equal, and `0`, otherwise. ```lang-c #pragma once // tbx.int_array2D.h #include <stddef.h> struct int_array2D_t { int** data; size_t n_rows; size_t n_cols; }; void free_int_array2D( struct int_array2D_t* a); struct int_array2D_t make_int_array2D( const size_t n_rows, const size_t n_cols); struct int_array2D_t clone_int_array2D( const struct int_array2D_t* a); void swap_int_array2D( struct int_array2D_t* a, struct int_array2D_t* b); void copy_assign_int_array2D( struct int_array2D_t* a, const struct int_array2D_t* b); void move_assign_int_array2D( struct int_array2D_t* a, struct int_array2D_t* b); int equals_int_array2D( const struct int_array2D_t* a, const struct int_array2D_t* b); // end file: tbx.int_array2D.h ``` #### A trivial application With these functions, code for the application becomes almost trivial. I am not sure why the OP wrote his own version of `strlen`, but I went with it, changing only the type of its return value. ```lang-c // main.c #include <stddef.h> #include <stdio.h> #include "tbx.int_array2D.h" size_t ft_strlen(char* str) { size_t count = 0; while (*str++) count++; return (count); } struct int_array2D_t parray(char* str) { size_t len = ft_strlen(str); struct int_array2D_t ret = make_int_array2D(len, 2); for (size_t r = ret.n_rows; r--;) { ret.data[r][0] = str[r] - '0'; ret.data[r][1] = (int)(len - 1 - r); } return ret; } int main() { char* str = "1255555555555555"; struct int_array2D_t ret = parray(str); for (size_t r = 0; r < ret.n_rows; ++r) { printf("%d %d \n", ret.data[r][0], ret.data[r][1]); } free_int_array2D(&ret); } // end file: main.c ``` #### Source code for tbx.int_array2D.c Function `free_int_array2D` has been designed so that it can be used for the normal deallocation of an array, such as happens in function `main`, and also so that it can be called from function `make_int_array2D`, when an allocation fails. Either way, it sets the `data` pointer to `NULL`, and both `n_rows` and `n_cols` to zero. Applications that use header `tbx.int_array2D.h` can check the `data` pointer of objects returned by functions `make_int_array2D`, `clone_int_array2D`, and `copy_assign_int_array2D`. If it is `NULL`, then the allocation failed. ```lang-c // tbx.int_array2D.c #include <stddef.h> #include <stdlib.h> #include "tbx.int_array2D.h" //====================================================================== // free_int_array2D //====================================================================== void free_int_array2D(struct int_array2D_t* a) { for (size_t i = a->n_rows; i--;) free(a->data[i]); free(a->data); a->data = NULL; a->n_rows = 0; a->n_cols = 0; } //====================================================================== // make_int_array2D //====================================================================== struct int_array2D_t make_int_array2D( const size_t n_rows, const size_t n_cols) { struct int_array2D_t a = { malloc(n_rows * sizeof(int*)), n_rows, n_cols }; if (!n_rows || !n_cols) { free(a.data); a.data = NULL; a.n_rows = 0; a.n_cols = 0; } else if (a.data == NULL) { a.n_rows = 0; a.n_cols = 0; } else { for (size_t i = 0u; i < n_rows; ++i) { a.data[i] = malloc(n_cols * sizeof(int)); if (a.data[i] == NULL) { a.n_rows = i; free_int_array2D(&a); break; } } } return a; } //====================================================================== // clone_int_array2D //====================================================================== struct int_array2D_t clone_int_array2D(const struct int_array2D_t* a) { struct int_array2D_t clone = make_int_array2D(a->n_rows, a->n_cols); for (size_t r = clone.n_rows; r--;) { for (size_t c = clone.n_cols; c--;) { clone.data[r][c] = a->data[r][c]; } } return clone; } //====================================================================== // swap_int_array2D //====================================================================== void swap_int_array2D( struct int_array2D_t* a, struct int_array2D_t* b) { struct int_array2D_t t = *a; *a = *b; *b = t; } //====================================================================== // copy_assign_int_array2D //====================================================================== void copy_assign_int_array2D( struct int_array2D_t* a, const struct int_array2D_t* b) { if (a->data != b->data) { if (a->n_rows == b->n_rows && a->n_cols == b->n_cols) { for (size_t r = a->n_rows; r--;) { for (size_t c = a->n_cols; c--;) { a->data[r][c] = b->data[r][c]; } } } else { free_int_array2D(a); *a = clone_int_array2D(b); } } } //====================================================================== // move_assign_int_array2D //====================================================================== void move_assign_int_array2D( struct int_array2D_t* a, struct int_array2D_t* b) { if (a->data != b->data) { free_int_array2D(a); *a = *b; b->data = NULL; b->n_rows = 0; b->n_cols = 0; } } //====================================================================== // equals_int_array2D //====================================================================== int equals_int_array2D( const struct int_array2D_t* a, const struct int_array2D_t* b) { if (a->n_rows != b->n_rows || a->n_cols != b->n_cols) { return 0; } for (size_t r = a->n_rows; r--;) { for (size_t c = a->n_cols; c--;) { if (a->data[r][c] != b->data[r][c]) { return 0; } } } return 1; } // end file: tbx.int_array2D.c ```
You can add it to your PATH. First evaluate the node path: sudo which node In `~/.bashrc` or `~/.zshrc`, add the line with the evaluated `node_path`: export PATH="node_path:$PATH" In the end, you need to restart a shell or source the file.
How can I lock a rigidbody's rotation on all axis? Bullet Physics
Is it possible to write a Chrome/Firefox plug-in that can automatically open the dev tools for every open tab and execute code in the console? I have already done this with Selenium, but I would like to have it as a plug-in. Unfortunately, I haven't found a chrome api yet that allows you to automatically insert and execute code in devtools. I would be very grateful to anyone who could help me get a step closer. PS:Since I don't add the plugin to the store, developer API's or other unconventional alternatives can also be used.
The VCALENDAR object, as supplied, is not strictly valid: the EXDATE property must have one or more date-time or date values (see [3.8.5.1. Exception Date-Times](http://icalendar.org/iCalendar-RFC-5545/3-8-5-1-exception-date-times.html)). Despite that, *vobject* parses the data successfully, ending up with an empty list of exceptions in the VEVENT object. To get the list of occurrences, try: >>> s = "BEGIN:VCALENDAR ... END:VCALENDAR" >>> ical = vobject.readOne(s) >>> rrule_set = ical.event.getrruleset() >>> print(list(rrule_set)) [datetime.datetime(2011, 3, 25, 8, 0), datetime.datetime(2011, 3, 26, 8, 0), datetime.datetime(2011, 3, 27, 8, 0), datetime.datetime(2011, 3, 28, 8, 0), datetime.datetime(2011, 3, 29, 8, 0), datetime.datetime(2011, 3, 30, 8, 0)] >>> If we add a valid EXDATE property value, like EXDATE:20110327T080000 re-parse the string, and examine the RRULE set again, we get: >>> list(ical.vevent.getrruleset()) [datetime.datetime(2011, 3, 25, 8, 0), datetime.datetime(2011, 3, 26, 8, 0), datetime.datetime(2011, 3, 28, 8, 0), datetime.datetime(2011, 3, 29, 8, 0), datetime.datetime(2011, 3, 30, 8, 0)] >>> which is correctly missing the 27th March, as requested. (Apologies for the 13 year delay in responding. I hope this might help someone, someday!)
I have access to 2 nodes, each has 2 GPUs. I want to have 4 processes, each has a GPU. I use `nccl` (if this is relevant). Here is the Slurm script I tried. I tried different combinations of setup. It works occasionally as wanted. Most of time, it creates 4 processes in 1 node, and allocate 2 processes to 1 GPU. It slows down the program and cause out of memory, and makes `all_gather` fail. How can I distribute processes correctly? ``` #!/bin/bash #SBATCH -J jobname #SBATCH -N 2 #SBATCH --cpus-per-task=10 # version 1 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 #SBATCH --gpu-bind=none # version 2 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 # version 3 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 # version 4 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 #SBATCH --gpus-per-task=1 # # version 5 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=2 #SBATCH --gpus-per-task=1 module load miniconda3 eval "$(conda shell.bash hook)" conda activate gpu-env nodes=( $( scontrol show hostnames $SLURM_JOB_NODELIST) ) nodes_array=($nodes) head_node=${nodes_array[0]} head_node_ip=$(srun --nodes=1 --ntasks=1 -w "$head_node" hostname --ip-address) echo Node IP: $head_node_ip export LOGLEVEL=INFO export NCCL_P2P_LEVEL=NVL srun torchrun --nnodes 2 --nproc_per_node 2 --rdzv_id $RANDOM --rdzv_backend c10d --rdzv_endpoint $head_node_ip:29678 mypythonscript.py ```
methods in contextBridge not working in child window
|vue.js|electron|
null
`GetBitLength` is [documented](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger.getbitlength?view=net-8.0) as: > Gets the number of bits required for shortest two's complement representation of the current instance without the sign bit. And also, helpfully: > For positive integers the return value is equal to the ordinary binary representation string length. Now, consider two (very small) `BigInteger` values - 1 and 3. It only takes 1 bit to represent the integer value 1, whereas it takes 2 bits to represent the integer 3. Effectively, any leading 0 bits which might have been passed in the original byte array aren't included in `GetBitLength()`. I suspect that's absolutely fine for you, but it will definitely depend on what you're planning to do with the result. To put it another way: if you only wanted 4 bit numbers, would you want values between 0 and 15 inclusive, or between 8 and 15 inclusive? Because requiring `GetBitLength()` to return 4 would make you generate the latter... (That's effectively "3 random bits and a leading bit that's always 1".)
|typescript|deno|freshjs|
## Next.js (SSR) If you are using a modern React framework like [Next.js](https://nextjs.org/) that supports SSR, dynamically importing SVG is very easy. The following guide demonstrates the concept, which should be applicable for any other frameworks that support SSR. Assuming SVG files are placed in assets folder: ```bash ├── src │   └── assets │   ├── a-b-2.svg │   └── a-b-off.svg ``` 1. Install [`@svgr/webpack`](https://react-svgr.com/docs/next/) (or any other SVG loader of your choice), which allow you to import SVG files directly and use them as React components. \*Feel free to skip this step if you already have a loader in place. 1. Add a `src/components/lazy-svg.tsx` async component. ```tsx import { ComponentProps } from "react"; import dynamic from "next/dynamic"; interface LazySvgProps extends ComponentProps<"svg"> { name: string; } export const LazySvg = async ({ name, ...props }: LazySvgProps) => { const Svg = dynamic(() => import(`@/assets/${name}.svg`)); // Or without using `dynamic`: // We use `default` here because `@svgr/webpack` converts all other *.svg imports to React components, this might be different for other loaders. // const Svg = (await import(`@/assets/${name}.svg`)).default; return <Svg {...props} />; }; ``` 1. Import and use it as follows: ```tsx import { LazySvg } from "@/components/lazy-svg"; // Server side: <LazySvg name="a-b-2" /> // Client side: Wrap with Suspense to render loading state when SVG is loading. <Suspense fallback={<>Loading...</>}> <LazySvg name="a-b-2" /> </Suspense> ``` ### Usages #### Server Demo ```tsx import { LazySvg } from "@/components/lazy-svg"; export const ServerDemo = () => ( <div> <LazySvg name="a-b-2" stroke="yellow" /> <LazySvg name="a-b-off" stroke="lightgreen" /> </div> ); ``` #### Client Demo ```tsx "use client"; import { Suspense, useState } from "react"; import { LazySvg } from "@/components/lazy-svg"; export const ClientDemo = () => { const [name, setName] = useState<"a-b-2" | "a-b-off">("a-b-2"); return ( <div> <button onClick={() => setName((prevName) => (prevName === "a-b-2" ? "a-b-off" : "a-b-2")) } > Change Icon </button> <Suspense fallback={<>Loading...</>}> <LazySvg name={name} stroke={name === "a-b-2" ? "yellow" : "lightgreen"} /> </Suspense> </div> ); }; ``` [![Edit nextjs-dynamic-svg-import](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/edit/nextjs-dynamic-svg-import?file=components%2Flazy-svg.tsx) ## Vite React (SPA) If you are not using SSR, you can dynamically import SVG files using the dynamic import hook. The following guide demonstrates the concept, which should be applicable for any other frameworks that use SPA. Assuming SVG files are placed in assets folder: ```bash ├── src │   └── assets │   ├── a-b-2.svg │   └── a-b-off.svg ``` 1. Install [`vite-plugin-svgr`](https://github.com/pd4d10/vite-plugin-svgr) (or any other SVG loader of your choice), which allow you to import SVG files directly and use them as React components. \*Feel free to skip this step if you already have a loader in place. 1. Add a `src/components/lazy-svg.tsx` component. ```tsx import { ComponentProps, FC, useEffect, useRef, useState } from "react"; interface LazySvgProps extends ComponentProps<"svg"> { name: string; } // This hook can be used to create your own wrapper component. const useLazySvgImport = (name: string) => { const importRef = useRef<FC<ComponentProps<"svg">>>(); const [loading, setLoading] = useState(false); const [error, setError] = useState<Error>(); useEffect(() => { setLoading(true); const importIcon = async (): Promise<void> => { try { importRef.current = ( await import(`../assets/${name}.svg?react`) ).default; // We use `?react` here following `vite-plugin-svgr`'s convention. } catch (err) { setError(err as Error); } finally { setLoading(false); } }; importIcon(); }, [name]); return { error, loading, Svg: importRef.current, }; }; // Example wrapper component using the hook. export const LazySvg = ({ name, ...props }: LazySvgProps) => { const { loading, error, Svg } = useLazySvgImport(name); if (error) { return "An error occurred"; } if (loading) { return "Loading..."; } if (!Svg) { return null; } return <Svg {...props} />; }; ``` ### Usage ```tsx import { useState } from "react"; import { LazySvg } from "./components/lazy-svg"; function App() { const [name, setName] = useState<"a-b-2" | "a-b-off">("a-b-2"); return ( <main> <button onClick={() => setName((prevName) => (prevName === "a-b-2" ? "a-b-off" : "a-b-2")) } > Change Icon </button> <LazySvg name={name} stroke={name === "a-b-2" ? "yellow" : "lightgreen"} /> </main> ); } export default App; ``` [![Edit vite-react-ts-dynamic-svg-import](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/edit/vite-react-ts-dynamic-svg-import?file=src%2Fcomponents%2Flazy-svg.tsx) ## Create React App (SPA) [*Deprecated*] The majority of Vite's [guide](#vite-react-spa) applies, with the only difference being on the `import` method: ```ts const useLazySvgImport = (name: string) => { const importRef = useRef<FC<ComponentProps<"svg">>>(); const [loading, setLoading] = useState(false); const [error, setError] = useState<Error>(); useEffect(() => { setLoading(true); const importIcon = async (): Promise<void> => { try { importRef.current = ( await import(`../assets/${name}.svg`) ).ReactComponent; // CRA comes pre-configured with SVG loader, see https://create-react-app.dev/docs/adding-images-fonts-and-files/#adding-svgs. } catch (err) { setError(err as Error); } finally { setLoading(false); } }; importIcon(); }, [name]); return { error, loading, Svg: importRef.current, }; }; ``` ## Caveats There’s limitation when using dynamic imports with variable parts. This [answer](https://stackoverflow.com/a/54257036/11125492) explained the issue in detail. To workaround with this, you can make the dynamic import path to be more explicit. E.g, Instead of ```tsx <LazySvg path="../../assets/icon.svg" />; // ... import(path); ``` You can change it to ```tsx <LazySvg name="icon" />; // ... import(`../../icons/${name}.svg`); ```
|python|excel|openpyxl|python-datetime|
I want to make a HTML,CSS,JS app in which you can enter you face image, and it will give you all the image in which your face is present i want to do this in frontend , pls tell how to implement it , I had used face-api and other tools but nothing worked ? Please tell any resource or code to make it also it should be very minimal .... Answer and suggestions to complete it or some code or guidance
How to make image recognition classifier in frontend html,css,js
|javascript|html|web|frontend|
null
I am trying to get the sample rate of each chunk of audio recorded using AudioContext but when I run my current code it prints the sample rate once and then keeps printing ```Uncaught (in promise) DOMException: Failed to execute 'decodeAudioData' on 'BaseAudioContext': Unable to decode audio data.``` Why is this occurring and how can I fix it? <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> async function getSampleRate() { try { const constraints = { audio: { channelCount: 1 } }; const stream = await navigator.mediaDevices.getUserMedia(constraints); mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm' }); // Start recording audio mediaRecorder.start(1000); // Create an AudioContext object const audioContext = new(window.AudioContext || window.webkitAudioContext)(); // Function to handle data available const handleDataAvailable = async(e) => { // Create a Blob from the received audio data const audioBlob = new Blob([e.data], { type: 'audio/webm' }); // Create a URL for the Blob const audioURL = URL.createObjectURL(audioBlob); // Fetch the audio data as an ArrayBuffer const response = await fetch(audioURL); const audioArrayBuffer = await response.arrayBuffer(); // Decode the ArrayBuffer into an AudioBuffer const audioBuffer = await audioContext.decodeAudioData(audioArrayBuffer); // Extract the sample rate const sampleRate = audioBuffer.sampleRate; // Log the sample rate console.log('Sample Rate:', sampleRate); }; // Push audio chunks to buffer mediaRecorder.ondataavailable = handleDataAvailable; // Stop recording when mediaRecorder stops mediaRecorder.onstop = () => { console.log('Recording stopped'); }; } catch (error) { console.error('Error accessing microphone:', error); } } getSampleRate() <!-- end snippet -->
How can I get the difference in minutes between two dates and hours?
In OWASP ZAP what does the summary in the Token Generation and Analysis tool mean? What do each of the tests mean? There is not very much info about this tool online. [1]: [https://i.stack.imgur.com/ruOla.png][1] [1]: https://i.stack.imgur.com/g9KvG.png
How do you use the Token Generation and Analysis tool in ZAP?
|zap|
Your side effect does not guarantee that the `OutlinedTextField` has finished its composition. To address this, you can request the focus within the [`onGloballyPositioned`](https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/OnGloballyPositionedModifier#onGloballyPositioned(androidx.compose.ui.layout.LayoutCoordinates)) modifier, like this: ```kt @Composable fun ScreenView( data: ScreenViewData, ) { val focusRequester = remember { FocusRequester() } // LaunchedEffect( // key1 = Unit, // ) { // focusRequester.requestFocus() // } Scaffold { innerPadding -> Column( modifier = Modifier .padding(innerPadding) ) { OutlinedTextField( value = "your_text_field_value", onValueChange = { /* TODO */ }, modifier = Modifier .focusRequester(focusRequester) .onGloballyPositioned { focusRequester.requestFocus() } ) } } } ``` Note that this function will execute each time the global position of the `OutlinedTextField` changes. If you don't want this behaviour, consider checking a condition before requesting the focus (e.g., checking if the focus was already requested).
Snowflake doesn’t hold data as files (assuming that you are using standard tables) so in this case your last comment, particularly “Snowflake to overwrite it's old files”, still doesn’t make much sense. Assuming your Snowflake tables have a column that indicates a “day” then you can delete these records and load your latest Spark files into Snowflake. If your new set of files is a change to data in the existing records in Snowflake then you can potentially insert/update/delete with a merge statement. If you are talking about some type of Snowflake External table (that sits over files held in a cloud storage system) then you can manage those files outside of Snowflake and just refresh the metadata in Snowflake as necessary. If you’re just trying to move data from Spark to Snowflake then I’d start by reading [this][1] part of the documentation [1]: https://docs.snowflake.com/en/user-guide/spark-connector-use#moving-data-from-spark-to-snowflake
use the following: python setup.py install --prefix=<your path>
From [\[bit.cast\]/2](https://timsong-cpp.github.io/cppwp/n4950/bit.cast#2): > [...] A bit in the value representation of the result is indeterminate if it does not correspond to a bit in the value representation of _from_ [...]. For each bit in the value representation of the result that is indeterminate, the smallest object containing that bit has an indeterminate value; the behavior is undefined unless that object is of unsigned ordinary character type or std​::​byte type. [...] So, in your case, the behavior of the expression is undefined, but not because of the `std::bit_cast` itself. Because the bits of `b` do not correspond to any bit of the value representation of `A{}`, they are indeterminate and the value of `b` itself is consequently indeterminate. Only because `b` has type `unsigned char`, this is not immediately undefined behavior. However, for the comparison with `0 ==`, you then read the value of `b`, which causes undefined behavior because its value is indeterminate. Of course, because you are using the comparison as the condition in a `static_cast`, the program will be ill-formed, not have undefined behavior. The compiler needs to diagnose this and therefore only Clang is conforming.
NextAuth.js signIn response always undefined
|node.js|next.js|next-auth|
null
``` import { NextResponse } from "next/server"; import User from "../../models/post"; const POST = async (req, res) => { try { const body = req.json(); console.log(req); const userData = { Title: body.title, content: body.content, tag: body.tag, time: new Date() }; //make corrections here return NextResponse.json({ message: "User posted successfully" }, { status: 200 }); } catch (error) { console.error("Error occurred while saving user data:", error); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 }); } }; export default POST; ``` Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported. at stringify (<anonymous>) as well as req.json is not a function error getting this error in nextjs14 using app router so what I understand from these errors is that I cannot pass certain objects from server components to client components but I am not sending anything from my server api where I am just creating a post for a blog ,just simply passing a message back to the react frontend. I just want to know why is this happening?
Error occurred while saving user data: TypeError: req.json is not a function
|next.js|nextjs-api-router|