instruction stringlengths 0 30k β |
|---|
```
add_action( 'woocommerce_update_product', 'auto_tag_product_by_price', 10, 1 );
function auto_tag_product_by_price( $product_id ) {
$product = wc_get_product( $product_id );
$price = $product->get_price();
// Define your price ranges and corresponding tag IDs here
$price_ranges = array(
'budget' => array( 'min' => 0, 'max' => 100, 'tag_id' => 123 ), // Replace 123 with your tag ID
'mid-range' => array( 'min' => 101, 'max' => 200, 'tag_id' => 456 ), // Replace 456 with your tag ID
'premium' => array( 'min' => 201, 'max' => 9999, 'tag_id' => 789 ), // Replace 789 with your tag ID
);
$assigned_tag = null;
foreach ( $price_ranges as $tag_name => $range ) {
if ( $price >= $range['min'] && $price <= $range['max'] ) {
$assigned_tag = $range['tag_id'];
break;
}
}
if ( $assigned_tag ) {
$product->set_tag_ids( array( $assigned_tag ) );
$product->save();
}
}
```
I am trying to automaticlly tagging products according to their prices at that moment but couldnt manage to do it. Is it possible to do this? |
Auto Tagging WooCommerce Products according to the Price |
|wordpress|woocommerce|hook-woocommerce| |
null |
What is the optimal way for the scanner to reread the contents of the file from the beginning? Since in the verticesSet function, I'm using while (scanner.hasNextLine()), which reads until there are no more values in the file because it has already read them all, when I call the edgesSet function, nothing happens because it tries to read values from the file, but the "cursor" is positioned at the very end.
I know it's possible to prevent this by reopening a new scanner and passing it to the edgesSet function, but is that the right way to do it? For example, if I have 10 other functions, I probably wouldn't want to create a new scanner each time. Is there a way to tell it to read from the beginning of the file?
```
public class Test{
public static void main(String[] args) {
File fileName = new File("test.txt");
try {
Scanner scanner = new Scanner(fileName );
verticesSet(scanner);
edgesSet(scanner);
scanner.close();
} catch (FileNotFoundException exception) {
System.err.println("file not found" + exception.getMessage());
}
}
public static void verticesSet(Scanner scanner) {
Set<Integer> verticesSet = new HashSet<>();
while (scanner.hasNextLine()) {
verticesSet.add(scanner.nextInt());
}
System.out.println(verticesSet);
}
public static void edgesSet(Scanner scanner) {
List<String> edges = new ArrayList<>();
while (scanner.hasNextLine()) {
edges.add(scanner.nextLine());
}
for (int i = 0; i < edges.size(); i++) {
System.out.println("index" + i + " is" + edges.get(i));
}
}
}
``` |
How can the scanner reread the entire file after it has already executed hasNextLine once? |
|java|file|java.util.scanner| |
null |
{"Voters":[{"Id":14732669,"DisplayName":"ray"},{"Id":286934,"DisplayName":"Progman"},{"Id":1599751,"DisplayName":"PeterJ"}]} |
Preserving DataFrame Modifications Across Options in a Streamlit Application |
|python|pandas|dataframe|scope|streamlit| |
null |
You should try Give All domain access to Socket first, Like
socketio.io.attach(server, {
cors: {
origin: "*",
method: ["POST", "GET"],
},
});
If working in this case we can get the Exact error |
i am making a multiplayer game using Mirror, the premise of this action is simple :
if a player walks in front of a patrolling enemy, the enemy will start following the player, in a single player context it all works fine, however when in a multiplayer setting it all goes bad :
- The client player walks in front of the patrolling enemy
- The patrolling enemy goes to the host player's position
(this update only happens on the host's POV, nothing changes on the client side)
this is my patrolling code :
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Mirror;
public class PatrolNavigation : NetworkBehaviour
{
private NavMeshAgent agent;
public FieldOfView fov;
[SerializeField] Transform[] posPoints;
int posInt;
Vector3 dest;
// Boolean that activates the first time you see the player
public bool hasSeenPlayer = false;
[SerializeField] float targetTime;
[SerializeField] float PosTime;
private Vector3 startPosition;
public GameObject PatrolPoints;
private bool hasSpawnedPatrolPoints = false;
// Start is called before the first frame update
void Start()
{
posInt = Random.Range(0, posPoints.Length);
agent = GetComponent<NavMeshAgent>();
startPosition = gameObject.transform.position;
StartCoroutine(GoPosPoints());
}
// Update is called once per frame
void Update()
{
/*if (!isServer)
return;*/
if (fov.canSeePlayer)
{
GoToPlayer();
}
else if (hasSeenPlayer && !fov.canSeePlayer)
{
Patrol();
if (targetTime < 0)
{
GoBackToSpawn();
}
}
}
[Command(requiresAuthority = false)]
private void GoToPlayer()
{
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
if (players.Length > 0)
{
// Set destination to the first player found (you might want to implement logic to select the closest player)
agent.destination = players[0].transform.position;
hasSeenPlayer = true;
targetTime = 10.0f;
SpawnPatrolPoints();
}
}
[Command(requiresAuthority = false)]
private void SpawnPatrolPoints()
{
if (!hasSpawnedPatrolPoints)
{
PatrolPoints.transform.position = agent.destination;
hasSpawnedPatrolPoints = true;
}
}
[Command(requiresAuthority = false)]
private void Patrol()
{
targetTime -= Time.deltaTime;
dest = posPoints[posInt].position;
agent.SetDestination(dest);
hasSpawnedPatrolPoints = false;
}
[Command(requiresAuthority = false)]
public void GoBackToSpawn()
{
agent.SetDestination(startPosition);
}
IEnumerator GoPosPoints()
{
yield return new WaitForSeconds(PosTime);
posInt = Random.Range(0, posPoints.Length);
StartCoroutine(GoPosPoints());
}
}
```
Field of view :
```
using System.Collections;
using UnityEngine;
using Mirror;
public class FieldOfView : NetworkBehaviour
{
public float radius;
[Range(0, 360)]
public float angle;
public LayerMask targetMask;
public LayerMask obstructionMask;
[SyncVar]
public bool canSeePlayer;
private void Start()
{
StartCoroutine(FOVRoutine());
}
private IEnumerator FOVRoutine()
{
WaitForSeconds wait = new WaitForSeconds(0.2f);
while (true)
{
yield return wait;
FieldOfViewCheck();
}
}
private void FieldOfViewCheck()
{
Collider[] rangeChecks = Physics.OverlapSphere(transform.position, radius, targetMask);
if (rangeChecks.Length != 0)
{
foreach (Collider col in rangeChecks)
{
if (!col.CompareTag("Player"))
continue;
Transform target = col.transform;
Vector3 directionToTarget = (target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, directionToTarget) < angle / 2)
{
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (!Physics.Raycast(transform.position, directionToTarget, distanceToTarget, obstructionMask))
{
canSeePlayer = true;
return; // If the player is seen, exit early
}
}
}
}
canSeePlayer = false; // If no player is seen, update to false
}
}
```
i added NetworkIdentity to all the enemies but still nothing changed |
Cannot sync non-player objects in Unity mirror |
|unity-game-engine|game-development|multiplayer|mirror| |
null |
all,
we have a large Spring WebFlux code-base that relies on certain `@ExceptionHandler` / `@RestControllerAdvice`. and we have a case for `Exception.class` that basically logs the exception as `error` and returns a certain model:
```
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public RestError handleUnknown(Exception exception) {
log.error(Optional.ofNullable(exception.getCause())
.map(Throwable::getMessage)
.orElse(exception.getMessage()),
exception);
return new RestError(exception);
}
```
It should only be used occasionally, because we have also extensive coverage for specific exceptions. But still, we would like to keep this fallback option.
Problem, however, happens when a _certain type of issue is causing the exception in question_ - namely, Netty's `AbortedException`. An exception handler, in this case, tries to write response body, and we see a completely obscure `[xxx] Error [java.lang.UnsupportedOperationException] for HTTP GET "/actuator/health/readiness", but ServerHttpResponse already committed (200 OK)` in the logs. This has been bugging me for a long while and I figured something needs to be done it.
So, I've added a custom `WebFilter` with a `SignalListener` that now logs this `UnsupportedOperationexception` with it's stacktrace, and I see that the error is actually `Connection has been closed BEFORE send operation` and the `UnsupportedOperationException` happens when the response body is written and a `Content-Length` header is set, and for whatever reason, these `Headers` are read-only, thus `UnsupportedOperationException`:
```
java.lang.UnsupportedOperationException: null
at org.springframework.http.ReadOnlyHttpHeaders.set(ReadOnlyHttpHeaders.java:108)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint β’ Exception handler com.company.common.exception.handler.RestExceptionHandler#handleUnknown(Exception), error="Connection has been closed BEFORE send operation" [DispatcherHandler]
*__checkpoint β’ com.company.common.monitoring.logging.raw.LoggingWebFilter [DefaultWebFilterChain]
*__checkpoint β’ com.breakwater.sitecheckerservice.common.config.ErrorLoggingWebFilter [DefaultWebFilterChain]
*__checkpoint β’ HTTP POST "/v1/some-url" [ExceptionHandlingWebHandler]
Original Stack Trace:
at org.springframework.http.ReadOnlyHttpHeaders.set(ReadOnlyHttpHeaders.java:108)
at org.springframework.http.HttpHeaders.setContentLength(HttpHeaders.java:963)
at org.springframework.http.codec.EncoderHttpMessageWriter.lambda$write$1(EncoderHttpMessageWriter.java:135)
```
Question: can an `@ExceptionHandler` be written so, that it
* either does NOT handle this particular error type (`AbortedException`)
* or does NOT return any value
* or otherwise signals that no response needs to be written in some cases
while being able to handler other `Exception.class`-type exceptions normally (by returning a body of a particular type)
? |
I have a ksqldbcluster with 2 nodes. Sometimes i might receive an alert from grafana(which i monitor the cluster) that some queries are in error state. When i check the show queries i see that a number of queries have 1 PERSISTENT running and 1 ERROR. I restart first the second ksqdb docker instance. Sometimes is fixed sometimes is not. If is not i restart the first ksqldb docker instance and then is fixed. Any ideas?
> version: '3' services: ksqldb-server:
> container_name: ksqldb-server
> hostname: ksqldb.xxxxxxx
> network_mode: host
> image: confluentinc/ksqldb-server:latest
> environment:
> KSQL_HOST_NAME: ksqldb.xxxxxxxx
> KSQL_BOOTSTRAP_SERVERS: xxxxxx:9093
> KSQL_SECURITY_PROTOCOL: SSL
> KSQL_LISTENERS: http://xxxxxx:8088,https://xxxxxx:8443
> KSQL_KSQL_SCHEMA_REGISTRY_URL: http://xxxxxxxx-as.net:8081,http://xxxxxx:8082
> KSQL_SSL_CLIENT_KEY_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
> KSQL_SSL_CLIENT_KEY_STORE_PASSWORD: xxxxxx
> KSQL_SSL_CLIENT_TRUST_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
> KSQL_SSL_CLIENT_TRUST_STORE_PASSWORD: xxxxxxx
> KSQL_SERVER_ID: id1
> KSQL_STREAMS_NUM_STANDBY_REPLICAS: 1 # Corrected property name
> KSQL_LOG4J_ROOT_LOGLEVEL: "ERROR"
> KSQL_QUERY_PULL_ENABLE_STANDBY_READS: true
> KSQL_HEARTBEAT_ENABLE: true
> KSQL_QUERY_PULL_THREAD_POOL_SIZE: "30"
> KSQL_LAG_REPORTING_ENABLE: true
> KSQL_INTERNAL_LISTENER: http://xxxxxxx:8080
> KSQL_SSL_TRUSTSTORE_LOCATION: /etc/kafka/secrets/ksqldb.truststore.jks
> KSQL_SSL_TRUSTSTORE_PASSWORD: xxxxxx
> KSQL_SSL_KEYSTORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
> KSQL_SSL_KEYSTORE_PASSWORD: xxxxxxx
> KSQL_JMX_OPTS: -Dcom.sun.management.jmxremote -javaagent:/etc/kafka/secrets/jmx_prometheus_javaagent-0.17.2.jar=4000:/etc/kafka/secrets/ksql.yaml
> ports:
> - 8088:8088
> - 4000:4000
> - 8443:8443
> volumes:
> - /ksqldata/data:/var/lib/ksqldb-server/data
> - /ksqldata/newssl/:/etc/kafka/secrets/
>
> ksqldb-cli:
> image: confluentinc/ksqldb-cli:latest
> container_name: ksqldb-cli
> entrypoint: /bin/sh
> tty: true # Corrected indentation
>
> telegraf:
> image: telegraf
> restart: always
> volumes:
> - ./telegraf.conf:/etc/telegraf/telegraf.conf:ro
> - /var/run/docker.sock:/var/run/docker.sock ~
When restarting ksqldb instance the issue is resolved. Maybe i am missing something in my parameters or how to fix the error? |
After following instructions for installing MacOS on VirtualBox, I kept running into errors. This is the one that stumped me. The exact error message is as follows:
```VM Name: BigSur
Failed to query SMC value from the host (VERR_INVALID_HANDLE).
Result Code:
E_FAIL (0X80004005)
Component:
ConsoleWrap
Interface:
IConsole {6ac83d89-6ee7-4e33-8ae6-b257b2e81be8}
```
I've followed all the recommended steps online (reinstalling, turning Virtualization on/off etc.) and nothing seems to work. After reinstalling it did go from showing the error in the Virtual Machine window to showing it on the sidebar of the menu (as shown in the image: (https://i.stack.imgur.com/kfDZj.png). Can someone tell me what I did wrong? |
How do I fix VERR_INVALID_HANDLE (0X80004005) Error in VirtualBox? |
I want to add a variable in the variable area of this debugger, that is, a variable will appear when the startup, now that the startup part is done, but I can't add the variable part, I saw the official mock example, but it's too complicated for me to understand, only the startup part.
I want to add a variable in the variable area of this debugger |
A question about vscode plugin development |
|vscode-extensions|vscode-debugger| |
null |
I'm pretty sure that this is a problem with the SBCL repl itself, and possibly a problem with the way that you are introducing strings into your code.
As far as the repl is concerned, the SBCL repl is not really actively developed; most lispers are probably using Slime or something similar for repl development. This is a much better experience than working with the SBCL repl. I couldn't get the posted code to misbehave in a Slime repl.
I was able to reproduce the problem with an SBCL repl. On my Windows machine, it seems that pasting the posted string literal into an SBCL repl window resulted in a string which is UTF-16 encoded. This is where I suspect there is some issue with the SBCL repl. Calling `babel:string-to-octets` on the pasted string yields the wrong result, as OP noted. SBCL has its own `sb-ext:string-to-octets` procedure, and calling that on the pasted string drops into the debugger with an `SB-IMPL::OCTETS-ENCODING-ERROR` error. This makes me think that the problem is somewhere on the SBCL side.
As a workaround, I was able to round-trip the pasted string through a UTF-16 encoding using `babel`:
```none
;; Calling on a pasted string literal:
* (print-hex (babel:string-to-octets "οΏ½οΏ½TESTοΏ½οΏ½TEST"))
ED A0 BD ED B1 89 54 45 53 54 ED A0 BD ED B3 8D 54 45 53 54 (20 bytes)
NIL
;; Round-tripping the pasted string literal:
* (print-hex (babel:string-to-octets
(babel:octets-to-string
(babel:string-to-octets "οΏ½οΏ½TESTοΏ½οΏ½TEST" :encoding :utf-16)
:encoding :utf-16)))
F0 9F 91 89 54 45 53 54 F0 9F 93 8D 54 45 53 54 (16 bytes)
NIL
* (let* ((s "οΏ½οΏ½TESTοΏ½οΏ½TEST")
(s-reencoded (babel:octets-to-string
(babel:string-to-octets s :encoding :utf-16)
:encoding :utf-16)))
(format t "TEST STRING [~A]~%" s)
(print-hex (babel:string-to-octets s-reencoded)))
TEST STRING [TESTTEST]
F0 9F 91 89 54 45 53 54 F0 9F 93 8D 54 45 53 54 (16 bytes)
NIL
*
```
Note that I was unable to make the same round-tripping work by using SBCL's `sb-ext:string-to-octets` and `sb-ext:octets-to-string` procedures.
The OP has said: _"This string is stored in a UTF-8 encoded file."_ The significance of this is unclear. Was the posted code saved in a file and loaded into a repl? I saved the posted code in a file using Emacs and Slime, using Windows Notepad with UTF-8 encoding, and using Windows Notepad with UTF-16 encoding. Every time I loaded this code from any of these files into either the SBCL repl or the Slime repl it worked as expected. This leads me to believe that the problem may be an inconvenience for playing in the repl, but not an issue for real programs. |
[enter image description here](https://i.stack.imgur.com/7sEP2.png)[enter image description here](https://i.stack.imgur.com/yoj4C.png)
Browser send right array from form but server end req body has only first value as string.
tried with different online solution nothing work.
Please help me to figure out problem. |
Java program images not showing up |
|java| |
null |
My spring boot project is structured so that i have modules contract (that handles incoming requests) and impl (that deals with the logic). Contract has a facade that passes the request to a facade in impl, that passes it to a service class, which is where the logic resides.
Using the repository pattern, structuring my code so that first i get the data, then i process it, how would i do that if for example, i had a list of orders coming in the request, and had to add the total amount which i get from the database using query a, then the item from query b? My struggle is, if i'm getting all data first, and then processing it, how do i know that item x belongs to the order x, considering i'm working with a list?
I have tried doing a foreach, and getting all the data for each order, and then building it, but that way i'm mixing the part where i get all the data and, and process it. |
Using Repository pattern to fetch data from different places and build list of objects |
|design-patterns|coding-style|repository-pattern| |
null |
So there are multiple problems...
1. You are scrolling the entire page, not just the table containing the data you want.
1. As you scroll >the table< either horizontally or vertically, the elements (rows and/or columns) that move off the screen (are no longer visible) actually disappear from the DOM.
This is going to be a nightmare to scrape.
Having said that, I did write some basic code to get you started. It doesn't even attempt to scroll... only pull what is visible (and then some). It only sees the first 14 cells in each row and the first 20 rows.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
url = 'https://app.powerbi.com/view?r=eyJrIjoiNzA0MGM4NGMtN2E5Ny00NDU3LWJiNzMtOWFlMGIyMDczZjg2IiwidCI6IjM4MmZiOGIwLTRkYzMtNDEwNy04MGJkLTM1OTViMjQzMmZhZSIsImMiOjZ9&pageName=ReportSection'
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
wait = WebDriverWait(driver, 10)
table = wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@role='document'][.//div[text()='Job Name']]")))
headers = table.find_elements(By.CSS_SELECTOR, "div[role='columnheader']")
headers.pop(0) # clean up first header
# print(len(headers))
h = []
for header in headers:
h.append(header.text.strip())
print(h)
rows = table.find_elements(By.CSS_SELECTOR, "div[role='row']")
rows.pop(0) # clean up empty row
for row in rows:
cells = row.find_elements(By.CSS_SELECTOR, "div[role='gridcell']")
if cells:
cells.pop(0) # clean up empty cell
# print(len(cells))
c = []
for cell in cells:
c.append(cell.text)
print(c)
The output
['Job Name', 'State', 'Licensed, Registered or Certified by State', 'Education Requirement', 'Amount of Training Required (In Hours)', 'Amount of Experience Required', 'Professional Exam', 'Required Time of License Renewal (In Years)', 'Continuing Education Requirement', 'Additional Required Exams', 'Cost of Initial Licensure (In Dollars)', 'Cost of License Renewal (In Dollars)', 'Reciprocity or Endorsement', 'Good Moral Character Requirement']
['Athletic Trainer', 'Alabama', 'Licensed', 'A bachelorβs degree is required (from an accredited academic institution or similarly recognized institution)', '0', '0', 'Yes, individuals must take an exam to attain licensure', '1', '26 hrs x 1 yr', '0', '505', '75', 'State does have statutory language allowing reciprocity or endorsement agreements', 'State does not have a βgood moral character" clause']
... and so on |
The data structure for this is a [Trie][1] (Prefix Tree):
* Time Efficiency: Search, Insertion & Deletion: With a time-complexity of **O(m)** where m is the length of the string.
* Space Efficiency: Store the unique characters present in the strings. This can be a space advantage compared to storing the entire strings.
```php
<?php
class TrieNode
{
public $childNode = []; // Associative array to store child nodes
public $endOfString = false; // Flag to indicate end of a string
}
class Trie
{
private $root;
public function __construct()
{
$this->root = new TrieNode();
}
public function insert($string)
{
if (!empty($string)) {
$this->insertRecursive($this->root, $string);
}
}
private function insertRecursive(&$node, $string)
{
if (empty($string)) {
$node->endOfString = true;
return;
}
$firstChar = $string[0];
$remainingString = substr($string, 1);
if (!isset($node->childNode[$firstChar])) {
$node->childNode[$firstChar] = new TrieNode();
}
$this->insertRecursive($node->childNode[$firstChar], $remainingString);
}
public function commonPrefix()
{
$commonPrefix = '';
$this->commonPrefixRecursive($this->root, $commonPrefix);
return $commonPrefix;
}
private function commonPrefixRecursive($node, &$commonPrefix)
{
if (count($node->childNode) !== 1 || $node->endOfString) {
return;
}
$firstChar = array_key_first($node->childNode);
$commonPrefix .= $firstChar;
$this->commonPrefixRecursive($node->childNode[$firstChar], $commonPrefix);
}
}
// Example usage
$trie = new Trie();
$trie->insert("Softball - Counties");
$trie->insert("Softball - Eastern");
$trie->insert("Softball - North Harbour");
$trie->insert("Softball - South");
$trie->insert("Softball - Western");
echo "Common prefix: " . $trie->commonPrefix() . PHP_EOL;
?>
```
Output:
Common prefix: Softball -
[Demo][2]
Trie Visualization (Green nodes are marked: endOfString):
[![enter image description here][3]][3]
[1]: https://en.wikipedia.org/wiki/Trie
[2]: https://onecompiler.com/php/428w3k8pe
[3]: https://i.stack.imgur.com/KppuH.png |
**Goal**: I'm trying to set up a telegram bot, which downloads pictures that are sent to it.
After doing some manual playing with ```requests```, I'd rather like to *use the python-telegram-bot* library. Yet unfortunately most examples outside the docs are written for some Version <20, the official docs are purely written for Versions >20 and unfortunately never cover this topic to an extend which allowed me to write working code. *I dont want to downgrade the version of my lib, I want to understand the current Version (v21.x.x). *
My relevant **current code** looks like this:
```python
from dotenv import load_dotenv
import os
import asyncio
import telegram
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, ApplicationBuilder
from telegram.ext import InlineQueryHandler, ExtBot
load_dotenv()
TOKEN = os.getenv('TOKEN')
### **Downloader**
async def downloader(update: Update, context: ContextTypes.DEFAULT_TYPE):
logging.DEBUG("in downloader app!")
new_file = await update.message.effective_attachment[-1].get_file() # [-1] for largest size of photo
file = await new_file.download_to_drive()
# file2 = await ExtBot.get_file()
return file
### **Main**
if __name__ == '__main__':
application = ApplicationBuilder().token(TOKEN).build()
downloader_handler = MessageHandler(filters.Document.IMAGE, downloader) #**here are the filters**;
application.add_handler(downloader_handler)
#file_handler = MessageHandler(filters.Document.JPG, downloader) # another try, also Document.ALL
#application.add_handler(file_handler)
application.run_polling()
```
My observations so far:
- when filters set for Document.ALL and i send a pdf-File, it seems to enter the downloader, yet the pdf I'm not able to retrieve the downloaded pdf everytime (it seems its sometimes saving it to a path which is unknown to me)
- when i send an image (jpg), it seems, the downloader is never entered (no debug/print statements)
- I was running in all heaps of Errors, when trying to replace code with snippets from other posts, as it seems most rely on v>20-way of writing this.
To me it seems, this shouldn't be that much hustle...
---
Any help would be highly apprechiated. I don't think, I will be the only one struggling with this after the major overhaul of the library.
Thanks in advance and happy coding to everyone :)
I've tried various stackoverflow-Posts related to this, from all I've read, [this example snippet, specifically designed with v20 syntax](https://stackoverflow.com/questions/62253718/how-can-i-receive-file-in-python-telegram-bot) should work. It does for pdfs (see above weird behaviour), but it doesn't for images, which leads me to believe it is some sort of problem related to filters.
**Filters I've tried**:
- `filters.Document.IMAGE`
- `filters.Document.JPG`
- `filters.Document.ALL` |
|runtime-error|virtual-machine|virtualbox| |
null |
I was studying convolutional neural networks, and creating a module.
While using nn.conv2d, I can't figure out exactly how to specify my out_channels.
I understand that it is the number of filters that are going to be used.
For a black and white picture, (meaning in_channels to be 1), if I put 8 output_channels, does it mean that I will get 8 different feature maps?
Also if I increase my input_channel to 3, let's say RGB, does this mean that I will get total of 24 (3*8 = 24) feature maps, 8 red, 8 green, 8 black? |
It sounds like you are on the right track using [`pl.DataFrame.join_asof`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.join_asof.html). To group by the symbol the `by` parameter can be used.
```python
(
fr
.join_asof(
events,
left_on="Date",
right_on="Earnings_Date",
by="Symbol",
)
)
```
```
shape: (5, 5)
βββββββββ¬βββββββββ¬βββββββββββββ¬ββββββββββββββββ¬ββββββββ
β index β Symbol β Date β Earnings_Date β Event β
β --- β --- β --- β --- β --- β
β u32 β str β date β date β i64 β
βββββββββͺβββββββββͺβββββββββββββͺββββββββββββββββͺββββββββ‘
β 0 β A β 2010-08-29 β 2010-06-01 β 1 β
β 1 β A β 2010-09-01 β 2010-09-01 β 4 β
β 2 β A β 2010-09-05 β 2010-09-01 β 4 β
β 3 β A β 2010-11-30 β 2010-09-01 β 4 β
β 4 β A β 2010-12-02 β 2010-12-01 β 7 β
βββββββββ΄βββββββββ΄βββββββββββββ΄ββββββββββββββββ΄ββββββββ
```
Now, I understand that you'd like each event to be matched *at most once*. I don't believe this is possible with `join_asof` alone. However, we can set all event rows that equal to the previous row to `Null`. For this, an [`pl.when().then()`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html) construct can be used.
```python
def null_if_duplicate(col: str, by: str) -> pl.Expr:
return pl.when(
pl.col(col).ne_missing(pl.col(col).shift()).over(by)
).then(
pl.col(col)
)
(
fr
.join_asof(
events,
left_on="Date",
right_on="Earnings_Date",
by="Symbol",
)
.with_columns(
null_if_duplicate("Earnings_Date", by="Symbol"),
null_if_duplicate("Event", by="Symbol"),
)
)
```
```
shape: (5, 5)
βββββββββ¬βββββββββ¬βββββββββββββ¬ββββββββββββββββ¬ββββββββ
β index β Symbol β Date β Earnings_Date β Event β
β --- β --- β --- β --- β --- β
β u32 β str β date β date β i64 β
βββββββββͺβββββββββͺβββββββββββββͺββββββββββββββββͺββββββββ‘
β 0 β A β 2010-08-29 β 2010-06-01 β 1 β
β 1 β A β 2010-09-01 β 2010-09-01 β 4 β
β 2 β A β 2010-09-05 β null β null β
β 3 β A β 2010-11-30 β null β null β
β 4 β A β 2010-12-02 β 2010-12-01 β 7 β
βββββββββ΄βββββββββ΄βββββββββββββ΄ββββββββββββββββ΄ββββββββ
``` |
So I have a website hosted on Godaddy, where I have a "sellers.json" file, the file updates once in a while using a php script I created to update the phpmyadmin database, all of the CRUD operations work as they should, however, the issue we encounter is that on every database update I have to manually go into /wp-admin and click flush cache.
As a developer, I wanted to create a function that will automaticly flush the cache upon every create/edit/delete, I have came across this function "WP_Object_Cache::flush()", and tried to use it but it didn't work for me due to an error.
Is that the function and method that I need? or is there an easier method? Thanks!
|
Array send by post form always received as string with first element only in Node js Express with pug |
|node.js|express|pug| |
null |
When i pass a pointer to a function and then change the pointer to a another location of the memory, I get SIGSEV or garbage values. Where is a code to demonstrate that:
```c
#include <stdio.h>
void fn(char *n) {
/*
* imagine this variable 'b' is
* a part of a structure of
* some library
*/
char *b = "hello, world!";
n = b;
}
int main() {
char *a = NULL;
fn(a);
/* it throws garbage or SIGSEV */
printf("%s\n", a);
}
```
I know what's the reason for this problem. The function `fn`, when called creates a variable `b` but when `fn` ends, `b` is deleted. And therefore, `a` is pointing to a memory that the program doesn't own. What do I do to fix this program. I know, I can solve the issue just by using C++ with it's std::string. But I have to do it in C.
Thanks. |
char * gives garbage value when pointing to a variable of a function in C |
|c|string|pointers| |
I'm making an Aqua button (from Mac OS X) and one of the many things I must fix is the button pulse, which seems to be very hard to find one to implement that actually (kinda) works
However, I found a (quarter-working) fix that "technically" pulses, but that doesn't fix the new problem of making the entire background pulse instead of the background size. It moves the color of choice (specifically the `background`) of the `@keyframe` up and down. So I want the entire background of the button to pulse instead of `background-size`. [The background keyframe for clarity here.][1]
Here's the CSS code:
```css
@keyframes color {
from {
background-size:50% 50%;
}
to {
background-size:100% 100%;
}
}
:root {
--confirm: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207));
--cancel: linear-gradient(#AAAAAA,#FFFFFF);
--altconfirm: linear-gradient(rgb(0, 100, 240),rgb(200, 200, 210))
}
button {
-webkit-appearance: none;
-moz-appearance: none;
border: 1px solid #ccc;
border-radius: 125px;
box-shadow: inset 0 13px 25px rgba(255,255,255,0.5), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.1);
cursor: pointer;
font-family: 'Lucida Sans Unicode', Helvetica, Arial, sans-serif;
font-size: 1.5rem;
margin: 1rem 1rem;
padding: .8rem 2rem;
position: relative;
transition: all ease .3s;
}
button:hover {
box-shadow: inset 0 13px 25px rgba(255,255,255,.7), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.2);
transform: scale(1.001);
}
button::before {
background: linear-gradient(rgba(255,255,255,.8) 7%, rgba(255,255,255,0) 50%);
border-radius: 125px;
content:'';
height: 97.5%;
left: 5%;
position: absolute;
top: 1px;
transition: all ease .3s;
width: 90%;
}
button:active{
box-shadow: inset 0 13px 25px rgba(255, 255, 255, 0.2), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.2);
transform: scale(1);
}
button::before:active{
box-shadow: inset 0 13px 25px rgba(255, 255, 255, 0.01), 0 3px 5px rgba(0,0,0,0.418), 0 10px 13px rgba(0, 0, 0, 0.418);
transform: scale(1);
}
button.confirm {
background: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207));
animation-name: color;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-timing-function: ease;
}
button.cancel {
background: var(--cancel);
border: 1.7px solid #AAA;
color: #000;
}
```
And the HTML code:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./Test.css">
</head>
<body>
<button class="confirm" style="background-color: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207))">Push Button</button><br>
<button class="cancel">Push Button</button><br>
<p>EEE</p>
</body>
</html>
```
[1]: https://i.stack.imgur.com/k3RJZ.gif |
Download files (spec. images) with telegram bot (python-telegram-bot) |
|python|bots|telegram|python-telegram-bot| |
null |
Traceback (most recent call last):
File "C:\Users\Soe Htet Oo\PycharmProjects\PythonTesting\PythonSelenium\demoBrowser.py", line 3, in <module>
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: WebDriver.__init__() got an unexpected keyword argument 'executable_path'
I am just beginner and I got this error. |
Pycharm doesn't show "executable_path" and I got this error and no idea what to do |
|window| |
null |
In this code
char *line;
line = strncpy(line, req, size);
`line` is not explicitly initialized to a specific value; since it's an `auto` (local) variable, its initial value is *indeterminate*, meaning it could be literally anything. The behavior on writing through an invalid pointer is *undefined*, meaning that neither the compiler nor the runtime environment are required to handle the situation in any particular way.
In this particular case that indeterminate initial value just happened to corresponded to the address of a writable piece of memory, so your code *appeared* to work without any problems.
However, there's no guarantee you didn't overwrite something important that would have caused a problem later on, or that another thread or process won't write over that memory while you're using it. |
How to share authorization implemented in the server project with the client project in Blazor Web App Auto project? |
**i try to send email with set email image **
> Next to the message title there is a small picture. I am trying to change it to reflect the nature of the email sent in each sending process
>

