instruction
stringlengths 0
30k
⌀ |
---|
Too many records cannot import in the Web app |
|python|nginx|nginx-reverse-proxy| |
null |
I am using `react-native-date-picker:^4.4.0` package. When I've updated my project's react-native version to `0.73.3` from `0.62.7` it stoped working properly. Now, when I tap the field to open picker it gives me an error both on Android and IOS.
```
ERROR TypeError: null is not an object (evaluating 'NativeModule.openPicker')
```
In code I use it like that:
```
import React from 'react';
import { Text, TextInput, TouchableOpacity, Keyboard } from 'react-native';
import DatePicker from 'react-native-date-picker';
import moment from 'moment';
import i18n from 'app/localize/i18n';
import styles from './styles';
const Input = React.memo(({ mode, label, input, style, minimumDate, maximumDate, ...rest }) => {
const [date, setDate] = React.useState(new Date());
const [open, setOpen] = React.useState(false);
return (
<DatePicker
modal
mode={mode}
open={open}
date={date}
title={null}
theme='light'
minimumDate={minimumDate}
maximumDate={maximumDate}
onConfirm={handleConfirm}
onCancel={() => setOpen(false)}
confirmText={i18n.t('action.confirm')}
cancelText={i18n.t('action.cancel')}
/>
</TouchableOpacity>
);
});
export default Input;
```
I know that some methods are missing, but do not pay attention to that, I've removed them on purpose.
Also, I've tried some other date selection packages, but I encounter errors with them also, like `@react-native-community/datetimepicker:7.6.2` gives an error
```
'requireNativeComponent: "RNDatePicker" was not found in the UIManager.'
``` |
For this problem: https://leetcode.com/problems/search-suggestions-system/solution/, solution 1 states that for Java, _"there is an additional complexity of O(m^2) due to Strings being immutable, here m is the length of searchWord.") I am really scratching my head about this. Why the heck does immutability of string cause an additional runtime of O(m^2)?
|
I have tables that have hundreds of rows displayed per page, and each row has inputs that can be changed by the user. I want to send only the updated data to the backend so that not too much data will be sent. There is a "save changes" button at the top.
I am not using a form element currently (So to not send the entire table)
What I do is, I give each `<tr>` the row id from the database as a `dataset` attribute, and listen to changes on inputs, then if one of the values of a row is changed, I add this entire row and its inputs to an object that holds all the changed rows. This object is then sent to the backend
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let updatedData = {};
let table1Form = document.querySelector('#table_1');
table1Form.addEventListener("change", (event) => {
let row = event.target.closest('tr');
let rowId = row.dataset.dbRowId;
let rowInputs = row.querySelectorAll('input');
updatedData[rowId] = {};
rowInputs.forEach((input) => {
if (input.type === "checkbox") {
updatedData[rowId][input.name] = input.checked;
} else {
updatedData[rowId][input.name] = input.value;
}
});
});
document.querySelector("#save-changes").addEventListener("click", () => {
console.log(updatedData);
});
<!-- language: lang-html -->
<button id="save-changes">Save Changes</button>
<table id="table_1">
<tr data-db-row-id="1">
<td><input type="text" name="email" value="foo@example.com" /></td>
<td><input type="text" name="name" value="Foo" /></td>
<td><input type="checkbox" name="show" checked="checked" /></td>
</tr>
<tr data-db-row-id="2">
<td><input type="text" name="email" value="bar@example.com" /></td>
<td><input type="text" name="name" value="Bar" /></td>
<td><input type="checkbox" name="show" /></td>
</tr>
</table>
<!-- end snippet -->
But it feels cumbersome, and I need to check for each type of input (in the above example I had to have distinction between the `checkbox` and the `text` inputs because they are evaluated differently
Perhaps there's a better way to do that (with the use of Form Data maybe as well?) |
I have built an ML model API using FastAPI, and this API mostly requires GPU usage. I want to make this API serve at least some amount of parallel requests. To achieve this, I tried to make all the functions def instead of async def so that it can handle requests concurrently (as mentioned [here](https://stackoverflow.com/questions/71516140/fastapi-runs-api-calls-in-serial-instead-of-parallel-fashion/71517830#71517830:~:text=Async/await%20and%20Blocking%20I/O%2Dbound%20or%20CPU%2Dbound%20Operations), [here](https://stackoverflow.com/questions/71186596/how-to-avoid-duplicate-processing-in-python-apiserver/71188190#71188190:~:text=Thus%2C%20when%20you%20use%20def%20instead%20of%20async%20def%20the%20server%20processes%20requests%20concurrently.) and [here](https://youtu.be/nvLRjtvu1nk?t=1697)). Currently, what I am experiencing is that if one request is made, it takes 3 seconds to get output, and if three parallel requests are made, then all users are getting the output in 9 seconds. Here, all users are getting the output at the same time, but as you can see, the time increases as the number of requests increases. However, what I actually want is for all users to get the output in 3 seconds.
I have tried some approaches like ThreadPoolExecutor ([here](https://stackoverflow.com/questions/71516140/fastapi-runs-api-calls-in-serial-instead-of-parallel-fashion/71517830#71517830:~:text=loop%20%3D%20asyncio.get_running_loop()%0Awith%20concurrent.futures.ThreadPoolExecutor()%20as%20pool%3A%0A%20%20%20%20res%20%3D%20await%20loop.run_in_executor(pool%2C%20cpu_bound_task%2C%20contents))), ProcessPoolExecutor ([here](https://stackoverflow.com/questions/71613305/how-to-process-requests-from-multiiple-users-using-ml-model-and-fastapi#:~:text=Alternatively%2C%20as%20described)), Asyncio ([here](https://stackoverflow.com/questions/71516140/fastapi-runs-api-calls-in-serial-instead-of-parallel-fashion/71517830#71517830:~:text=import%20asyncio%0A%0Ares%20%3D%20await%20asyncio.to_thread(cpu_bound_task%2C%20contents))), run_in_threadpool ([here](https://github.com/tiangolo/fastapi/issues/1066#issuecomment-612940187)), but none of these methods worked for me.
This is the how my api code looks like with simple def:
```
from fastapi import Depends, FastAPI, File, UploadFile, Response
import uvicorn
class Model_loading():
def __init__():
self.model = torch.load('model.pth')
app = Fastapi()
model_instance = Model_loading()
def gpu_based_processing(x):
---- doing some gpu based computation ----
return result
@app.post('/model-testing')
def my_function(file: UploadFile = File(...)):
---- doing some initial preprocessing ----
output = gpu_based_processing(x)
return Response(content=output , media_type="image/jpg")
```
Additionally, I have observed a behavior where making 20 parallel requests to the above API leads to a CUDA out-of-memory error. Even with only 20 requests, it is unable to handle them. How can I address the CUDA memory issue and manage handling multiple parallel requests simultaneously?
|
How to handle multiple parallel requests in FastAPI for an ML model API |
|machine-learning|cuda|python-asyncio|fastapi| |
null |
Which approach is the better use of `HttpClient` in .NET Framework 4.7?
In terms of socket exhaustion and thread safe? Both are reusing `HttpClient` instance, right?
I can't implement `IHttpClientFactory` right now. It is difficult to us to implement dependency injection
First code snippet:
```
class Program
{
private static HttpClient httpClient;
static void Main(string[] args)
{
httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("your base url");
// add any default headers here also
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minute timeout
MainAsync().Wait();
}
static async Task MainAsync()
{
await new MyClass(httpClient).StartAsync();
}
}
public class MyClass
{
private Dictionary<string, string> myDictionary;
private readonly HttpClient httpClient;
public MyClass(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task StartAsync()
{
myDictionary = await UploadAsync("some file path");
}
public async Task<Dictionary<string, string>> UploadAsync(string filePath)
{
byte[] fileContents;
using (FileStream stream = File.Open(filePath, FileMode.Open))
{
fileContents = new byte[stream.Length];
await stream.ReadAsync(fileContents, 0, (int)stream.Length);
}
HttpRequestMessage requestMessage = new HttpRequestMessage();
// your request stuff here
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
// parse response and return the dictionary
}
}
```
Second code snippet:
```
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
}
static async Task MainAsync()
{
await new MyClass().StartAsync();
}
}
public class MyClass
{
private Dictionary<string, string> myDictionary;
private static readonly HttpClient httpClient= = new HttpClient() { BaseAddress = new Uri("your base url"), Timeout = new TimeSpan(0, 2, 0) };
public async Task StartAsync()
{
myDictionary = await UploadAsync("some file path");
}
public async Task<Dictionary<string, string>> UploadAsync(string filePath)
{
byte[] fileContents;
using (FileStream stream = File.Open(filePath, FileMode.Open))
{
fileContents = new byte[stream.Length];
await stream.ReadAsync(fileContents, 0, (int)stream.Length);
}
HttpRequestMessage requestMessage = new HttpRequestMessage();
// your request stuff here
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
// parse response and return the dictionary
}
}
```
I'm expecting to resolve socket exhaustion problem. |
When writing a LINQ query with multiple "and" conditions, should I write a single `where` clause containing `&&` or multiple `where` clauses, one for each conditon?
static void Main()
{
var ints = new List<int>(Enumerable.Range(-10, 20));
var positiveEvensA = from i in ints
where (i > 0) && ((i % 2) == 0)
select i;
var positiveEvensB = from i in ints
where i > 0 where (i % 2) == 0
select i;
System.Diagnostics.Debug.Assert(positiveEvensA.Count() ==
positiveEvensB.Count());
}
Is there any difference other than personal preference or coding style (long lines, readability, etc.) between *positiveEvensA* and *positiveEvensB*?
One possible difference that comes to mind is that different LINQ providers may be able to better cope with multiple `where`s rather than a more complex expression; is this true?
|
Ngrok does not receive the response from my local application when a webhook is tunneled to my local application.
The Ngrok UI shows:
> Waiting to receive a response from your server (17 minutes so far).
My application however shows in the logs that the request was correctly received, processed and a 200 status code was sent back.
Ngrok was started like this:
ngrok http --host-header="api.myapp.local:80" api.myapp.local:80
And is appearently working correct:
> Forwarding https://xxx-xxx.ngrok-free.app -> http://api.myapp.local:80
Why does ngrok not receive the response and forwards it back into the tunnel? |
Ngrok does not receive response |
|ngrok| |
{"OriginalQuestionIds":[4660142],"Voters":[{"Id":687262,"DisplayName":"BugFinder"},{"Id":328193,"DisplayName":"David","BindingReason":{"GoldTagBadge":"c#"}}]} |
The main issues i think you're having are adding the attributs to the root element:
- `xmlns="http://www.sefaz.am.gov.br/autodesembaraco" `
- `xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"`
- `xsi:schemaLocation="http://www.sefaz.am.gov.br/autodesembaraco enviDeclaracaoMensalAuto_v1.02.xsd"`
The issue was with how you're creating the namespaces schema location:
```
Dim doc As New MSXML2.DOMDocument60
Dim root As IXMLDOMNode
Dim nmsp As String, xsi As String, schemaLocation As String
' namespaces and schema location
nmsp = "http://www.sefaz.am.gov.br/autodesembaraco"
xsi = "http://www.w3.org/2001/XMLSchema-instance"
schemaLocation = "http://www.sefaz.am.gov.br/autodesembaraco enviDeclaracaoMensalAuto_v1.02.xsd"
```
1. Create the root element by passing the namespace:
```
' Create the root element - with namespace - by using createNode (NODE_ELEMENT = 1)
Set root = doc.createNode(NODE_ELEMENT, "enviDeclaracaoAutodesembaraco", nmsp)
doc.appendChild root
```
2. Declare the `xsi` namespace:
```
' Add xmlns:xsi attribute
Set xsiAttr = doc.createAttribute("xmlns:xsi")
xsiAttr.Value = xsi
root.Attributes.setNamedItem xsiAttr
```
3. Add the `schemaLocation`:
```
' Add xsi:schemaLocation attribute
Set schemaLocationAttr = doc.createAttribute("xsi:schemaLocation")
schemaLocationAttr.Value = schemaLocation
```
|
I'm not at Excel to try this right now, but it looks like this will not producing the range string you want:
```
.Range("A:A" & (fVal.Row)).Copy
```
If fVal.Row is row 27 ... this makes A:A27. Maybe VBA is failing here rather than throwing an error.
I think you want:
```
.Range("A" & (fVal.Row) & ":A").Copy
```
If you don't want to explicitly include the row of the flag/found text, add one to fVal.Row before your string concatenation. |
```
SELECT *
FROM (
SELECT 'name' col, name, count(*) c FROM mytable WHERE gender = 'male' group by name union all
SELECT 'gender', gender, count(*) c FROM mytable WHERE gender = 'male' group by gender union all
SELECT 'image', image, count(*) c FROM mytable WHERE gender = 'male' group by image union all
SELECT 'browser', browser, count(*) c FROM mytable WHERE gender = 'male' group by browser union all
SELECT 'os', os, count(*) c FROM mytable WHERE gender = 'male' group by os
) x
WHERE x.c = (SELECT count(*) FROM mytable WHERE gender = 'male');
;
```
Solution for `female` is the same, just replace 'male' by 'female'.
see: [DBFIDDLE](https://dbfiddle.uk/dUIg27qB) |
Does anyone have a simple telegram client example written in C# that can be run on android?
* I found simple java example for android: https://github.com/androidmads/TelegramBotSample
* I found simple C# example for console application: https://github.com/tdlib/td
But I need a simple example that I can just download and run for android.
In general I do not care what android stack is used (but please let me know what to download and install on linux machine) - it might be even cross-platform game engine (but free to use) :). Of course the less to install the better.
Thanks. |
Telegram for android on C# |
|c#|android|.net|telegram|telegram-bot| |
I'm getting an inexplicable error in my Eclipse IDE:
The type java.util.Collection cannot be resolved. It is indirectly referenced from required type picocli.CommandLine
It is not allowing me to iterate a List object like the following:
```
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import gov.uscourts.bnc.InputReader;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
...
List<ServerRecord> data = execute(hostnames);
for (ServerRecord record : data) {
hostInfoList.add(new String[] { record.hostname(), record.ip(), record.mac(), record.os(),
record.release(), record.version(), record.cpu(), record.memory(), record.name(),
record.vmware(), record.bios() });
}
```
"data" is underlined in red and it says: Can only iterate over an array or an instance of java.lang.Iterable
Tried cleaning the project, rebuilding, checked Java version (21), updated Maven project, pom.xml specified target and source to be 21, deleted project and recreated it. Same error.
Here is my pom.xml:
```
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>gov.uscourts.bnc.app</groupId>
<artifactId>server-query</artifactId>
<version>1.0.0</version>
<name>server-query</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>
gov.uscourts.bnc.app.CollectServerData
</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>gov.uscourts.bnc</groupId>
<artifactId>bnc</artifactId>
<version>1.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.picocli/picocli -->
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>4.7.5</version>
</dependency>
</dependencies>
</project>
```
|
Which approach is better use of HttpClient in .NET Framework 4.7? |
|c#|httpclient|dotnet-httpclient|.net-4.7|sendasync| |
Got the following result when I ran flutter doctor:
Network resources
X A cryptographic error occurred while checking "https://pub.dev/": Handshake error in client
You may be experiencing a man-in-the-middle attack, your network may be compromised, or you may have malware installed on your computer.
X A cryptographic error occurred while checking "https://storage.googleapis.com/": Handshake error in client You may be experiencing a man-in-the-middle attack, your network may be compromised, or you may have malware
installed on your computer.
X A cryptographic error occurred while checking "https://maven.google.com/": Handshake error in client You may be experiencing a man-in-the-middle attack, your network may be compromised, or you may have malware installed on your computer.
When I tried to run flutter doctor (as I was getting some errors loading network image in an app) I ran into some issues in network resources part .
|
`Inheritance` -> Use to inherit the properties/methods of the class (`AbstractClass`) Since the class is abstract, its just defines the common structure definitions, that must be present in the children that inherit it!
When you do inheritance, there is no need for adding in the providers array, seems like an unnecessary step IMHO
Abstract class cannot be used as a component, **its just used when you need to define a hierarchy of classes that share common attributes and behaviors** |
I found the reason why the extracted values are different. If the `<w:pixelsPerInch w:val="144"/>` attribute is set in the WebSettings.xml file of Word, the result obtained will be different from the default result without this attribute |
For the Same wifi connection of computer and mobile.
All these answers are right but they did not mention that the IP address must be the wifi IP.
if you run the program locally and your wifi is from a **Wi-Fi router** then the IP should be Wi-Fi IP.
**[Picture is Here][1]**
[1]: https://i.stack.imgur.com/Q1sW8.png |
Try
Optional<User> findByEmailAndDeletedAt(String email, DateTime deletedAt);
And call it using
repo.findByEmailAndDeletedAt(email, null); |
Trying to apt update and I am getting this, due to this I cannot install playwright as it fails when I do so
I get this every time i do so
```none
Err:13 https://download.docker.com/linux/debian jammy Release
404 Not Found [IP: 108.158.245.93 443]
...none
Reading package lists... Done
E: The repository 'https://download.docker.com/linux/debian jammy Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
```
I tried changing the docker.list value but no change here. also can anybody point me to where I can change or remove
```none
Err:13 https://download.docker.com/linux/debian jammy Release
404 Not Found [IP: 108.158.245.93 443]
``` |
#### Solutions
1. Three ways
- For small projects: write a `compile_flags.txt`:
```
-std=c++11
```
- For big projects: generate `complie_commands.json` by a build system like CMake, which can be enabled by adding this to your CMakeLists.txt file:
```txt
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
```
- If no compilation database(`compile_flags.txt`/`complie_commands.json`) is found, you can do this in your vscode:
- `cmd/ctrl + shift + p`: Preferences: Open User Settings (JSON)
- Add these into your `settings.json` file:
```json
"clangd.fallbackFlags": [
"-std=c++11",
// do not add line below or it will cause conflict
// "-std=c99",
],
```
- `cmd/ctrl + shift + p`: clangd: Restart language server
2. You just can't set C & C++ standard at the same time or it will conflict. But you can make your compiler treat your .h as C/C++ by `-x`
```shell
> man clang
-x <language>
Treat subsequent input files as having type language.
```
> see: https://stackoverflow.com/a/19413311/17001641
So, the final answer is use `compile_flags.txt` or build system with `complie_commands.json` instead.
#### Explaination
clangd first check for a [compilation database](https://clangd.llvm.org/design/compile-commands#compilation-databases) in the directory containing the source file, and then walk up into parent directories until we find one. The compilation database can be:
1. a file named `compile_commands.json` listing commands for **each** file. Usually generated by a build system like CMake.
- Tedious and **error-prone** to write by hand
- See: [format and example](https://clang.llvm.org/docs/JSONCompilationDatabase.html#format)
1. a file named `compile_flags.txt` listing flags to be used for **all** files. Typically hand-authored for simple projects.
- easy to use in small projects
3. If no compilation database is found, use `clangd.fallbackFlags`.
Note: this answer will be improved by time.
|
This is intended behavior as Health Connect permissions follow the standard permissions model on Android 14+. You can see the reference to this behavior in the Android developer documentation here: https://developer.android.com/training/permissions/requesting#remove-access |
I have two xaml files:
- one (present in solution1) I can see in the design view.
- the other one (present in solution2) I can't see in the design view.
There's nothing wrong with the second xaml: I can see it when I run the application. But I would like to see it in design view (if ever I need to perform a modification, I'll see what I'm doing).
In order to learn, I decided to open the one in solution1 in design view and see in the "Output" window how everything should behave, and based on that, I'd learn what to do.
That failed, because, when opening a xaml file in design view, nothing is added to Visual Studio's "Output" window (nothing in the "Debug" chapter, nothing either in "Build", "Build order" or the other chapters).
For your information, my xaml-related settings look as follows:
[![enter image description here][1]][1]
Where can I see what happens in the design view of Visual Studio (2022) while opening a xaml file?
Thanks in advance
[1]: https://i.stack.imgur.com/i1hmL.png |
Does Visual Studio (2022) have a "XAML design debug output" window? |
I am not familiar with `bytemuck`'s internals, but I would guess this is a soundness requirement, as `bytemuck` certainly works with `unsafe` code to perform bit fiddling.
The actual specification of the `Copy` trait is that a type `T` can be `Copy` if a value `x: T` only "owns its bits" (as in Rust's ownership system). For instance, an integer is `Copy` because when you own an integer, you just own the bits that represent this integer, whereas when you own a `Box<i32>`, you don't just own the bits used to represent the box (which, in the end, is just a pointer). You also own what is pointed by the pointer.
A corollary of being `Copy` is that any value of a `Copy` type is that moving it is the same operation as `clone`ing it (which is why `Clone` is a supertrait of `Copy`). This is because moving a value in Rust is defined as a bitwise copy of the bits of the underlying representation, from one location to an other.
In particular, it is not true that having a type not being `Copy` prevents it from being bitwise copied: **every value can be implicitely bitwise-copied whenever it is moved**. So having your type which is a huge blob of data not being `Copy` does *not* prevent it from being bitwise copied around.
However, it is true that it is expected that `Copy` types are cheap to copy, because otherwise Rust prefers users having to explicitly write `clone`, to ensure that they consciously know they are doing an expensive operation.
For this reason, you might indeed not want to tag your type as `Copy`. To solve that problem, you could use the newtype pattern: create a type `struct MyPublicStructure(MyStructure)`, which does *not* implement `Copy`. Implement `Copy` and `Pod` for the inner type. Then, simply use that type when you need to do some bit fiddling, and convert back to `MyPublicStructure` when you don't need to do bit fiddling anymore. This way, you can explicitly highlight the parts of your code where you need pay attention that you might accidentally implicitly perform an expensive copy, and your public API is clean. |
Here's how I solved the problem.
Firstly, as the scope of the data grows, you have to give up on looking at all the raw data, because of performance.
What I can do is to reduce the resolution of the data in some way. In prometheus, there are operations named 'overtime': avg_over_time, max_over_time, etc.
If you are curious about the average trend of your raw data, you can use avg_over_time. On the other hand, if you want to capture the spikes that occurred in the raw data, you can apply max_over_time. If you are curious about the dips, you can apply min_over_time. I applied max_over_time to capture the spike at the time.
Naturally, the lookup will be slower because of the extra maths that are being added to the raw data. I was willing to take the performance hit for accurate monitoring. |
I am adding prefab in content at runtime but its not refreshing with new content and I am using fancy scroll view of example of UI extension How can I do that(Fancy scroll example 07) |
How to refresh content in fancy scroll view of UI Extension at runtime Unity |
|unity-game-engine|user-interface| |
{"Voters":[{"Id":5373689,"DisplayName":"Denton Thomas"}],"DeleteType":1} |
{"Voters":[{"Id":21625319,"DisplayName":"TraderInTheMaking"}]} |
0
I am simply creating Elastic Beanstalk and when going to "Set up networking, database, and tags" section and enabling database section it is throwing the below error even I am not providing any parameter related to DB:
Configuration validation exception: Invalid option value: 'db.t2.micro' (Namespace: 'aws:rds:dbinstance', OptionName: 'DBInstanceClass'): DBInstanceClass db.t2.micro not supported for mysql db engine.
I can not choose any value as the option itself is disabled now and to edit I need to enable it and when I an enabling getting the above error.

I tried deleting the resources available previously and nothing there in my AWS console totally empty and still getting this error. |
I faced the same bug a while ago, It only occurs when you have `[autoResize] = true` (it is by default true). So you have to explicitly disable it and handle resizing some other way. |
{"Voters":[{"Id":8690857,"DisplayName":"Drew Reese"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":6463558,"DisplayName":"Lin Du"}],"SiteSpecificCloseReasonIds":[13]} |
I recently received a new Mac computer for work. I regularly use files which have macros built in. I am not the creator of these files/macros and am not an expert in this area.
For one of my files, each time I open it and click "enable macros" I get an error:
>Some controls on this presentation can't be activated. They might not be registered on this computer.
I have confirmed that the macros are functioning properly on the Windows machines of my colleagues. I have also tried a few other macro-enabled files on my Mac which also seem to be functioning properly. Clearly there is some issue with this one file.
I have entered into Visual Basic Editor and confirmed that the code is there. It has been transferred properly via cloud transfer from my old PC to my new Mac. |
|vba|macros|powerpoint| |
import win32api #https://timgolden.me.uk/pywin32-docs/win32api.html
print("GetWindowsDirectory:", win32api.GetWindowsDirectory()[0])
#or
print("GetSystemDirectory:", win32api.GetSystemDirectory())
Output:
> GetWindowsDirectory: C
>
> GetSystemDirectory: C:\Windows\system32 |
**Description**:
I recently purchased a Moto e22 device running Android 12 and encountered several issues while trying to build my Flutter project using Android Studio.
**First Problem:**
After creating a new Flutter project with no modifications, when I attempted to run the project from Android Studio using the play button, the build succeeded, but I encountered a white screen with no logs in the run tab. However, if I manually kill the app and relaunch it on the Android device without any further build from Android Studio, it runs without any issues.
**Second Problem:**
When I tried running the project using flutter run --verbose or flutter run --debug, the app installed successfully on my Android device, but I got stuck with the message "Waiting for VM Service port to be available" or "Built build/app/outputs/flutter-apk/app-debug.apk" without any further actions such as hot reload or hot restart.
Here's a summary of my Flutter doctor output:
this is my flutter doctor summary
```
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel main, 3.21.0-17.0.pre.19, on macOS 12.6.8 21G725 darwin-x64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[!] Xcode - develop for iOS and macOS (Xcode 14.2)
! CocoaPods 1.12.1 out of date (1.13.0 is recommended).
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To upgrade see https://guides.cocoapods.org/using/getting-started.html#updating-cocoapods for instructions.
[✓] Chrome - develop for the web
[✓] Android Studio (version 2023.2)
[✓] VS Code (version 1.84.2)
[✓] Connected device (3 available)
[✓] Network resources
! Doctor found issues in 1 category.
```
I've attempted various solutions found in threads, including changing the Flutter channel, but the issues persist.
Here's the output of my logcat:
```
2024-03-29 06:58:54.905 669-830 UxUtility ven...hardware.mtkpower@1.0-service E notifyAppState error = NULL
2024-03-29 06:58:54.926 2937-2937 PhoneInterfaceManager com.android.phone E [PhoneIntfMgr] getCarrierPackageNamesForIntentAndPhone: No UICC
2024-03-29 06:58:54.943 3886-3886 AidRoutingManager com.android.nfc E Size of routing table804
2024-03-29 06:58:54.958 681-681 BpTransact...edListener surfaceflinger E Failed to transact (-32)
2024-03-29 06:58:54.958 681-681 BpTransact...edListener surfaceflinger E Failed to transact (-32)
2024-03-29 06:58:54.986 681-834 BufferQueueDebug surfaceflinger E [com.android.settings/com.android.settings.SubSettings#0](this:0xb400007a470532e8,id:-1,api:0,p:-1,c:-1) id info cannot be read from 'com.android.settings/com.android.settings.SubSettings#0'
2024-03-29 06:58:55.381 681-834 BufferQueueDebug surfaceflinger E [Splash Screen com.whimstech.driverapp.new_flutter_project#0](this:0xb400007a47069f68,id:-1,api:0,p:-1,c:-1) id info cannot be read from 'Splash Screen com.whimstech.driverapp.new_flutter_project#0'
2024-03-29 06:58:55.494 669-830 UxUtility ven...hardware.mtkpower@1.0-service E notifyAppState error = NULL
2024-03-29 06:58:55.633 6026-6043 OpenGLRenderer com.android.settings E EglManager::makeCurrent mED = 0x1, surface = 0x0, mEC = 0xb4000078bd6be650, error = EGL_SUCCESS
2024-03-29 06:58:55.741 6249-6271 QT pid-6249 E [QT]file does not exist
2024-03-29 06:58:56.370 681-835 BufferQueueDebug surfaceflinger E [com.whimstech.driverapp.new_flutter_project/com.whimstech.driverapp.new_flutter_project.MainActivity#0](this:0xb400007a47042188,id:-1,api:0,p:-1,c:-1) id info cannot be read from 'com.whimstech.driverapp.new_flutter_project/com.whimstech.driverapp.new_flutter_project.MainActivity#0'
2024-03-29 06:58:56.400 6249-6269 OpenGLRenderer com...driverapp.new_flutter_project E EglManager::makeCurrent mED = 0x1, surface = 0x0, mEC = 0xb4000078bd6b8110, error = EGL_SUCCESS
2024-03-29 06:58:56.400 681-835 BufferQueueDebug surfaceflinger E [SurfaceView[com.whimstech.driverapp.new_flutter_project/com.whimstech.driverapp.new_flutter_project.MainActivity](BLAST)#0](this:0xb400007a47056078,id:-1,api:0,p:-1,c:-1) id info cannot be read from 'SurfaceView[com.whimstech.driverapp.new_flutter_project/com.whimstech.driverapp.new_flutter_project.MainActivity](BLAST)#0'
2024-03-29 06:58:56.407 681-835 HWComposer surfaceflinger E getSupportedContentTypes: getSupportedContentTypes failed for display 0: Unsupported (8)
2024-03-29 06:58:56.413 6249-6276 ion com...driverapp.new_flutter_project E ioctl c0044901 failed with code -1: Invalid argument
2024-03-29 06:59:00.457 24427-4404 WakeLock com.google.android.gms.persistent E GCM_HB_ALARM release without a matched acquire!
2024-03-29 06:59:00.470 6249-6269 OpenGLRenderer com...driverapp.new_flutter_project E fbcNotifyFrameComplete error: undefined symbol: fbcNotifyFrameComplete
2024-03-29 06:59:00.470 6249-6269 OpenGLRenderer com...driverapp.new_flutter_project E fbcNotifyNoRender error: undefined symbol: fbcNotifyNoRender
```
Complete Output of flutter run --verbos
```
[ +13 ms] Stopping app 'app-debug.apk' on moto e22.
[ +1 ms] executing: /Users/ibtihajnaeem/Library/Android/sdk/platform-tools/adb -s ZE2235Q3DM shell am force-stop
com.whimstech.driverapp.new_flutter_project
[ +202 ms] executing: /Users/ibtihajnaeem/Library/Android/sdk/platform-tools/adb -s ZE2235Q3DM shell pm list packages
com.whimstech.driverapp.new_flutter_project
[ +106 ms] package:com.whimstech.driverapp.new_flutter_project
[ +5 ms] executing: /Users/ibtihajnaeem/Library/Android/sdk/platform-tools/adb -s ZE2235Q3DM shell cat
/data/local/tmp/sky.com.whimstech.driverapp.new_flutter_project.sha1
[ +85 ms] d398535fddb940e49abe5dd0a43b3932ccf5e1be
[ +1 ms] Latest build already installed.
[ +2 ms] executing: /Users/ibtihajnaeem/Library/Android/sdk/platform-tools/adb -s ZE2235Q3DM shell -x logcat -v time -t 1
[ +92 ms] --------- beginning of main
03-29 07:25:16.521 E/BpTransactionCompletedListener( 681): Failed to transact (-32)
[ +21 ms] executing: /Users/ibtihajnaeem/Library/Android/sdk/platform-tools/adb -s ZE2235Q3DM shell am start -a android.intent.action.MAIN -c
android.intent.category.LAUNCHER -f 0x20000000 --ez enable-dart-profiling true --ez enable-checked-mode true --ez verify-entry-points true
com.whimstech.driverapp.new_flutter_project/com.whimstech.driverapp.new_flutter_project.MainActivity
[ +124 ms] Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x20000000
cmp=com.whimstech.driverapp.new_flutter_project/.MainActivity (has extras) }
[ +1 ms] Waiting for VM Service port to be available...
```
|
Take a look at the documentation linked below for telebot, specifically for the edit_message_text method. You're passing the parameters in the wrong order, the resultmsg should be the first parameter passed. The corrected code would look like bot.edit_message_text(resultmsg_x, gpid, msg_id)
[Telebot][1]
[1]: https://pytba.readthedocs.io/en/latest/sync_version/index.html#telebot.TeleBot.edit_message_text |
I have a shared config file that's used in a lot of places. My code doesn't care what extension the config file has. However, some packages expect it to be `.js`, others expect it to be `.ts`. E.g. if I name it `config.js`, then I can import it with zx and not Capacitor. Vice-versa if I name it `config.ts`. Also, I've had to name some files `.cjs` in the past just to be able to import them.
zx error importing `config.ts`:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for config.ts
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
at defaultLoad (node:internal/modules/esm/load:143:22)
at async ModuleLoader.load (node:internal/modules/esm/loader:409:7)
at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:291:45) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
Capacitor error importing `config.js`:
Error [ERR_REQUIRE_ESM]: require() of ES Module config.js from
capacitor.config.ts not supported.
Instead change the require of config.js in capacitor.config.ts to a dynamic import() which is
available in all CommonJS modules.
at Object.<anonymous> (capacitor.config.ts:3:21)
at require.extensions..ts (node_modules/@capacitor/cli/dist/util/node.js:35:72)
The only solution I can think of is just having 2 identical files with different extensions. Is it possible to import/require a file and ignore the extension? E.g. import a `.ts` file and pretend it's a `.js` file, the file won't have any Typescript-specific syntax. |
|visual-studio|xaml|debugging|visual-studio-2022|output-window| |
I've been delving into Ktor to learn about Websockets, but despite spending numerous hours researching similar questions, I'm still unable to pinpoint the root of my issue. I'm trying to open multiple websocket sessions using Ktor to be able to send and receive messages between the users. However, once I create a websocket session, it closes itself. I'm initializing the websocket session once the main login page of my application opens up.
I've also tried understanding the answer to this [same problem](https://stackoverflow.com/questions/65314683/how-to-keep-a-kotlin-ktor-websocket-open), but they're using a html file. Is there another solution to this problem?
Here is the code where I create the websocket session:
```
// In CommManager object
suspend fun receiveMessage(session: DefaultWebSocketSession) {
var text = ""
while (connected.get() == true) {
try {
for (othersMessages in session.incoming) {
othersMessages as? Frame.Text ?: continue
text = othersMessages.readText()
println(text)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
// In the login page
suspend fun createWebsocketSession() {
val session = client.webSocketSession(method = HttpMethod.Get, host = "hosturl", port = 8080, path = "/webSocketSession")
CommManager.connected.set(true)
CommManager.receiveMessage(session)
}
init
{
// Initialize Websocket session here
coroutine.launch()
{
createWebsocketSession()
}
}
```
As for the server side:
```
routing()
{
webSocket("/webSocketSession") {
ConnectionsHandler.connectWebSocketSession(this)
}
}
// ConnectionsHandler object
fun connectWebSocketSession(session: DefaultWebSocketSession){
println("adding new user")
val thisConnection = Connection(session)
webSocketUserList += thisConnection
println("${thisConnection.name} is connected!")
}
```
After running the server and then the client, this is what I get as output from the server:
```
Route resolve result:
SUCCESS @ /webSocketSession/(method:GET)/(header:Connection = Upgrade)/(header:Upgrade = websocket)
2024-03-19 09:35:25.142 [eventLoopGroupProxy-4-1] TRACE i.k.s.p.c.ContentNegotiation - Skipping because body is already converted.
2024-03-19 09:35:25.165 [eventLoopGroupProxy-3-5] TRACE io.ktor.websocket.WebSocket - Starting default WebSocketSession(io.ktor.websocket.DefaultWebSocketSessionImpl@49a741b5) with negotiated extensions:
2024-03-19 09:35:25.169 [eventLoopGroupProxy-3-5] TRACE io.ktor.server.websocket.WebSockets - Starting websocket session for /webSocketSession
adding new user
user0 is connected!
2024-03-19 09:35:25.218 [eventLoopGroupProxy-3-5] TRACE io.ktor.websocket.WebSocket - Sending Frame CLOSE (fin=true, buffer len = 2) from session io.ktor.websocket.DefaultWebSocketSessionImpl@49a741b5
2024-03-19 09:35:25.222 [eventLoopGroupProxy-3-5] TRACE io.ktor.websocket.WebSocket - Sending Close Sequence for session io.ktor.websocket.DefaultWebSocketSessionImpl@49a741b5 with reason CloseReason(reason=NORMAL, message=) and exception null
2024-03-19 09:35:25.251 [eventLoopGroupProxy-3-3] TRACE io.ktor.websocket.WebSocket - WebSocketSession(StandaloneCoroutine{Active}@2cea43ee) receiving frame Frame CLOSE (fin=true, buffer len = 2)
```
From my understanding, "sending Frame CLOSE" means that it is closing the websocket session, but I haven't specified any command to do so in the client or the server. Am I missing something in the server side to keep the session running? If you need more information about the problem, please tell me and I'll edit the post.
|
You can also add the following to `dash_table.DataTable()`:
```
css = [{
"selector": ".Select-menu-outer",
"rule": 'display : block !important'
}]
``` |
You can set the token expiration time by passing 'expires_delta' parameter to the 'create_access_token' function:
```python
from datetime import timedelta
from flask_jwt_extended import create_access_token
from flask_login import current_user
expires = timedelta(days=3)
token = create_access_token(identity=str(current_user.id), expires_delta=expires)
``` |
While Adding the useContext in my react app. I am getting the
Please find the code snippet below.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import AuthProvider from "./compnents/context/AuthProvider";
import { BrowserRouter, Routes, Route } from "react-router-dom";
ReactDOM.createRoot(document.getElementById("root")).render(
// Ensure contextValue is a function before rendering
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/*" element={<App />}></Route>
</Routes>
</AuthProvider>
</BrowserRouter>
</React.StrictMode>
<!-- end snippet -->
|
React Hook useContext: Uncaught TypeError: render2 is not a function |
|reactjs|react-router-dom|hook| |
`std::set` and `std::unordered_set` on a `string` both pull out the unique characters only, but neither leaves the characters in the original order as they appeared in the string.
There's so much of the STL I am ignorant of, but I wondered if there was an STL way of getting just the unique characters from the string WITHOUT losing the original order and WITHOUT resorting to loops. I can do it with iterators, loops and, for example, `std::remove` , but I wondered if there was a more elegant way. This thought train was triggered by today's GeeksforGeeks problem, so the test string was `"geEksforGEeks"` which should end up as `"geEksforG"` (case sensitive, `'g' != 'G'`).
Thoughts?
|
STL: Keeping Only Unique String Characters AND Preserving Order |
|c++|stl|unique| |
With anything that involves sending messages, always try looking at the actual messages: for IP networking, tcpdump; for D-Bus, use `busctl monitor` or `dbus-monitor`.
For basic types, sd_bus_set_property() doesn't want pointers to the value – it wants the value directly. See the manual for [_sd_bus_message_append(3)_][1], which has a table with "Expected C type" for each type specifier. (That is, it's more like printf() than ioctl().)
(The second example with sd_bus_message_append_basic() _does_ want a pointer,
[1]: https://www.freedesktop.org/software/systemd/man/latest/sd_bus_message_append.html |
The `sprintf` alone won't do in a `for` loop, you need wrap it in `print`.
> for (i in n) {
+ poblacion <- rnorm(N, 10, 10)
+ mu.pob <- mean(poblacion)
+ sd.pob <- sd(poblacion)
+ p <- vector(length=k)
+ for (j in 1:k) {
+ muestra <- poblacion[sample(1:N, length(n))]
+ p[j] <- t.test(muestra, mu=mu.pob)$p.value
+ }
+ a_teo <- 0.05
+ a_emp <- length(p[p<a_teo])/k
+ print(sprintf("alpha_teo = %.3f <-> alpha_emp = %.3f", a_teo, a_emp))
+ }
[1] "alpha_teo = 0.050 <-> alpha_emp = 0.056"
[1] "alpha_teo = 0.050 <-> alpha_emp = 0.050"
[1] "alpha_teo = 0.050 <-> alpha_emp = 0.064"
[1] "alpha_teo = 0.050 <-> alpha_emp = 0.048"
A more R-ish way to do this would be to wrap the logic in a function.
> comp_fn <- \(N, n, k, alpha=.05, verbose=FALSE) {
+ poblacion <- rnorm(N, 10, 10)
+ mu.pob <- mean(poblacion)
+ sd.pob <- sd(poblacion)
+ p <- replicate(k, t.test(poblacion[sample(1:N, n)], mu=mu.pob)$p.value)
+ a_emp <- length(p[p < alpha])/k
+ if (verbose) {
+ message(sprintf("alpha_teo = %.3f <-> alpha_emp = %.3f", a_teo, a_emp))
+ }
+ c(a_teo, a_emp)
+ }
>
> set.seed(1)
> comp_fn(1000, 20, 500)
[1] 0.050 0.058
> comp_fn(1000, 20, 500, verbose=TRUE)
alpha_teo = 0.050 <-> alpha_emp = 0.042
[1] 0.050 0.042
To loop over different arguments, `mapply` is your friend.
> set.seed(1)
> mapply(comp_fn, 1000, c(2, 10, 15, 20), 500)
[,1] [,2] [,3] [,4]
[1,] 0.050 0.050 0.050 0.050
[2,] 0.058 0.054 0.048 0.046 |
Node import/require files while ignoring file extension? |
|node.js|typescript| |
The example seems to be adopted from https://stackoverflow.com/questions/58119428/how-to-set-default-value-for-row-labels-in-pivot-table-using-poi/58137844#58137844. There my answer explains the basics.
The difference is that the example there uses text items to filter. Your example needs numeric items to filter.
For text items `sharedItems` in `pivotCacheDefinition` - `cacheFields` - `cacheField` are `s`-items.
For numeric items `sharedItems` in `pivotCacheDefinition` - `cacheFields` - `cacheField` are `n`-items. But while `sharedItems` having `s`-items don't need furthrt settings, `sharedItems` having `n`-items need further settings about the number type. For example:
<sharedItems containsSemiMixedTypes="false" containsString="false" containsNumber="true" containsInteger="true">
<n v="1"/>
<n v="2"/>
<n v="3"/>
</sharedItems>
Code differences:
For text items:
for (String item : uniqueItems) {
...
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(0)
.getSharedItems().addNewS().setV(item);
...
}
For numeric items:
for (Integer item : uniqueItems) {
...
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsSemiMixedTypes(false);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsString(false);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsNumber(true);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsInteger(true);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.addNewN().setV(item);
...
}
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
class PivotIntegerFilter {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./pivottable.xlsx")) {
Sheet pivotSheet = workbook.createSheet("Pivot");
Sheet dataSheet = workbook.createSheet("Data");
setCellData(dataSheet, workbook);
AreaReference areaReference = new AreaReference("A1:E5", SpreadsheetVersion.EXCEL2007);
XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference, new CellReference("A4"), dataSheet);
pivotTable.addRowLabel(0);
pivotTable.addReportFilter(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2);
java.util.TreeSet<Integer> uniqueItems = new java.util.TreeSet<Integer>();
for (int r = areaReference.getFirstCell().getRow() + 1; r < areaReference.getLastCell().getRow() + 1; r++) {
uniqueItems.add((int) dataSheet.getRow(r).getCell(1).getNumericCellValue());
}
int i = 0;
for (Integer item : uniqueItems) {
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).getItems().getItemArray(i).unsetT();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).getItems().getItemArray(i).setX((long) i);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsSemiMixedTypes(false);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsString(false);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsNumber(true);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.setContainsInteger(true);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(1).getSharedItems()
.addNewN().setV(item);
if (!(item == 3)) {
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).getItems().getItemArray(i).setH(true);
}
i++;
}
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).setMultipleItemSelectionAllowed(true);
workbook.write(fileout);
}
}
static void setCellData(Sheet sheet, Workbook workbook) {
Row row;
Cell cell;
Object[][] data = new Object[][]{
new Object[]{"PARTY", "SNO", "VOTES", "Total Count", "Total Absent"},
new Object[]{"REPUBLICAN", 1, 10d, "?", "?"},
new Object[]{"DEMOCRAT", 3, 5d, "?", "?"},
new Object[]{"AMERICAN INDEP", 3, 10d, "?", "?"},
new Object[]{"DECLINED", 2, 10d, "?", "?"}
};
for (int r = 0; r < data.length; r++) {
row = sheet.createRow(r);
Object[] rowData = data[r];
for (int c = 0; c < rowData.length; c++) {
cell = row.createCell(c);
if (rowData[c] instanceof String) {
cell.setCellValue((String) rowData[c]);
} else if (rowData[c] instanceof Double) {
cell.setCellValue((Double) rowData[c]);
} else if (rowData[c] instanceof Integer) {
cell.setCellValue((Integer) rowData[c]);
DataFormat format = workbook.createDataFormat();
CellStyle integerCellStyle = workbook.createCellStyle();
integerCellStyle.setDataFormat(format.getFormat("0"));
cell.setCellStyle(integerCellStyle);
}
}
}
}
}
|
I am looking for a way to read data incrementally from the PVOs to the GCP. My initial hunch was to use Apache Airflow, but I think that would not serve the purpose. Later, I came across the BICC scheduled incremental extracts using the connector console but I am not able to locate any example to load data to GCS. I am not sure if BICC has that capability yet. Can someone guide me to any example that could help me meet the requirement?
Any help/guidance is appreciated.

- I went throguh the documentations but could not locate any way to connect to GCP
- the apprach to look for Apache Airflow did not also work as PVO are views combining multiple base tables and are exposed by BICC (Business Intelligence Cloud Connector) and we don't get access to the base Oracle tables directly |
I try to make my problem to sample. Something like this:
CREATE TABLE test
(
[No] [bigint] IDENTITY(1, 1) PRIMARY key,
[Title] [nvarchar](100) NOT NULL
)
GO
INSERT INTO test(Title)
SELECT '개인경비 청구서 작성 및 교육'
UNION ALL
SELECT 'a'
CREATE PROCEDURE [dbo].[Notice_Dels]
@SerchText NVARCHAR(200)
AS
BEGIN
DECLARE @Query NVARCHAR(MAX);
SET @Query = N'SELECT N.No, N.Title
FROM test N
WHERE N.Title LIKE N''%@SerchText%'' '
PRINT @Query
EXEC SP_EXECUTESQL @Query, N' @SerchText NVARCHAR(200)', @SerchText
END
EXEC [Notice_Dels] N'개인경비';
It returns no row. How can I fix it? |
I'm currently trying to create a custom ScrollViewer that has a zoom and pan functionality implementing UIKit's ScrollView but there's a bug that whenever the screen's zoomed and the app resumes from a sleep state, the view changes its position, shrinks its ScrollHeight , and zooming out positions the grid on the upper left of the screen. (Refer to the screenshot below.)
It could be a bug in .NET Maui itself but I'm not sure. (on Xamarin.Forms the grid's position resets to the middle of the screen.)
Is there a work-around or a way to resolve it?
UPDATE: Pressing the button while the grid's zoomed also moves the scrollposition, and changes the scrollview's height.
[View after zooming out:][1]
Here's the code below to reproduce the problem:
**MainPage.xaml**
```
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:MauiAppTest"
x:Class="MauiAppTest.MainPage">
<controls:ZoomableScrollView>
<Grid Background="pink">
<VerticalStackLayout
Padding="30,0"
Spacing="25">
<Image
Source="dotnet_bot.png"
HeightRequest="185"
Aspect="AspectFit"
SemanticProperties.Description="dot net bot in a race car number eight" />
<Label
Text="Hello, World!"
Style="{StaticResource Headline}"
SemanticProperties.HeadingLevel="Level1" />
<Label
Text="Welcome to .NET Multi-platform App UI"
Style="{StaticResource SubHeadline}"
SemanticProperties.HeadingLevel="Level2"
SemanticProperties.Description="Welcome to dot net Multi platform App U I" />
<Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnCounterClicked"
HorizontalOptions="Fill" />
</VerticalStackLayout>
</Grid>
</controls:ZoomableScrollView>
</ContentPage>
```
**ZoomableScrollView.cs (Custom ScrollView)**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MauiAppTest
{
public class ZoomableScrollView : ScrollView
{
}
}
```
**ZoomableScrollViewHandler.cs**
```
using Microsoft.Maui.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIKit;
namespace MauiAppTest.Platforms.iOS
{
public class ZoomableScrollViewHandler : ScrollViewHandler
{
protected override void ConnectHandler(UIScrollView platformView)
{
base.ConnectHandler(platformView);
if(platformView != null)
{
platformView.MinimumZoomScale = 1;
platformView.MaximumZoomScale = 3;
platformView.ViewForZoomingInScrollView += (UIScrollView sv) =>
{
return platformView.Subviews[0];
};
}
}
protected override void DisconnectHandler(UIScrollView platformView)
{
base.DisconnectHandler(platformView);
}
}
}
```
**MauiProgram.cs**
```
using Microsoft.Extensions.Logging;
#if IOS
using MauiAppTest.Platforms.iOS;
#endif
namespace MauiAppTest
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
#if IOS
builder.ConfigureMauiHandlers(handlers =>
handlers.AddHandler(typeof(ZoomableScrollView),typeof(ZoomableScrollViewHandler)));
#endif
#if DEBUG
builder.Logging.AddDebug();
#endif
return builder.Build();
}
}
}
```
I expected that the ScrollViewer would work without problem as it worked on Xamarin.Forms.
Things I've tried including:
・Using a ScrollViewRenderer(with the use of maui.compatibility)
・Tried getting the ZoomScale and ContentOffset during OnSleep, then setting them again during OnResume.
[1]: https://i.stack.imgur.com/FLTYe.jpg
UPDATE: Here's the code in Xamarin.Forms
**ZoomableScrollView.cs (Custom ScrollView)**
```
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace TestXamarin
{
public class ZoomableScrollView : ScrollView
{
}
}
```
**ZoomableScrollViewRenderer.cs**
```
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestXamarin;
using TestXamarin.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(ZoomableScrollView), typeof(ZoomableScrollViewRenderer))]
namespace TestXamarin.iOS
{
public class ZoomableScrollViewRenderer : ScrollViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
var test = this.Element as ZoomableScrollView;
this.MinimumZoomScale = 1f;
this.MaximumZoomScale = 3f;
this.ViewForZoomingInScrollView += (UIScrollView sv) => { return this.Subviews[0]; };
}
}
}
```
works on both Xamarin.Forms 4.8 and 5.0 (haven't tested on lower versions) |
One option to achieve your desired result would be to conditionally nudge your labels and set the alignment of the labels using e.g. `dplyr::case_when` inside `aes()`. To nudge the position of the labels I make use of `ggplot2::stage()`:
``` r
library(ggplot2)
library(ggsankey)
df <- mtcars |>
make_long(cyl, vs, am, gear, carb)
ggplot(df, aes(
x = x, next_x = next_x,
node = node, next_node = next_node,
fill = factor(node), label = node
)) +
geom_sankey(
flow.alpha = .6,
node.color = "gray30",
space = 20
) +
geom_sankey_label(
aes(
# Shift labels conditional on position
x = stage(x,
after_stat = x + .1 *
dplyr::case_when(
x == 1 ~ -1,
x == 5 ~ 1,
.default = 0
)
),
# Align labels conditional on position
hjust = dplyr::case_when(
x == "cyl" ~ 1,
x == "carb" ~ 0,
.default = .5
)
),
size = 3,
color = "white",
fill = "gray40",
space = 20
) +
scale_fill_viridis_d() +
theme_sankey(base_size = 18) +
theme(
legend.position = "none",
plot.title = element_text(hjust = .5)
) +
labs(x = NULL, title = "Car features")
```
<!-- --> |
null |
You can use a flag, a rookie mistake is to exit a single loop, remember the double break, another practice that is not recommended but necessary in very high performance processes is to use goto and my favorite, a function with a return.
#include <iostream>
// Dont clone vars, use references, for performance
int calc(int &row, int &cols, int &max) {
int sum = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < cols; j++) {
sum += i + j;
if (sum > max) {
return sum;
}
}
}
return sum;
}
int main() {
int rows = 1000;
int cols = 1000;
int max = 1000;
int result = calc(rows, cols, max);
std::cout << "Result: " << result;
return 0;
}
Alternative version, a little more modular:
#include <iostream>
// Dont clone vars, use references, for performance
void calc(int &row, int &cols, int &max, int &result) {
int sum = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < cols; j++) {
sum += i + j;
if (sum > max) {
result = sum;
return;
}
}
}
result = sum;
}
int main() {
int rows = 1000;
int cols = 1000;
int max = 1000;
int result = 0;
calc(rows, cols, max, result);
std::cout << "Result: " << result;
return 0;
}
GOTO example, completely discouraged today:
#include <iostream>
int main() {
int rows = 1000;
int cols = 1000;
int max = 1000;
int result = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result += i + j;
if (result > max) {
goto end;
}
}
}
end:
std::cout << "Result: " << result;
return 0;
}
Break and boolean, nowadays they are discouraged in universities, you get worse performance than using goto because you have to check the break condition all the time although it is a more accepted method:
#include <iostream>
int main() {
int rows = 1000;
int cols = 1000;
int max = 1000;
int result = 0;
bool done = false;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result += i + j;
if (result > max) {
done = true;
break;
}
}
if (done) {
break;
}
}
std::cout << "Result: " << result;
return 0;
}
Conclusion: using a separate function has advantages in real life, in addition to the fact that you can parallelize them more easily (especially for processes where you must compare large amounts of bytes, this is advantageous). |
I think you have a problem in your imports and are currently importing Dataset from another package. This should resolve your error :
from torch.utils.data import Dataset
|
```py
# import libraries
import numpy as np # Corrected indentation and spelling
import torch
import torch.nn as nn
import torch.nn.functional as F # Corrected extra space
from torch.utils.data import DataLoader, TensorDataset # Removed extra dot
import copy
from sklearn.model_selection import train_test_split # Corrected indentation
# for importing data
import torchvision
import matplotlib.pyplot as plt
from IPython import display
display.set_matplotlib_formats('svg') # Corrected indentation and removed extra spaces
```
```py
# download the dataset
cdata = torchvision.datasets.EMNIST(root='emnist', split='letters', download=True)
```
Error:
>URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
how can i solve this problem? |
I don't know how exactly you got the initial matrix. But if you get a correct image with different colors after scaling, then each number in the matrix represents a pixel, not a color component of the pixel. And you lost the colors before you even built the initial matrix.
Also, don't use multidimensional arrays in critical code, they have a very slow implementation. Use nested arrays instead. And don't use the GetLength method inside the for condition, it is called on every iteration.
If you really want to do the matrix transformation you described in the question, then just increment j and l by 3 instead of 1, and work with triplets instead of single numbers.
```
int coeff = 2;
int index = 1;
int line = 3;
int column = 6;
int[][] m = new int[line][];
for (int i = 0; i < line; i++)
{
m[i] = new int[column];
for (int j = 0; j < column; j++)
{
m[i][j] = index;
index++;
Console.Write(m[i][j] + " ");
}
Console.WriteLine();
}
int[][] matrix = new int[line * coeff][];
for (int i = 0; i < line; i++)
{
for (int k = i * coeff; k < i * coeff + coeff; k++)
{
matrix[k] = new int[column * coeff];
}
for (int j = 0; j < column; j += 3)
{
for (int k = i * coeff; k < i * coeff + coeff; k++)
{
for (int l = j * coeff; l < j * coeff + coeff * 3; l += 3)
{
int[] matrixLine = matrix[k];
int[] mLine = m[i];
matrixLine[l + 0] = mLine[j + 0];
matrixLine[l + 1] = mLine[j + 1];
matrixLine[l + 2] = mLine[j + 2];
}
}
}
}
Console.WriteLine();
for (int i = 0; i < line * coeff; i++)
{
for (int j = 0; j < column * coeff; j++)
{
Console.Write(matrix[i][j] + " ");
}
Console.WriteLine();
}
``` |
What is a proper way to get the changed values from a table with hundreds of rows (To be sent as form to the backend)? |
This might be a alternative **https://github.com/yogeshlonkar/lua-import**
Disclaimer: I'm the author of this module |
it is generally a good practice to specify classes for sections in HTML. This can help maintain a cohesive design and make it easier to update the styling of multiple sections at once by modifying the CSS rules for that class. |
I'm trying to follow [Sebastian Lague's Fluid simulation](https://www.youtube.com/watch?v=rSKMYc1CQHE) video in c++ and OpenGL. I'm at the point where we calculate a `propertyGradient` value (timestamp is 14:15).
I'll try to provide all the code that is relevant further down below.
```
float CalculatePropertyGradient(Vector2 samplePoint, const std::vector<Vector2>& positions, const std::vector<float>& particleProperties, float smoothingRadius, float mass)
{
float propertyGradient = 0.0f;
DensityCalculator calculator(positions, smoothingRadius);
for (int i = 0; i < positions.size(); i++)
{
float dst = (positions[i] - samplePoint).magnitude();
Vector2 dir = (positions[i] - samplePoint) / dst;
float slope = SmoothingKernelDerivative(dst, smoothingRadius);
float density = calculator.CalculateDensity(positions[i]);
Vector2 scaledDir = dir * particleProperties[i];
propertyGradient += -(scaledDir) * slope * mass / density;
}
return propertyGradient;
}
```
But I'm getting a syntax error in the line:
`propertyGradient += -(scaledDir) * slope * mass / density;`
under += operator that my Vector2 class doesn't support this operation involving float and vector2
My vector2 class:
```
class Vector2 {
public:
float X;
float Y;
Vector2(float x, float y) : X(x), Y(y) {}
float magnitude() const {
return sqrt(X * X + Y * Y);
}
Vector2 operator-(const Vector2& other) const {
return Vector2(X - other.X, Y - other.Y);
}
Vector2 operator/(const float& scalar) const {
return Vector2(X / scalar, Y / scalar);
}
Vector2 operator*(const float& right) const {
return Vector2(X * right, Y * right);
}
Vector2 operator-(const float& scalar) const {
return Vector2(X - scalar, Y - scalar);
}
Vector2 operator*(const Vector2& other) const {
return Vector2(X * other.X, Y * other.Y);
}
Vector2 Zero() {
return Vector2(0.0f, 0.0f);
}
Vector2 operator-() const {
return Vector2(-X, -Y);
}
Vector2& operator+=(const float& scalar) {
X += scalar;
Y += scalar;
return *this;
}
};
```
My density class:
```
class DensityCalculator {
private:
std::vector<float> densities;
std::vector<Vector2> positions;
float smoothingRadius;
public:
DensityCalculator(const std::vector<Vector2>& positions, float smoothingRadius)
: positions(positions), smoothingRadius(smoothingRadius) {}
void PreCalculateDensities() {
densities.clear();
for (const auto& position : positions) {
densities.push_back(CalculateDensity(position));
}
}
float CalculateDensity(Vector2 position) const {
float density = 0;
const float mass = 1;
for (const auto& p : positions) {
float dst = (p - position).magnitude();
if (dst <= smoothingRadius) {
float influence = SmoothingKernel(smoothingRadius, dst);
density += mass * influence;
}
}
return density;
}
float GetDensity(int index) const {
return densities[index];
}
};
```
SmoothingKernel and SmoothingKernelDerivative functions:
```
float SmoothingKernel(float radius, float dst)
{
if (dst < radius)
{
float volume = M_PI * pow(radius, 8) / 4;
float v = std::max(radius * radius - dst * dst, 0.0f);
return ((v * v * v) / volume);
}
else
{
return 0;
}
}
static float SmoothingKernelDerivative(float dst, float radius)
{
if (dst >= radius)
return 0;
float f = radius * radius - dst * dst;
float scale = -24 / (M_PI * pow(radius, 8));
return scale * dst * f * f;
}
```
Here's the function call in my main function:
```
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j) {
float x = distX(mt);
float y = distY(mt);
balls.emplace_back(x, y, 0.0, 0.0, radius);
// Calculate the value of ExampleFunction at the particle's location and store it in particleProperties
float propertyValue = ExampleFunction(Vector2(x, y));
particleProperties.push_back(propertyValue);
}
}
```
Where ExampleFunction is just
```
static float ExampleFunction(Vector2(pos))
{
return cos(pos.Y - 3 + sin(pos.X));
}
```
I've tried **declaring the operator += of vector2 as acting on a const object** as suggested by another post but i get an error that X and Y must be a modifiable value. |
Error: No operator '+=' matches float and Vector2 in fluid simulation property gradient calculation |
|c++|opengl|vector|floating-point|operator-overloading| |
null |
`ActivityDesktopView` is a view entity and the dot notation `Activity.Documents` is trying to traverse an array. If you are using the `viewEntityColumn` sub-element then it does not allow traversing arrays and hence the error. This is mentioned in the [View Entities Documentation](https://docs.guidewire.com/cloud/bc/202310/config/config/topics/r_dz3181928.html) (Requires Login).
> The path attribute definition cannot traverse arrays.
>
> The path attribute is always relative to the primary entity on which
you base the view.
I figured that the `computedcolumn` sub-element doesn't allow traversing arrays either and the other way to deduce this would be using something like the below on the boolean cell of the list view or through an enhancement property like you mentioned.
`ActivityDesktopView.Activity.Documents.Count > 0` |
Pretty much what it says on the tin.
I have a JS script that isn't staying within the div element it is designated to on my page, it "sits" in the footer section instead.
[Page design with the JS script result "sitting" in the footer](https://i.stack.imgur.com/0Dpil.png)
```
<header>
<div>icon</div>
<div>header</div>
<div style="padding:5px;">
script is supposed to go here
<script src="JS/SpinningBaton.js"></script>
</div>
</header>
```
That's how I currently have the HTML block written in an attempt to resolve the issue. Unfortunately, nothing has changed. What am I doing to wrong?
For context, the div element is 165px in size while the JS script is 155px, so it should fit without overflow.
I have tried putting the script within different elements within the div and resizing the div element. But the script defiantly stays in the footer area regardless of what I have tried so far.
SpinningBaton code - I'd include the code that makes the script actually work, but it exceeds the limit:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
angleMode = "radians";
var angle = 0;
var aVelocity = 0;
var aAcceleration = 0.0001;
// var TargetSpeed = ((Math.random() * 2)-1)/2;
function RandNum(){
a = Math.floor(Math.random() * 256);
return a;
}
Num1 = RandNum();
Num2 = RandNum();
Num3 = RandNum();
Num4 = RandNum();
Num5 = RandNum();
Num6 = RandNum();
Num7 = RandNum();
Num8 = RandNum();
Num9 = RandNum();
Num10 = RandNum();
Num11 = RandNum();
Num12 = RandNum();
draw = function() {
createCanvas(155,155);
resetMatrix();
translate(width/2, height/2);
rotate(angle);
stroke(0, 0, 0,0);
fill(Num1, Num2, Num3);
ellipse(60, 0, 32, 32);
fill(Num4, Num5, Num6);
ellipse(-60, 0, 32, 32);
fill(Num7, Num8, Num9);
ellipse(0, 60, 32, 32);
fill(Num10, Num11, Num12);
ellipse(-0, -60, 32, 32);
if (aVelocity < TargetSpeed)
{
aVelocity += aAcceleration;
}
else
{
aVelocity -= aAcceleration;
}
angle += aVelocity;
};
<!-- end snippet -->
|
If, Anyone else is getting this issue in a React Naive app, It's Probably because of a package you're using. Search for that specific View Controller in XCode which will reveal your culprit. Try updating the package to latest version. |
Although @oguz-ismail's answer would work with the sample output provided, it seems that actual `equery` output is very strange when fed into a pipe.
This convoluted commandline seems to work around the problems:
```
script -B /dev/null -E never -f -q -c '
eix-installed -a | xargs equery depends
' |
tr -d '\r' |
grep -v '^---' |
awk '!/\n/' RS= ORS='\r\n'
```
* `script` makes `equery` believe it is talking to a terminal
* `tr` strips the carriage returns added by `script`
* `grep` filters some non-dependency info (per @konsolebox comment)
* `awk` splits on empty lines and filters out multi-line records
- setting `ORS` is only needed for terminal output
|
|javascript|jquery|backend| |
|machine-learning|pytorch|torchvision| |
```
expand-close-icon && expand-open-icon
``` |
I updated your `process_excel_file` function and it works:
```
def process_excel_file(excel_file, root_directory):
try:
wb = openpyxl.load_workbook(excel_file)
sheet = wb.active
data_rows = sheet.iter_rows(min_row=2, min_col=1, max_col=4, values_only=True)
processed_data = []
for row in data_rows:
directory_info = [str(cell).strip() if cell else "" for cell in row]
level = 0
target_code = directory_info[level]
directory = find_directory(root_directory, target_code)
if directory:
descriptions = [directory.name]
current_directory = directory
while level < len(directory_info) - 1:
level += 1
target_code += directory_info[level]
current_directory = find_directory(current_directory, target_code)
if not current_directory:
break
descriptions.append(current_directory.name)
processed_row = directory_info + descriptions
processed_data.append(processed_row)
else:
print(f"Directory {target_code} not found.")
return processed_data
except Exception as e:
print(f"Error occurred while processing Excel file: {e}")
return None
```
The main update is those lines:
[![while loop updates][1]][1]
[1]: https://i.stack.imgur.com/4RBPk.png |
null |
null |
null |
null |
I am running ActiveMQ Classic as a Docker container. It is running on port `61616`. I haven't changed any settings.
I have created this example queue in the webinterface:
[![enter image description here][1]][1]
Here is the queue definition:
```xml
<queues>
<queue name="ExampleQueue">
<stats size="0" consumerCount="0" enqueueCount="0" dequeueCount="0"/>
<feed>
<atom>queueBrowse/ExampleQueue?view=rss&feedType=atom_1.0</atom>
<rss>queueBrowse/ExampleQueue?view=rss&feedType=rss_2.0</rss>
</feed>
</queue>
</queues>
```
I am trying to access this queue in Java with the following code:
```java
package messageListener;
import javax.naming.*;
import java.util.Properties;
import javax.jms.*;
public class MessageListenerSender {
// Member-Variables
InitialContext initialContext;
ConnectionFactory connectionFactory;
Connection connection;
Session session;
Queue queue;
MessageProducer queueMessageProducer;
Topic topic;
MessageProducer topicMessageProducer;
// Connect to Message-Broker
public void connectToMessageBroker() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
properties.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");
initialContext = new InitialContext(properties);
connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
// Access Point-To-Point Queue
public void accessPointToPointQueue() throws Exception {
queue = (Queue) initialContext.lookup("/queue/ExampleQueue");
queueMessageProducer = session.createProducer(queue);
}
// Access Topic-Orientated Queue
public void accessTopicQueue() throws Exception {
topic = (Topic) initialContext.lookup("/topic/ExampleTopic");
topicMessageProducer = session.createProducer(topic);
}
// Send Messages
public void sendMessages() throws Exception {
Message message0 = session.createTextMessage("Hello World!");
queueMessageProducer.send(message0);
Message message1 = session.createTextMessage("Goodbye World!");
topicMessageProducer.send(message1);
}
// Close all Connections
public void closeConnections() throws Exception {
if (initialContext != null) {
initialContext.close();
}
if (connection != null) {
connection.close();
}
}
public static void main(String[] args) throws Exception {
MessageListenerSender messageListenerSender = new MessageListenerSender();
messageListenerSender.connectToMessageBroker();
messageListenerSender.accessPointToPointQueue();
messageListenerSender.accessTopicQueue();
messageListenerSender.sendMessages();
messageListenerSender.closeConnections();
}
}
```
This code produces this error:
```
Exception in thread "main" javax.naming.NameNotFoundException: queueBrowse/ExampleQueue?view=rss&feedType=atom_1.0
at org.apache.activemq.jndi.ReadOnlyContext.lookup(ReadOnlyContext.java:235)
at java.naming/javax.naming.InitialContext.lookup(InitialContext.java:409)
at messageListener.MessageListenerSender.accessPointToPointQueue(MessageListenerSender.java:40)
at messageListener.MessageListenerSender.main(MessageListenerSender.java:74)
```
Sadly i can't figure out what I need to change to resolve this issue. Do I use the wrong path or sth like that?
I want to set up a sender and a receiver that communicate via ActiveMQ.
[1]: https://i.stack.imgur.com/3wMR9.png |
|ios|uitableview|uikit|swiftui-tabview|uihostingcontroller| |
I tried to deploy Sveltekit project in firebase hosting am facing below error when I enables SSR for my sveltekit project
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'tailwindcss' imported from /workspace/entries/pages/_page.svelte.js
at packageResolve (node:internal/modules/esm/resolve:853:9)
at moduleResolve (node:internal/modules/esm/resolve:910:20)
at defaultResolve (node:internal/modules/esm/resolve:1130:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:396:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:365:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:240:38)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:85:39)
at link (node:internal/modules/esm/module_job:84:36) {
2024-03-10T09:19:41.621719Z ? ssrhomeappname: code: 'ERR_MODULE_NOT_FOUND'
2024-03-10T09:19:41.621725Z ? ssrhomeappname: }
Site is working properly when I disabled SSR and deploying in Firebase hosting.
export const ssr = false;
export const prerender = false;
It works well when I tested locally with production build. This issue occurs only when I Hosted in Firebase-Hosting it's not working
Here is my Firebase.json file:
{
"hosting": {
"site": "home-sitename",
"source": ".",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"frameworksBackend": {
"region": "us-central1",
"maxInstances": 2
}
}
}
Here is my tailwind.config.js file
/** @type {import('tailwindcss').Config} */
import { fontFamily as _fontFamily } from "tailwindcss/defaultTheme";
import scrollbarHide from 'tailwind-scrollbar-hide'
import colors from "tailwindcss/colors";
const plugin = require('tailwindcss/plugin')
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {
fontFamily: {
inter: ["Inter", ..._fontFamily.sans],
},
fontWeight:{
inherit: 'inherit'
},
fontSize: {
"xx+": ["0.600rem", "0.755rem"],
tiny: ["0.625rem", "0.8125rem"],
"tiny+": ["0.6875rem", "0.875rem"],
"xs+": ["0.8125rem", "1.125rem"],
"sm+": ["0.9375rem", "1.375rem"],
// '3xl' : ["2rem"],
// '2xl' : ["1.5rem"],
// 'xl' : ["1.17rem"],
// 'lg' : ["1rem"],
// 'base' : ["0.83em"],
'sm' : ["0.875rem", '1.5'],
},
colors:{
'primary-top': '#0b00db',
'primary': '#0b00db',
'primary-pressed': '#0859D0',
'primary-hover': '#148cfc',
'primary-focus': '#148cfc',
'primary-light' :'#637EFF',
'secondary' : '#9591F2',
'text-primary': '#273266',
'background' : '#f5f5f5',
'on-primary' : '#ffffff',
'scrollbar' : colors.slate[400],
'scrollbarHover' : colors.slate[500],
...colors
},
},
},
plugins: [scrollbarHide],
}
Here is my svelte config file:
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
},
preprocess: vitePreprocess()
};
export default config;
Tailwind and svelitekit versions:
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"tailwindcss": "^3.4.1",
"autoprefixer": "^10.4.17", |
Sveltekit & TailwindCSS - Getting ERR_MODULE_NOT_FOUND for TailwindCSS package for SSR in Firebase Hosting |
|tailwind-css|sveltekit|firebase-hosting| |
Please help me to resolve this issue.
snowflake.connector is unable to import after it is successfully installed in Azure Pipeline.
**Error::**
[Devops error](https://i.stack.imgur.com/9AZD7.png)
**Devops YAML Script::**
```
trigger:
branches:
include:
- snowpipe
variables:
vmImageName: 'windows-latest'
# Working Directory
workingDirectory: '$(System.DefaultWorkingDirectory)'
pool:
vmImage: $(vmImageName)
steps:
- task: UsePythonVersion@0
displayName: 'Define Python version'
inputs:
versionSpec: '3.8.x'
addToPath: true
- task: bash@3
inputs:
targetType: inline
workingDirectory: $(workingDirectory)
script: |
python -m venv worker_venv
source worker_venv/bin/activate
pip install --upgrade pip
pip install --target="./.python_packages/lib/site-packages" snowflake-connector-python
python --version
python snowflake.py
displayName: 'Install Snowflake Python Connector '
```
**I tried to execute Python inline code also. But no luck..**
```
- task: PythonScript@0
displayName: 'Run Python Script to Connect to Snowflake'
inputs:
scriptSource: 'inline'
workingDirectory: $(workingDirectory)
script: |
import snowflake.connector
print("done")
```
I tried to install the library through VS Code with Python Environment and then import the library snowflake.connector and that was successfully executed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.