```
def check(line):
arre = str(line).split(':')
print(arre)
mail_username="username"
mail_password="password"
try:
from_addr = mail_username
to_addrs=('myemail@gmail.com')
HOST = "smtpDomain"
print(HOST)
PORT = 587
smtp = smtplib.SMTP(HOST)
smtp.connect(HOST,PORT)
time.sleep(2)
smtp.ehlo()
smtp.starttls()
try:
smtp.login(mail_username,mail_password)
print ("goodlogin")
smtp.set_debuglevel(1)
msg = MIMEMultipart()
msg['From'] = "emample@example.com"
msg['To'] = to_addrs
msg['Reply-to'] = "emample@example.com"
msg['Subject']='test message'
msg.add_header('Content-Type', 'text/html')
data = line
msg.attach(MIMEText(data, 'html', 'utf-8'))
print(smtp)
smtp.sendmail(from_addr,[msg['To']],msg.as_string())
print ("done")
except Exception as ee:
print( ee)
smtp.quit()
except Exception as ee:
print ("asd")
print (ee)
```
I need help on how to send a different image
|
How to clear cache of a json file in my Godaddy Wordpress website automatically when I update it |
|php|wordpress|phpmyadmin|ads|wordpress-rest-api| |
null |
I am using jQuery to check the value of a range slider, and if that value is 1, add a class to an other element. The code below works well for this:
$(document).ready(function() {
$("#range-slider").mousemove(function() {
if (this.value == "1") {
$('.other-element').addClass('is--active');
} else {
$('.other-element').removeClass('is--active');
}
});
});
However I'd like to do this for multiple values, but the below code does not work. So how can I achieve this?
$(document).ready(function() {
$("#range-slider").mousemove(function() {
if (this.value == "1", "2", "3", "4", "5") {
$('.other-element').addClass('is--active');
} else {
$('.other-element').removeClass('is--active');
}
});
});
|
Check multiple values with jQuery |
|jquery| |
the given code is not conerging to correct eigenvalues. Kindly highlight potential issues and make corrections.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import simps
xlower = 10**-15
xupper = 60
dr = 0.001
x = np.arange(xlower,xupper+ dr,dr)
G = x.shape[0]
delta_x = dr
G
def potential(x, l=0):
V = l*(l+1)/2*x**2 - 1/x
return V
def intervals():
delta_E = 1
E = 0
energy_intervals = []
while E>-1:
energy_intervals.append((E-delta_E, E))
E = E - delta_E
return energy_intervals
1-2/6
def Numerov(E, x,v, G):
psis = [0] * G
psis[1] = 10**-6
for j in range(1,len(x)-1):
m = 2*(1-5/12* delta_x**2 * 2*(E - v[j]))*psis[j]
n = (1+1/12*delta_x**2*(E - v[j-1])*2)*psis[j-1]
o = 1 + 1/12*delta_x**2 *(E - v[j+1])*2
psis[j+1] = (m - n)/o
return psis
def binary_search(function, left, right,x, v, G):
print('left', left)
print('right', right)
precision = 10**-14
iter = 0
while abs(right - left) > precision and iter <= 10:
mid = (left + right) / 2
print('mid', mid)
psis = function(mid, x, v, G)
left_psis = function(left, x,v, G)
print('psis', psis[-1])
if np.isclose(psis[-1], 10**-6):
return mid, psis
elif left_psis[-1]*psis[-1] < 0:
print('psis < 0')
right = mid
print('new right', left)
else:
print('psis > 0')
left = mid
print('new left', right)
iter += 1
if np.isclose(psis[-1], 10**-6):
mid = (left + right) / 2
return mid, psis
return None, None
def main():
n_samples = 1
potentials = []
eigenvectors = {}
eigenvalues = {}
for i in range(n_samples):
eigenvectors[i] = []
eigenvalues[i] = []
V = potential(x)
energy_intervals = intervals()
for interval in energy_intervals:
print(interval)
eigenvalue, psis = binary_search(Numerov, interval[0], interval[1], x, V, G)
if eigenvalue is not None:
print("eigenvalue found")
eigenvalues[i].append(eigenvalue)
eigenvectors[i].append(psis)
print(f"{i}th sample is done")
return eigenvalues, eigenvectors
eigenvalues, eigenvectors= main()
eigenvalues
`
I tried counting the nodes in the solution first before implementing bisection method. but that didn't work also. The code is not converging to correct eigenvalues. |
I wrote some code in Pycharm last year, to loop through VAT numbers entered into the Gov website, to make sure they were still valid. It still works fine on the original laptop, but not on my other laptop, even thought the code is exactly the same (the only adjustment was for the location of the spreadsheet). I have given my code down below. When I try to run it on my other laptop, it comes up with the following error.
Traceback (most recent call last):
File "C:\Users\neils\Documents\Pycharm Projects\VATChecker\VATChecker.py", line 30, in <module>
VAT = web.find_element_by_xpath('//*[@id="target"]')
^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'
Process finished with exit code 1
One thing I also notice, is that the import sys and import datetime are both greyed out. I guess that's because it crashed before these imports were used?
I should mention, the version of Chrome is the same for both laptops (version 123), and I have the same chromedriver installed for both. Both laptops are windows 64 bit, in case you're thinking that might be the issue.
Are you able to advise me what the problem is please? Many thanks in advance.
```
import datetime
import sys
from selenium import webdriver
from openpyxl import workbook, load_workbook
from datetime import date
web = webdriver.Chrome()
wb = load_workbook('C:\\Users\\neils\\Documents\\NSO\\Self Billing agreements\\VATMusiciansCheckerUK.xlsx', data_only=True, read_only=False)
ws = wb.active
x=2
y=1
current_datetime = datetime.datetime.now()
current_datetime.strftime('%x %X')
invalid = ""
while ws.cell(x,1).value !=None:
ws.cell(x,9).value = ""
web.get("https://www.tax.service.gov.uk/check-vat-number/enter-vat-details")
web.implicitly_wait(10)
VatNumber = ws.cell(x,4).value
VAT = web.find_element_by_xpath('//*[@id="target"]')
VAT.send_keys(VatNumber)
VAT.submit()
web.implicitly_wait(4)
registered = web.find_element_by_xpath('/html/body/div[2]')
if (registered.text.find("Invalid")) > 0:
ws.cell(x,9).value = "Invalid VAT number"
invalid = invalid + str(y) + " " + ws.cell(x,1).value + " " + ws.cell(x,2).value + ", "
y=y+1
else:
ws.cell(x,9).value = "Valid VAT number"
ws.cell(x,6).value = current_datetime
x=x+1
if invalid == "":
print("All VAT records are correct")
else:
print("Invalid VAT records are " + invalid)
wb.save('C:\\Users\\neils\\Documents\\NSO\\Self Billing agreements\\VATMusiciansCheckerUK.xlsx')
``` |
Im using Google Analytics 4 and Google Tag Manager to register my events in my Wordpress site.
I have successfully added Google Tag Manager in both Header and Body and added an simple event called all_clicks and i have submitted all my latest changes.
[![enter image description here][1]][1]
The problem is that for some reason i get only events coming from the Home page of my site. If i click somewhere else and redirected, events wont show up in the Realtime report.
In the developers tools the events are being collected as intended for all pages meaning that the GTM is installed.
[![enter image description here][2]][2]
and events are also firing in Google Tag Assistant.
Note: If i go to the page that im redirected to by inserted the link directly to the nav bar of the browser, the all_click event will be reported in the Realtime reports. If i do a redirection afterwards, the all_click event wont be reported, even tho it is fired and collected.
Any ideas?
[1]: https://i.stack.imgur.com/ogj9o.png
[2]: https://i.stack.imgur.com/dNKAq.png |
The behaviour you're observing is defined [by the CSS specification's section on positioning][1]:
The short answer is that it is positioned (0,0) relative to its closest block-level ancestor element (in this case, its parent `<div`) because you didn't set any of the _inset properties_ for either axis of the inner `<div>` element.
------------------
The long answer requires following the spec:
[The _inset properties_][2] refer to `left:` and `right:` (for the horizontal axis), and `top:` and `bottom:` (for the vertical axis).
In your case, because all _inset properties_ in both axies are undefined, they default to `auto`, and when both properties in an axis are `auto` then the spec says this:
> If both inset properties in a given axis are `auto`, then, depending on the boxβs `self-alignment` property in the relevant axis:
(In your case, the `self-alignment` is `self-start`, for lengthy reasons I won't go into)
> ...for `self-start` alignment or its equivalent: Set its `start-edge` inset property to the _static position_, and its `end-edge` inset property to zero.
[The values for an element's _static position_][3] are determined by recalculating the box's shape/layout/etc if `position: static` were used instead (emphasis theirs):
> When both inset properties in a given axis are `auto`, they are resolved into a static position by aligning the box into its **static-position rectangle**, an _alignment container_ derived from the formatting context the box would have participated in if it were `position: static` (independent of its actual containing block). The static position represents an approximation of the position the box would have had if it were `position: static`.
[The _alignment container_ is described][4] as:
> The alignment container is the rectangle that the alignment subject is aligned within. This is defined by the layout mode, but is usually the alignment subjectβs containing block, and assumes the writing mode of the box establishing the containing block.
...so in your case, the _alignment container_ of the inner `<div>` is the outer `<div>` because that is the inner `<div>'s` _containing block_ because it has `display: block;` by default.
[1]: https://www.w3.org/TR/css-position-3/
[2]: https://www.w3.org/TR/css-position-3/#inset-properties
[3]: https://www.w3.org/TR/css-position-3/#staticpos-rect
[4]: https://www.w3.org/TR/css-align-3/#alignment-container |
when i am running npm run build command then getting this error
D:\SPR\Porfolio\developer-portfolio>npm run build
> developer-portfolio@0.1.0 build
> next build
β² Next.js 14.1.3
Creating an optimized production build ...
β Compiled successfully
β Linting and checking validity of types
β Collecting page data
β Generating static pages (5/5)
β Collecting build traces
β Finalizing page optimization
Route (app) Size First Load JS
β β / 93.4 kB 191 kB
β β /_not-found 882 B 85.2 kB
+ First Load JS shared by all 84.4 kB
β chunks/69-8cf8699d03dbafa6.js 29 kB
β chunks/fd9d1056-1b06546f2a6b6797.js 53.4 kB
β other shared chunks (total) 1.97 kB
β (Static) prerendered as static content
here is package.json file. i am unable to build the NextJs Project. i have tried many solutions from [this](https://stackoverflow.com/questions/53712936/how-to-build-next-js-production) but didn't work. because of the build failed issue i am also unable to deploy the nextjs app on github too.
{
"homepage": "https://myusername.github.io/portfolio",
"name": "developer-portfolio",
"description": "Portfolio",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@emailjs/browser": "^4.3.1",
"@next/third-parties": "^14.1.3",
"lottie-react": "^2.4.0",
"next": "^14.1.3",
"react": "latest",
"react-dom": "latest",
"react-fast-marquee": "^1.6.2",
"react-icons": "^4.11.0",
"react-toastify": "^10.0.4",
"sharp": "^0.33.3"
},
"devDependencies": {
"autoprefixer": "latest",
"eslint": "latest",
"eslint-config-next": "latest",
"postcss": "latest",
"sass": "^1.69.5",
"tailwindcss": "latest"
}
} |
My issue is given as follows:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/EBhfK.png
```python
import sympy as sp
p = sp.symbols('p')
I_p = sp.Identity(p)
C = sp.BlockMatrix([[I_p, I_p], [I_p, -I_p]])
Sigma_1 = sp.MatrixSymbol('Sigma_1', p, p)
Sigma_2 = sp.MatrixSymbol('Sigma_2', p, p)
Sigma = sp.BlockMatrix([[Sigma_1, Sigma_2], [Sigma_2, Sigma_1]])
C_Sigma_C_transpose = C * Sigma * C.T
print(C_Sigma_C_transpose)
## Matrix([
## [I, I],
## [I, -I]])*Matrix([
## [Sigma_1, Sigma_2],
## [Sigma_2, Sigma_1]])*Matrix([
## [I, I],
## [I, -I]])
```
The result does not match the expected output. How can we correct it? |
Using the `sympy` module in Python to compute a matrix multiplication involving symbols |
|python|matrix|sympy|matrix-multiplication|multiplication| |
recode
echo '>' | recode ascii..html
>
>< "
echo 'a' | recode ascii..html
a
> >
str=$1
for (( i=0; i<${#str}; i++ )); do
c=${str:$i:1}
printf "&#%d;" "'$c" #
done
echo ""
|
The best way to test more complex AWS lambda functions where development time and local infrastructure is the key. Is usage of their official [AWS Lambda docker image][1].
Simple Dockerfile example from documentation:
```Dockerfile
FROM public.ecr.aws/lambda/python:3.8
# Copy function code
COPY app.py ${LAMBDA_TASK_ROOT}
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "app.handler" ]
```
[1]: https://hub.docker.com/r/amazon/aws-lambda-python |
I think a good and simple solution is to use an adorner to render the masking symbols as an overlay of the original input.
Show the adorner to render the masking characters while hiding the password by setting the foreground brush to the background brush.
The following example shows how to use an `Adorner` to decorate the `TextBox`.
I have removed some code to reduce the complexity (the original library code also contained validation of input characters and password length, event logic, routed commands, `SecureString` support, low-level caret positioning to support any font family for those cases where the font is not a monospace font and password characters and masking characters won't align correctly etc. and a much more complex default `ControlTemplate`). The current version therefore only supports monospace fonts. The supported fonts have to be registered in the constructor. You could implement monospace font detection instead.
However, it's a fully working example (happy easter!).
**UnsecurePasswodBox.cs**
```c#
public class UnsecurePasswodBox : TextBox
{
public bool IsShowPasswordEnabled
{
get => (bool)GetValue(IsShowPasswordEnabledProperty);
set => SetValue(IsShowPasswordEnabledProperty, value);
}
public static readonly DependencyProperty IsShowPasswordEnabledProperty = DependencyProperty.Register(
"IsShowPasswordEnabled",
typeof(bool),
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(default(bool), OnIsShowPasswordEnabledChaged));
public char CharacterMaskSymbol
{
get => (char)GetValue(CharacterMaskSymbolProperty);
set => SetValue(CharacterMaskSymbolProperty, value);
}
public static readonly DependencyProperty CharacterMaskSymbolProperty = DependencyProperty.Register(
"CharacterMaskSymbol",
typeof(char),
typeof(UnsecurePasswodBox),
new PropertyMetadata('β', OnCharacterMaskSymbolChanged));
private FrameworkElement? part_ContentHost;
private AdornerLayer? adornerLayer;
private UnsecurePasswordBoxAdorner? maskingAdorner;
private Brush foregroundInternal;
private bool isChangeInternal;
private readonly HashSet<string> supportedMonospaceFontFamilies;
private FontFamily fallbackFont;
static UnsecurePasswodBox()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(typeof(UnsecurePasswodBox)));
TextProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(OnTextChanged));
ForegroundProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceForeground));
FontFamilyProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceFontFamily));
}
public UnsecurePasswodBox()
{
this.Loaded += OnLoaded;
// Only use a monospaced font
this.supportedMonospaceFontFamilies = new HashSet<string>()
{
"Consolas",
"Courier New",
"Lucida Console",
"Cascadia Mono",
"Global Monospace",
"Cascadia Code",
};
this.fallbackFont = new FontFamily("Consolas");
this.FontFamily = fallbackFont;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.Loaded -= OnLoaded;
FrameworkElement adornerDecoratorChild = this.part_ContentHost ?? this;
this.adornerLayer = AdornerLayer.GetAdornerLayer(adornerDecoratorChild);
if (this.adornerLayer is null)
{
throw new InvalidOperationException("No AdornerDecorator found in parent visual tree");
}
this.maskingAdorner = new UnsecurePasswordBoxAdorner(adornerDecoratorChild, this)
{
Foreground = Brushes.Black
};
HandleInputMask();
}
private static void OnIsShowPasswordEnabledChaged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var unsecurePasswordBox = (UnsecurePasswodBox)d;
unsecurePasswordBox.HandleInputMask();
Keyboard.Focus(unsecurePasswordBox);
}
private static void OnCharacterMaskSymbolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((UnsecurePasswodBox)d).RefreshMask();
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((UnsecurePasswodBox)d).RefreshMask();
private static object OnCoerceForeground(DependencyObject d, object baseValue)
{
var unsecurePasswordBox = (UnsecurePasswodBox)d;
// Reject external font color change while in masking mode
// as this would reveal the password.
// But store new value and make it available when exiting masking mode.
if (!unsecurePasswordBox.isChangeInternal && !unsecurePasswordBox.IsShowPasswordEnabled)
{
unsecurePasswordBox.foregroundInternal = baseValue as Brush;
}
return unsecurePasswordBox.isChangeInternal
? baseValue
: unsecurePasswordBox.IsShowPasswordEnabled
? baseValue
: unsecurePasswordBox.Foreground;
}
private static object OnCoerceFontFamily(DependencyObject d, object baseValue)
{
var unsecurePasswordBox = (UnsecurePasswodBox)d;
var desiredFontFamily = baseValue as FontFamily;
return desiredFontFamily is not null
&& unsecurePasswordBox.supportedMonospaceFontFamilies.Contains(desiredFontFamily.Source)
? baseValue
: unsecurePasswordBox.FontFamily;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.part_ContentHost = GetTemplateChild("PART_ContentHost") as FrameworkElement;
}
private void HandleInputMask()
{
this.isChangeInternal = true;
if (this.IsShowPasswordEnabled)
{
this.adornerLayer?.Remove(this.maskingAdorner);
ShowText();
}
else
{
HideText();
this.adornerLayer?.Add(this.maskingAdorner);
}
this.isChangeInternal = false;
}
private void ShowText()
=> SetCurrentValue(ForegroundProperty, this.foregroundInternal);
private void HideText()
{
this.foregroundInternal = this.Foreground;
SetCurrentValue(ForegroundProperty, this. Background);
}
private void RefreshMask()
{
if (!this.IsShowPasswordEnabled)
{
this.maskingAdorner?.Update();
}
}
private class UnsecurePasswordBoxAdorner : Adorner
{
public Brush Foreground { get; set; }
private readonly UnsecurePasswodBox unsecurePasswodBox;
private const int DefaultTextPadding = 2;
public UnsecurePasswordBoxAdorner(UIElement adornedElement, UnsecurePasswodBox unsecurePasswodBox) : base(adornedElement)
{
this.IsHitTestVisible = false;
this.unsecurePasswodBox = unsecurePasswodBox;
}
public void Update()
=> InvalidateVisual();
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
var typeface = new Typeface(
this.unsecurePasswodBox.FontFamily,
this.unsecurePasswodBox.FontStyle,
this.unsecurePasswodBox.FontWeight,
this.unsecurePasswodBox.FontStretch,
this.unsecurePasswodBox.fallbackFont);
double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
ReadOnlySpan<char> maskedInput = MaskInput(this.unsecurePasswodBox.Text);
var maskedText = new FormattedText(
maskedInput.ToString(),
CultureInfo.CurrentCulture,
this.unsecurePasswodBox.FlowDirection,
typeface,
this.unsecurePasswodBox.FontSize,
this. Foreground,
pixelsPerDip)
{
MaxTextWidth = ((FrameworkElement)this.AdornedElement).ActualWidth + UnsecurePasswordBoxAdorner.DefaultSystemTextPadding;
Trimming = TextTrimming.None;
};
var textOrigin = new Point(0, 0);
textOrigin.Offset(this.unsecurePasswodBox.Padding.Left + UnsecurePasswordBoxAdorner.DefaultSystemTextPadding, 0);
drawingContext.DrawText(maskedText, textOrigin);
}
private ReadOnlySpan<char> MaskInput(ReadOnlySpan<char> input)
{
if (input.Length == 0)
{
return input;
}
char[] textMask = new char[input.Length];
Array.Fill(textMask, this.unsecurePasswodBox.CharacterMaskSymbol);
return new ReadOnlySpan<char>(textMask);
}
}
}
```
**Generic.xaml**
```xaml
<Style TargetType="local:UnsecurePasswodBox">
<Setter Property="BorderBrush"
Value="{x:Static SystemColors.ActiveBorderBrush}" />
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="Background"
Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:UnsecurePasswodBox">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<AdornerDecorator Grid.Column="0">
<ScrollViewer x:Name="PART_ContentHost" />
</AdornerDecorator>
<ToggleButton Grid.Column="1"
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsShowPasswordEnabled}"
Background="Transparent"
VerticalContentAlignment="Center"
Padding="4,0">
<ToggleButton.Content>
<TextBlock Text=""
FontFamily="Segoe MDL2 Assets" />
</ToggleButton.Content>
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<ContentPresenter Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
``` |
A blank grey circle of `PullToRefreshContainer` is always displaying even first time or after refreshing.
Here is my code
val pullRefreshState = rememberPullToRefreshState()
Box(
modifier = Modifier
.fillMaxSize()
.nestedScroll(connection = pullRefreshState.nestedScrollConnection)
) {
// Another contents
PullToRefreshContainer(
modifier = Modifier.align(alignment = Alignment.TopCenter),
state = pullRefreshState,
)
}
Current compose version: `1.6.4`
[![enter image description here][1]][1]
Any help!
[1]: https://i.stack.imgur.com/zegl0.png |
PullRefreshIndicator circle always displaying on jetpack compose |
|android-jetpack-compose|pull-to-refresh| |
I am having an issue. It just published my first project and now I am realising if you add an "/" to the end of the URL it does load in a very different way I cant even explain. When you add a "Trailingslash" some of the Buttons of the Website are not clickable and if I do this with ng serve the font is changing, I cant click buttons and I get a white border to the side. You can try it yourself on https://22ndspartans.de the issue is only on the discord page at https://22ndspartans.de/discord and the issues appear with https://22ndspartans.de/discord/.
I tried it on my localhost, I tried to do it with other browsers and other devices. I found this issue when I set up my google search indexing. When I clicked my Discord page directly from the search results it doesn't load any backgroundimage. At the begining the issue was on the other pages aswell. I am abolutely confused.
Sorry for the english I gave my best to explain it.
[you can see the white border and font here with Trailingslash][1] ---->
[How it should be (without trailingslash)][2]
Edit: I found out in the published version the Anchor to the homepage is not working when you have a trailingslash on any other page. The rest seems to be working. I am hosting with cloudflare. Maybe this has something to do with google search aswell. Idk
2nd Edit: Okay I found out that the main problem is the Trailingslash so how do I tell my application to redirect to no trailingslash if a trailingslash is called? Or how do I get my website to load correctly with Trailingslash
Updated code:
[HTML of DiscordComponent][3]---->[TS of DiscordComponent][4]---->[New appo.routes.ts][5]
[1]: https://i.stack.imgur.com/C9NOF.jpg
[2]: https://i.stack.imgur.com/58Pmk.jpg
[3]: https://i.stack.imgur.com/jJgZp.jpg
[4]: https://i.stack.imgur.com/jXYub.jpg
[5]: https://i.stack.imgur.com/wW4S9.jpg |
In my flutter application using native kotlin code i am trying to fetch SIM numbers both SIM1 and SIM2 in my gradle file minimum sdk is 30
here is the function which i am have i am running the app on device having android 11 (tried with device having android 13 also)
```java
private fun getSimNumbers(): List<String> {
val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
val subscriptionManager = getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
val subscriptionIds = mutableListOf<String>()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
// Get subscription IDs for all slots
val allSubscriptionIds = subscriptionManager.activeSubscriptionInfoList
for (subscriptionInfo in allSubscriptionIds) {
val subscriptionId = subscriptionInfo.subscriptionId
val simNumber = subscriptionManager.getPhoneNumber(subscriptionId)
if (simNumber != null) {
subscriptionIds.add(simNumber)
}
}
} else {
// Request phone state permission if not granted
requestPermissions(arrayOf(Manifest.permission.READ_PHONE_STATE), PERMISSION_REQUEST_CODE)
}
return subscriptionIds
}
```
and the following error i am getting
```java
E/AndroidRuntime(15898): FATAL EXCEPTION: main
E/AndroidRuntime(15898): Process: com.ebankchallenger, PID: 15898
E/AndroidRuntime(15898): java.lang.NoSuchMethodError: No virtual method getPhoneNumber(I)Ljava/lang/String; in class Landroid/telephony/SubscriptionManager; or its super classes (declaration of 'android.telephony.SubscriptionManager' appears in /system/framework/framework.jar!classes3.dex)
```
i am expecting to get both SIM1 number and SIM2 number |
I have recently upgraded to Vuetify 3 from Vuetify 2. All the disabled v-input fields are not selectable by dragging the cursor. However, I noticed that v-autocomplete and v-select, even when disabled, have text selectable. Does anyone know the solution to this?
I tried testing it on regular html elements, without Vuetify. HTML input elements when disabled can select text but not vuetify disabled input fields |
null |
I am curious about how std algorithms interpret lambda expressions. In below example I am using std::set_difference algorithm for two maps. But the question is common for all algorithms vs comparison function.
```
std::map<std::string, int> map1{ {"test1",1}, {"test2",2}, {"test3",3}, {"test4",4},{"wxyz5",10}};
std::map<std::string, int> map2{ {"test1",2}, {"test2",3} };
std::map<std::string, int> difference;
std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(), std::inserter(difference, difference.begin()), [](const auto& one, const auto& two) { return one.first < two.first; });
```
I am getting correct output , `{"test3",3}, {"test4",4},{"wxyz5",10}`.
question is, if the comparison function returns true will the first element be added to output ?
If that is the case , I tried this in lambda return `return one.first != two.first` it breaks with assertion `sequence not ordered`. Here I am expecting that if keys are not same in both the maps then , return true , and the first element should be added to output. but it is not working .
Probably my way of understanding how each algorithm interprets lambda expression is wrong. Can anyone please explain .
thanks. |
how to build nextjs app unable to build and deploy |
|reactjs|github|next.js|build| |
null |
again me.
I use the following code to open a new flaps on the navigator:
function openNewWindowWithPost(url, params)
{
const form = document.createElement('form');
form.method = 'POST';
form.action = url;
form.target = '_blank';
for (const key in params)
{
if (params.hasOwnProperty(key))
{
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
It works very fine, but now I wish to close those flaps created with this code using javascript, I dont know how can I do it.
I thank you so much for your help. |
I want to parse my api response into desired type and i don't want to loop/map the results to desired type or destruct the props after retrieval of response. Please do the response parse while receiving api response itself.
API response in desired format:
```
import Items from "./DetailsResponse";
export default interface MinimalApiResponse {
Items: Items[];
status: number;
statusText: string;
}
```
API call:
```
async getPolicies(detail: Detail): Promise<MinimalApiResponse> {
try {
const response: AxiosResponse<MinimalApiResponse> = await axios.post(this.searchUrl, detail);
console.log(response);
} catch (error) {
throw error;
}
}
```
I have specified the minimalapiresponse there but still not result parsed to that type i do see other props as well apart from what i specified in minimalapiresponse. Please suggest. |
Iβm developing a flutter app using vs code and the Xcode simulator and I want to test a function where I have to press and hold. Itβs not working how can I test it?
I tried the shift and left click but it didnβt work. I also tried to connect my iphone but it also didnβt work because of the certification. |
How to press and hold in Xcode simulator |
|ios|flutter|xcode|ios-simulator| |
null |
I'm creating a program that runs a couple of scripts and has multiple threads / datastructure uses. When I shutdown the program, it quits normally but there is an error code received when I check $LastExitCode.
Β [![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/DnrG4.png
What can I do to make sure that the program exits correctly causing the exit code to be shown as 0? |
Program "clean" shutdown results in an error code from the system |
|c++|powershell| |
|sapui5| |
[enter image description here][1]
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
{
name: 'THERAPY 1',
testsuites: '65e93cc4950e6a858809348f',
description: 'UPDATED The pump software shall provide the Maximum Bolus Value therapy setting value upon request from the Pump Controller Interface.'
}
<!-- end snippet -->
Browser send right array from form but server end req body has only first value as string.
tried with different online solution nothing work.
Please help me to figure out problem.
[1]: https://i.stack.imgur.com/wLaR9.png |
Solving Hydrogen atom using Numerov's menthod and bisection method |
|python| |