instruction stringlengths 0 30k ⌀ |
|---|
I want to cry and cry, help friends, I believe in you
I want to cry and cry, help friends, I believe in you
I want to cry and cry, help friends, I believe in you
I want to cry and cry, help friends, I believe in you
import tensorflow as tf
from keras.preprocessing.sequence import Tokenizer
from keras.utils import pad_sequences
# Set parameters
vocab_size = 5000
embedding_dim = 64
max_length = 100
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"
training_size = len(processed_data)
# Create tokenizer
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_sequences(processed_data)
word_index = tokenizer.word_index
# Create sequences
sequences = tokenizer.texts_to_sequences(processed_data)
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
# Create training data
training_data = padded_sequences[:training_size]
training_labels = padded_sequences[:training_size]
# Build model
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Conv1D(64, 5, activation='relu'),
tf.keras.layers.MaxPooling1D(pool_size=4),
tf.keras.layers.LSTM(64),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(vocab_size, activation='softmax')
])
# Compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train model
num_epochs = 50
history = model.fit(training_data, training_labels, epochs=num_epochs, verbose=2)
def predict_answer(model, tokenizer, question):
# Preprocess question
question = preprocess(question)
# Convert question to sequence
sequence = tokenizer.texts_to_sequences([question])
# Pad sequence
padded_sequence = pad_sequences(sequence, maxlen=max_length, padding=padding_type, truncating=trunc_type)
# Predict answer
pred = model.predict(padded_sequence)[0]
# Get index of highest probability
idx = np.argmax(pred)
# Get answer
answer = tokenizer.index_word[idx]
return answer
# Start chatbot
while True:
question = input('You: ')
answer = predict_answer(model, tokenizer, question)
print('Chatbot:', answer)
There is an opportunity to write to the chat in the terminal. When I write my message, it gives an error: Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'model' is not defined
Oh, i am from Russia, sorry.
we still need to write something so that the post is not from the horror code |
How do I make sure that the labels of a echarts4r radar chart are completely visible on any screen? Works with bs4Dash::box but not with bslib::card |
The purpose of the code is to have a backup to the websocket in case of problems, so when it is NOT active I run a long time polling on http protocol until the websocket becomes active again
**This is the solution I found:**
properties:
```
pollingDone = signal(false)
private timerDone$ = new Subject<boolean>();
```
ws connection:
```
...
openObserver: {
next: (event) => {
this.pollingDone.set(true);
}
},
closeObserver: {
next: (event) => {
this.pollingDone.set(false);
}
}
...
```
constructor
```
effect( () => {
this.timerDone$.next(this.pollingDone())
if(this.pollingDone() === false) {
this.startPolling(5000).subscribe(val => this.store.dispatch(TablePageActions.load()))
}
})
```
methods
```
startPolling(interval: number = 5000): Observable<any> {
return timer(0, interval)
.pipe(
takeUntil(this.timerDone$)
)
}
```
Maybe it's not stylistic, I had difficulty defining an observable boolean accepted by the takeUntil, anyway it seems the goal was achieved. I tried to hook directly into the openObserver and closeObserver Events but failed. |
I'm trying to understand the behavior of Bash when it comes to reading heredocs, as I am trying to implement a minishell based on bash in C.
Specifically, I'm interested in knowing the circumstances under which Bash reads the content of a here document (<<). I've encountered some scenarios where it seems Bash behaves unexpectedly, and I'd like to clarify these points.
When piping commands together and using a heredoc, how does Bash determine when to read the heredoc? For example:
`ls |& cat <<END`
In this case, Bash reports a syntax error and doesn't read the heredoc. Why does this happen?
Conversely, when a heredoc precedes a pipe (|) followed by another command, how does Bash handle it? For instance:
`cat <<END |& ls`
Here, Bash reports a syntax error but still reads the heredoc from stdin. Why does this behavior differ from the previous example?
I'm seeking clarification on these behaviors to better understand how Bash processes heredocs in different contexts. |
When does Bash read heredocs? |
|c|bash|shell|heredoc| |
I had been working on a WPF project for several weeks, using VS 2022 17.9.2, targeting .Net 6.0, with no problems. Out of nowhere today, upon opening, I received a slate of errors relating to `Could not find InitializeComponent() ...` for a couple custom WPF controls. Ran through namespace checks, etc., searched the error, and couldn't resolve. Nothing had changed so I wasn't sure what else to check (no updates, etc.).
Decided to try updating VS after finding a couple old threads with similar unresolved problems. Updated to VS 2022 17.9.5. Now I receive the following error:
`The current .NET SDK does not support targeting .NET Core 6.0. Either target .NET Core 5.0 or lower, or use a version of the .NET SDK that supports .NET Core 6.0.`
[](https://i.stack.imgur.com/y2XIu.png)
Tried opening a brand-new WPF project and I get the same error right off the bat. Used the `Repair` option in VS installer, no changes.
Tried changing the target framework in Properties and these are the only options available now:
[](https://i.stack.imgur.com/mAb4L.png)
If I try to select any of them, it returns to a blank selection.
I get the same error if I create a new WinUI3 project.
Really not sure where to even begin. The errors came out of nowhere as far as I can tell - I was working this morning without issue, didn't even restart my system (much less update anything, etc.), and upon opening the project in the afternoon, started receiving the initial errors. Seems to have happened between closing VS in the morning and opening it in the afternoon.
I had found a couple old threads with similar errors but they all seem to relate to VS 2019 not supporting .Net 6 and I am absolutely working in VS 2022.
Thank you for any input... I'm not an expert so if there's anything required to diagnose this problem I would be happy to provide it if asked.
Tried loading existing and creating new WPF and/or WinUI3 projects. Received error upon creation, without modification. |
When logging in i create a token for the user and then put it in a cookie. I return that cookie to my front-end and then i use that cookie for every other request to my api. The cookie is in the request header when making requests but it stil doesn't work. I still get 401 errors.
Here is my login function:
```
class LoginController extends Controller
{
public function handleLogin(Request $request)
{
// Get the access token from the request's bearer token
$accessToken = $request->bearerToken();
// Call Microsoft Graph API to retrieve user information
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
])->get('https://graph.microsoft.com/v1.0/me');
// return response()->json($response->json());
// exit;
// Check if the request was successful
if ($response->successful()) {
$userData = $response->json();
// Check if the user exists in your database
$user = User::where('email', $userData['mail'])->first();
// If the user doesn't exist, create a new user
if (!$user) {
$user = new User();
$user->username = $userData['displayName'];
$user->email = $userData['mail'];
$user->credits = 0;
// Set the user's role based on their email domain
if (strpos($userData['mail'], '@landstede.nl') !== false) {
$user->role = 'admin';
} else {
$user->role = 'user';
}
$user->save();
}
// Authenticate the user with Sanctum
$token = $user->createToken('token')->plainTextToken;
$cookie = cookie('auth-token', $token, 60 * 24, '/', null, true, true, false, 'None');
// Return cookie with the token
return response()->json(['message' => 'User authenticated', 'user' => $user], 200)->withCookie($cookie);
} else {
// If the request to Microsoft Graph API fails, return an error response
return response()->json(['error' => 'Failed to retrieve user information from Microsoft Graph API'], $response->status());
}
}
}
```
These are my routes:
```
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->group(function () {
Route::get('/waitlist', [WaitlistController::class, 'getItems']);
Route::post('/waitlist/delete/{id}', [WaitlistController::class, 'deleteItem']);
Route::post('/waitlist/download', [WaitlistController::class, 'download']);
Route::get('/users', [UserController::class, 'getUsers']);
})->middleware('web');
Route::get('/login', [LoginController::class, 'handleLogin']);
```
This is my auth cookie:
[](https://i.stack.imgur.com/Orhfa.png)
Here is the request:
[](https://i.stack.imgur.com/vmouN.png) |
Why is sanctum not authenticating me with my cookie? |
|laravel|laravel-sanctum| |
null |
Good morning,
I needed your precious help, as it's been a few days of trying and I'm not able to reach the desired conclusion
Now, basically we have an online store and I would like to modify the label below the shipping method (hook: woocommerce_cart_shipping_method_full_label) based on the stock status of the products in the cart.
Basically, if there is 1 product whose stock status is "to order", then the label for shipping method 1 = "48/72h" and the label for shipping method 2 = "48/72h".
If there is 1 product that is "limited stock", then shipping method label 1 = "24/48h" and shipping method label 2 = "48/72h".
Otherwise (that is, all products are "in stock") the label = ""Shipping by 4pm".
My closest attempt was like this: (but it checks for each product, that is, it adds a label as many times as the number of products in the cart - which is wrong)
add_filter( 'woocommerce_cart_item_name', 'custom_text_based_status_name', 10, 3 );
function custom_text_based_status_name( $item_name, $cart_item, $cart_item_key ) {
if( ! ( is_checkout() ) )
return $item_name;
$shipping_class_1 = 'onbackorder';
$shipping_class = $cart_item['data']->get_stock_status();
if( $shipping_class === $shipping_class_1 ) {
add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_shipping_methods_label', 10, 2 );
function custom_shipping_methods_label( $label, $method ) {
switch ( $method->id ) {
case 'fish_n_ships:62': //Portugal Continental - Transportadora
$txt = __('Expedição estimada: 24 a 48h úteis''); // <= Additional text
break;
case 'fish_n_ships:63': //Portugal Continental - Gratuito
$txt = __('Expedição estimada: 72 a 96h úteis'); // <= Additional text
break;
default: //nos restantes casos
$txt = __('Confirmaremos assim que possível'); // <= Additional text
}
return $label . '<br /><small style="color:#777777">' . $txt . '</small>';
}
}
return $item_name;
}`
I also tried but show critical error:
add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_shipping_method_label', 10, 3 );
function custom_shipping_method_label( $label, $method, $cart_item ) {
switch ([$method->id, $cart_item['data']->get_stock_status]) {
case ['fish_n_ships:62', 'instock']: //Portugal Continental - Transportadora
$txt = __('Expedição estimada: 24 a 48h úteis'); // <= Additional text
break;
case ['fish_n_ships:62', 'stock_limitado']: //Portugal Continental - Transportadora
$txt = __('Expedição estimada: 24 a 48h úteis'); // <= Additional text
break;
default: //nos restantes casos
$txt = __('Confirmaremos assim que possível'); // <= Additional text
}
return $label . '<br /><small style="color:#777777">' . $txt . '</small>';
} |
Why is this code not working? I've tried everything and everything seems to be fine, but no |
|python|xcode|tensorflow| |
null |
Is it possible to combine two plots and make it one plot?
These are the plots I am trying to combine.
I have tried the "combined_plot" command, but I get the same result - two separate plots.
[enter image description here](https://i.stack.imgur.com/rNHuA.png)
Here are my codes:
Plot 1:
plot1 <- ggplot() +
geom_bar(data = complete_august_data, aes(x = DATE, y = Count, fill = MANUAL.ID.),
stat = "identity", width = 0.7, position = "dodge") +
geom_bar(data = complete_july_data, aes(x = DATE, y = Count, fill = MANUAL.ID.),
stat = "identity", width = 0.7, position = "dodge") +
labs(title = "Kumulative kurver for juli og august ved Borupgård 2018",
x = "Dato",
y = "Kumulative observationer",
fill = "Art") +
scale_x_date(date_labels = "%Y-%m-%d") +
theme_minimal()
Plot 2:
plot2 <- ggplot(result_df, aes(x = Dato, y = Belysning)) +
geom_line(color = "gold2") + # Tilføj en linje
geom_point(color = "goldenrod", size = 2) + # Tilføj punkter
labs(x = "Dato", y = "Belysning", title = "Graf over belysning 25 juli - 29 august 2018") +
scale_x_date(limits = as.Date(c("2018-07-26", "2018-08-29")),
date_breaks = "5 day",
date_labels = "%Y-%m-%d")+
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
theme_bw() |
How to combine two plots |
|rstudio| |
null |
You need to add `.Name` at the end beacause `FindFirstChild()` checks for strings
function click(player)
local y = workspace:FindFirstChild(player.Name).HumanoidRootPart.CFrame
local location = script.Parent.Location.Position
y = CFrame.new(location)
print("Teleported")
end
script.Parent.ClickDetector.MouseClick:connect(click) |
I'm working on a tool for animating 3D objects, and I've run into an issue that I'm not sure how to solve:
There is a rotation gizmo implemented, which works fine.
However since it's an animation tool, I need to end up with euler angles after a rotation is performed.
And the issue is, since I'm converting to quaternion to perform the rotation along an axis, and then back to euler. At certain angles I end up with flipped signs. (goes up to 180 degrees, and then switches to -180 degrees, and vice versa)
While the rotation looks fine when rendered, the sign flipping causes issues when trying to do the animation interpolation, the object will spin in the opposite direction etc.
The code looks something like this:
```
local rotation = object:GetQuaternionRotation();
rotation:RotateAroundAxis(direction, mouseDiff);
local newRotation = rotation:ToEuler();
```
- the direction is a direction vector (x,y,z), when rotating in world space Z direction would be (0, 0, 1) and when rotating in local space the vector is whatever the object's up vector is at that moment in time.
- the mouseDiff is just +- increment based on how much the mouse moved
- and finally RotateAroundAxis looks like this:
```
function Quaternion:RotateAroundAxis(axis, angle)
-- Calculate half angle
local halfAngle = angle * 0.5
-- Calculate sine and cosine of half angle
local sinHalfAngle = math.sin(halfAngle)
local cosHalfAngle = math.cos(halfAngle)
-- Normalize the axis
axis:Normalize()
local rotationQuat = Quaternion:New(
axis.x * sinHalfAngle,
axis.y * sinHalfAngle,
axis.z * sinHalfAngle,
cosHalfAngle
)
self:Multiply(rotationQuat)
end
```
A preview of what's going on
[enter image description here](https://i.stack.imgur.com/5gKCE.gif)
I tried just adding the euler values, but that obviously won't work when the direction vector is not axis aligned. |
{"Voters":[{"Id":1136211,"DisplayName":"Clemens"},{"Id":529282,"DisplayName":"Martheen"},{"Id":10024425,"DisplayName":"user246821"}]} |
The following simplified and revised code version, will also handle variable products (based on the variation max price), adding a product tag based on the product price by ranges:
- with a price up to $200, the product will be tagged with `789` term ID,
- with a price between $100 and $200, the product will be tagged with `456` term ID,
- with a price lower than $100, the product will be tagged with `123` term ID.
Try this replacement code:
```php
add_action( 'woocommerce_new_product', 'auto_add_product_tag_based_on_price', 10, 2 );
add_action( 'woocommerce_update_product', 'auto_add_product_tag_based_on_price', 10, 2 );
function auto_add_product_tag_based_on_price( $product_id, $product ) {
// Handle all product types price
$price = $product->is_type('variable') ? $product->get_variation_price('max') : $product->get_price();
if ( $price >= 200 ) {
$term_id = 789;
} elseif ( $price >= 100 ) {
$term_id = 456;
} else {
$term_id = 123;
}
if ( ! has_term($term_id, 'product_tag', $product_id) ) {
wp_set_post_terms($product_id, [$term_id], 'product_tag');
}
}
```
Code goes in functions.php file of your child theme (or in a plugin). Tested and works. |
I am trying to load my app for packaging but the native electron reload function used in the Menu "Window" - "Reload" is loading the file: "file:///"
electron: Failed to load URL: file:/// with error: ERR_FILE_NOT_FOUND
(Use `Electron --trace-warnings ...` to show where the warning was created)
I am loading the files using electron-vite but in production or in preview I use the file directly. How can i reload the same file i used with electron main.js
```
const appPath = app.getAppPath();
let mainWindow: BrowserWindow | null = null;
function createWindow() {
mainWindow = new BrowserWindow({
icon:
process.platform === "darwin"
? path.join(process.env.VITE_PUBLIC || "", "app-logo.icns")
: path.join(process.env.VITE_PUBLIC || "", "app-logo.ico"),
minWidth: 1200,
minHeight: 800,
width: 1920,
height: 1080,
webPreferences: {
preload: path.join(appPath, "out/preload/preload.js"),
webSecurity: false, // TODO: Review this
},
});
// Routers
VendorRouter();
SettingsRouter();
tsvRouter();
DatabaseRouter();
loggerRouter();
const productionPath = path.join(appPath, "out/renderer/index.html");
console.log("\nproductionPath", productionPath, "\n");
// Load the index.html of the app
if (app.isPackaged) mainWindow.loadFile(productionPath);
// Vite dev server URL
else mainWindow.loadURL("http://localhost:5173");
mainWindow.on("closed", () => (mainWindow = null));
}
```
I am expecting to see the same page (single page website - React) on reload.
Edit: I forgot to add that the index.html is loaded correctly when the app starts, but reloading using the window.reload() method reloads that empty file. Missing the file name or path. I saw some solutions saying to add a base tag to the index.html file to it can search the page but it didn’t work.
<base href="./"/> |
Update Sidebar Height to Cover the Document Height (with React Pro Sidebar) |
The current .NET SDK does not support targeting .NET Core 6.0. Brand new WPF Project VS Community 2022 17.9.5 |
|.net|visual-studio| |
null |
I am making an app, where i want to use mongodb. I have never used mongo before, so i watched a tutorial on youtube. I registered on mongodb and got the connection string from there using their free plan.
This is the code I'm using:
```
string connectionString = "CONNECTIONSTRING";
string dbn = "DBNAME";
string cn = "COLLECTIONNAME";
var client = new MongoClient(connectionString);
var db = client.GetDatabase(dbn);
var collection = db.GetCollection<FilmModel>(cn);
var results = await collection.FindAsync(_ => true);
foreach (var result in results.ToList())
{
Console.WriteLine($"{result.Id}: {result.Cim}");
}
```
For the first time, it worked, and I didn't modified anything and restarted the app and nothing happens, for 30s. then, it throws this error:
```
System.TimeoutException: 'A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [], DnsMonitorException : "DnsClient.DnsResponseParseException: Response parser error, 244 bytes available, tried to read 1 bytes at index 244.
```
But the thing is, somethimes it works, sometimes it doesn't. And I don't modify anything.
**What am I doing wrong?** |
MongoDb not connecting C# |
|c#|.net|mongodb|connection|timeout| |
I am learning sveltekit and I would like to use svelte-canvas in my project. I have a component called Globe.svelte
```
<script>
import { onMount } from "svelte";
import { Canvas, Layer } from "svelte-canvas";
import { feature } from "topojson-client";
import { geoOrthographic, geoPath, geoGraticule10 } from "d3-geo";
let map, width;
const projection = geoOrthographic(),
path = geoPath(projection);
onMount(() =>
fetch("https://cdn.jsdelivr.net/npm/world-atlas@2/land-110m.json")
.then((data) => data.json())
.then((data) => (map = feature(data, "land"))),
);
$: graticule = ({ context, width, time }) => {
projection
.fitSize([width, width], { type: "Sphere" })
.rotate([time / 50, -10]);
context.strokeStyle = "#ccc";
context.beginPath(), path(geoGraticule10()), context.stroke();
};
$: globe = ({ context }) => {
context.fillStyle = "green";
context.beginPath(), path(map), context.fill();
};
</script>
<Canvas autoplay>
<Layer setup={({ context }) => path.context(context)} render={graticule} />
<Layer render={globe} />
</Canvas>
```
in my +page.svelte I import the component as follow:
```
<script>
import Globe from "../../components/Globe.svelte";
</script>
<Globe />
```
I was expecting to see the Globe spinning as in [here](https://svelte.dev/repl/b0c3901c51cd49f1a2f337f731942269?version=4.2.12) but nothing. I am not sure if this is the correct way to use svelte-canvas. Any help? |
Changed woocommerce_cart_shipping_method_full_label based products in cart stock status |
|php|woocommerce|hook-woocommerce|orders|stock| |
null |
you should reshape your training data as below:
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
by doing this you just add a dimension to the inputs. Then your input shape will be like (None, X_train.shape[1], 1). |
I'm developing a web API and I hosted it on Azure, I have a call that takes about 2.5 seconds in my local machine but takes a lot longer when the app is hosted in Azure as you can see in this figure:
![][1]
It's taking 12.8 seconds which is not expected, why is this happening, and what is the part highlighted in red? Why does it take about 10 seconds to start with the first operation in the code? I have "AlwaysOn " on ON so this is not my API going to sleep, also, sometimes the call takes less time (4-6 seconds) which an inconsistency, please enlighten me.
[1]: https://i.stack.imgur.com/BskET.png |
Web API calls are slow in Azure |
|c#|azure|azure-application-insights|webapi| |
if you are talking about dotnet core then you can run the services of .Net 6.0 with .Net 8.0 you just have to install the .Net 8.0 necessary [SDK][1] and after that follow these steps:
1. find bin and obj folder in the project directory.
2. delete the both folder bin and obj.
3. run the command **dotnet clean** and **dotnet build** in your **VScode** if your using another IDE then clean and build your project accordingly.
4. run the project by **dotnet run** command if any issue persist then run the code in debug mode and resolve it accordingly.
[1]: https://dotnet.microsoft.com/en-us/download/dotnet/8.0 |
$this->eventDispatcher->dispatch(new OrderSentEvent($order, $context), 'name.goes.here');
…did the trick. No event subscriber could be found, because if you don't provide a name as 2nd argument, the full class name will be used, but the Flow Builder apparently uses the custom one. |
You only get the benefit of the cache when a request comes in to a specific container that already has that data cached. Any time you deploy, your cache gets completely wiped out. Any time the ECS service scales up to add another container, the new container will not have any data cached until some requests come in and it starts caching that data. |
null |
I want to learn WordPress but setting up a hosting domain and all the initial process is frustrating for me and I don’t want to get into this.
Is there anything which can help me to create a quick WordPress site without purchasing a domain or hosting so that I can start learning and start creating websites with WordPress, when I will learn everything I will be in a position to purchase hosting/domain.
Anyone know of any of these kinds of services?
I am trying to find a solution or any tool for my problem. |
Issues with a rotation gizmo and sign flips when converting back to euler angles |
|math|3d|rotation|quaternions|3d-engine| |
null |
Below is the error i got from my code editor[enter image description here](https://i.stack.imgur.com/bB6BP.png)[enter image description here](https://i.stack.imgur.com/gEOo2.png)
and this is the error i get on the browser:
[enter image description here](https://i.stack.imgur.com/ub9Li.png)
i don't know what is wrong but when i remove the syntaxlexx/chatmessenger the project works well |
how to fix issue; if i install chatmessenger to my laravel SaaS project: "Call to undefined function getAdminPanelUrlPrefix()" |
|laravel|laravel-10|php-8| |
null |
1) Make your url names unique.
2) Make url parameters as below.
```python
path("products/",product_list_view,name="product_list"),
path("product/<int:pid>/",product_detail_view,name="product_detail"),
path("product/<slug:slug>/",get_product,name="get_product")
```
[ref][1]
[1]: https://docs.djangoproject.com/en/5.0/topics/http/urls/#example
3)
Make an error page template and show this page on exception
```
def get_product(request, slug):
try:
product = Product.objects.get(slug=slug)
if request.GET.get('size'):
size = request.GET.get('size')
print(size)
return render(request, "core/product_detail.html")
except Exception as e:
print(e)
return render(request, "core/error_page.html")
```
4) Obviously, you model have no field called slug. So below code wouldn't work.
```python
product = Product.objects.get(slug=slug)
```
You can only get objects using fields values in the model.
Like below.
```python
product = Product.objects.get(title="product_title")
#or
product = Product.objects.get(id=4)
``` |
I have a web app deployed on Azure. During testing, I found one of my endpoints is not working... sometimes. More specifically, this `POST` endpoint always works in my dev environment, and it randomly works in Prod.
When it fails, my controller endpoint is not hit (discovered by adding logs), and a "successful" 200 is returned but no response content is sent down. My `POST` body is tiny, only 50 or so bytes.
I'm not sure if its a clue or not, but it does seem to work immediately after a browser refresh, then when my auth token is refreshed it fails much more. This is fairly anecdotal though.
From googling, I found this helps some people:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.MinRequestBodyDataRate = null;
options.Limits.MinResponseDataRate = null;
});
No such luck here though. Any ideas what else might caused this? OR, any idea how how I can have .NET better tell me what's failing? I have nothing in my logs or anything.
Thanks!
EDIT:
I have two middlewares:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly JsonSerializerOptions jsonPolicy = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
var response = context.Response;
string msg;
switch (exception)
{
case ApplicationException ex:
if (ex.Message.Contains("Invalid Token"))
{
response.StatusCode = (int)HttpStatusCode.Forbidden;
msg = ex.Message;
break;
}
response.StatusCode = (int)HttpStatusCode.BadRequest;
msg = ex.Message;
break;
default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
msg = exception.Message;
break;
}
var errorResponse = new
{
Failed = true,
ErrorMessage = msg
};
_logger.LogError(exception, exception.Message);
var result = JsonSerializer.Serialize(errorResponse, jsonPolicy);
await context.Response.WriteAsync(result);
}
}
and:
public class UserStatusMiddleware
{
private readonly RequestDelegate _next;
private readonly DbContextFactory DbContextFactory;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly JsonSerializerOptions jsonPolicy = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
public UserStatusMiddleware(RequestDelegate next, DbContextFactory dbrderMonkeyContextFactory, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
DbContextFactory = dbContextFactory;
}
public async Task InvokeAsync(HttpContext httpContext)
{
using (DBContext dbContext = DbContextFactory.CreateDbContext())
{
var user = httpContext.User.FindFirst(ClaimTypes.NameIdentifier);
if (user == null)
{
throw new ArgumentException();
}
AspNetUser dbUser = dbContext.AspNetUsers.FirstOrDefault(x => x.Id == user.Value);
if (dbUser.IsDisabled || !dbUser.IsApproved)
{
httpContext.Response.ContentType = "application/json";
var response = httpContext.Response;
string msg;
var errorResponse = new
{
Failed = true,
IsDisabled = dbUser.IsDisabled,
IsApproved = dbUser.IsApproved,
ErrorMessage = "User is either disabled or not approved"
};
response.StatusCode = (int)HttpStatusCode.Unauthorized;
var result = JsonSerializer.Serialize(errorResponse, jsonPolicy);
await httpContext.Response.WriteAsync(result);
}
else
{
_next(httpContext);
}
}
}
}
public static class UserStatusMiddlewareExtensions
{
public static IApplicationBuilder UseUserStatusCheck(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<UserStatusMiddleware>();
}
}
EDIT #2: So it looks like if I take out the second middleware, the problem goes away. But why? Is there some time limit for middleware? |
So it turns out there was a tiny simple mistake in the model file. For those of you who encounter a similar error make DOUBLY SURE that when you define your item texture you put this:
{
"parent" : "item/generated",
"**textures**" : {
"layer0" : "starforgery:item/pure_emerald"
}
}
And not this:
{
"parent" : "item/generated",
"**texture**" : {
"layer0" : "starforgery:item/pure_emerald"
}
}
I've bolded the error, check your typos people! Happy coding! |
To start with, that is not SAS syntax. With out seeing the data set you might want
```
data want (label='Sum of X1-X<N> in 100th row');
set have ;
if _n_ = 100 then Q1A = sum(of x:) ;
run ;
```
or
```
data want (keep=Q1A label='Sum of X from 1st 100 rows') ;
set have (obs=100) end=end ;
Q1A + X ;
if end ;
run ;
``` |
When I try to commit in VS Code it fails after a bit saying "Commit failed: no commit message was given" (or something like that).
In VS Code, I can't type anything in the box. The cursor goes up there, but does not allow me to type. Any ideas?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/G9Y14.png |
I would like to implement a pull-based subscription model in my P2P protocol. Instead of peers themselves sending the events they have produced to all other nodes, they ask (pull request) other nodes which events interest them. The problem is that this process involves a significant waste of bandwidth since each node will ask all the others for the same events and therefore will receive duplicates. |
How to avoid duplicates with the pull-based subscribe model? |
|networking|publish-subscribe|p2p|distributed-system| |
I'm building a virtual drive Windows desktop app using IT Hit User File System library. Sometimes I get an IOException with message: 'The cloud file provider is not running.', when I'm trying to remove one of the folders that are marked as 'cloud' (synchronized with cloud) from local file system.
Before removing it I check if it exists in the file system, so there is no way I'm trying to remove folder that doesn't exist.
All the googled references to 'The cloud file provider is not running.' error are related to OneDrive, I couldn't find anything on this issue from development perspective.
Can this exception not be related to OneDrive and be caused by any other reason?
What are possible reasons I get this exception?
I can't wrap my head around it. I'm struggling to grasp possible reasons for several days.
Any help is very much appreciated.
Thanks in advance. |
'IOException: The cloud file provider is not running', when trying to delete 'cloud' folder |
|.net|windows|virtual-drive| |
null |
Input an output of signed single-digit decimal numbers |
I have been struggling with this issue as well when trying to set up a VSCode remote development container (docker compose build but should not make a big difference) with x11 support.
My requirements were as follows, since I intended not to expose my development machine too much to the open internet:
- No `network_mode: host` or `--net=host` respectively
- No `X11UseLocalhost no`
- No `xhost`
I ended up spinning up a daemonized `socat` process on the remote host at devcontainer initialization, tunneling the TCP x11 traffic from port 6XXX used for x11 with SSH to an x11 UNIX socket that I share with my container.
Solution is best described in a commit: https://github.com/flxtrtwn/devious/pull/16/commits/c6a233eb7312ca606f9d53a102bea8c1f8282578 |
The messed-up output is mainly due to not specifying the required function number AH=09h before invoking DOS to print a message, and to using DH for holding the second number while at the same time you use DX for another purpose. Remember that the 16-bit DX is composed of the two 8-bit parts DH and DL.
Input of a signed single-digit decimal number
-
The DOS.GetCharacter function 01h first waits for the user to press a keyboard key, then it writes the corresponding character on the screen, and finally it returns to your program with the key's ASCII code in the AL register. For some special keys the function will return AL=0, that way
signaling that your program should invoke the function again so as to obtain the key's scancode.
If you want the user to be able to input a signed single-digit decimal number, so in the range [-9,9], you will have to take a two-step approach. If the first time that you use the function you already receive a digit [0,9] then you can just bypass the second step. If on the other hand the first character that you received happened to be a minus character then you must invoke the function a second time expecting a digit [0,9], and this time you must also negate the number.
Next simplified example validates the user input:
ReDo1:
mov ah, 01h ; DOS.GetCharacter
int 21h ; -> AL
sub al, '0'
cmp al, 10
jb GotIt ; Is positive [0,9]
cmp al, '-' - '0'
jne ReDo1 ; An invalid character detected
ReDo2:
mov ah, 01h ; DOS.GetCharacter
int 21h ; -> AL
sub al, '0'
cmp al, 10
jae ReDo2 ; Not a decimal digit
neg al
GotIt:
You don't want to repeat yourself too much, so you should put the above in a subroutine.
mov dx, OFFSET Msg1 ; Read the first number from the user
call Input ; -> AL
mov bl, al
mov dx, OFFSET Msg2 ; Read the second number from the user
call Input ; -> AL
mov bh, al
...
; IN (dx) OUT (al) MOD (ah)
Input:
mov ah, 09h ; DOS.PrintString
int 21h
ReDo1:
mov ah, 01h ; DOS.GetCharacter
int 21h ; -> AL
sub al, '0'
cmp al, 10
jb GotIt ; Is positive [0,9]
cmp al, '-' - '0'
jne ReDo1 ; An invalid character detected
ReDo2:
mov ah, 01h ; DOS.GetCharacter
int 21h ; -> AL
sub al, '0'
cmp al, 10
jae ReDo2 ; Not a decimal digit
neg al
GotIt:
ret
Output of a signed single-digit decimal number
-
It is not sufficient to just add '0' and have DOS display the one character. A test for negative is in order and if required the output of a minus character:
test bl, bl
jns IsPositive
mov dl, '-'
mov ah, 02h ; DOS.PrintChar
int 21h
IsPositive:
lea dx, [bx - '0'] ; BH and DH are un-important here
mov ah, 02h ; DOS.PrintChar
int 21h
Displaying the final summarizing message can benefit from using a subroutine too. I did include the necessary logic to differentiate between your *PositiveMsg* and *NegativeMsg* messages, something that you forgot to do:
mov dx, OFFSET Msg3 ; BL contains first number
call Output
mov bl, bh ; Load second number in BL
mov dx, OFFSET Msg4 ; Make this a ', $'
call Output
...
; IN (bl,dx) OUT () MOD (ax,dx)
Output:
mov ah, 09h ; DOS.PrintString
int 21h
test bl, bl
jns IsPositive1
mov dl, '-'
mov ah, 02h ; DOS.PrintChar
int 21h
IsPositive1:
lea dx, [bx - '0'] ; BH and DH are not important here
mov ah, 02h ; DOS.PrintChar
int 21h
mov dx, OFFSET PositiveMsg
test bl, bl
jns IsPositive2
mov dx, OFFSET NegativeMsg
IsPositive2:
mov ah, 09h
int 21h
ret
|
I'm like a 100% sure that this is a basic thing, and therefore I'm sorry if it has been answered.
I've seen many code samples and code bases where people include header files like this:
```cpp
#include "util.h"
int main(void){
int result = function1(); // something that was defined in util.h but implemented elsewhere
return 0;
}
```
...while the content of the given header file is just:
```cpp
#pragma once
int function1();
int function2();
float function3();
```
And probably there is a util.c somewhere that has:
```cpp
#include "util.h"
int function1(){
...
}
int function2(){
...
}
float function3(){
...
}
```
I have experience with the language. \
I've used it in 1-2 larger projects (irc client). \
I've used make files too, even though they were more like "script files". \
But this header file thing... Can someone explain me this? |
How can I use svelte-canvas in sveltekit? |
|svelte|sveltekit| |
As the detailed analysis of the issues with your code is given in the answer by *trincot*, this supplementary response tries to simplify the explanation and provides along with an example of binary tree to traverse also more details about the approach using the logical operators `and` and `or` which in Python don't return True/False as value but a value of one of the components of the expression.
**The actual root of the issue you describe is to expect that the initial call of the traverse function will return you the found node** except the case of the root node where there is no recursion. **This is because the values returned by the deeper level recursion function calls simply go nowhere** and don't propagate upwards to the calling function.
The code you are using traverses *always* the entire tree, so I have adjusted it a bit to stop further search at the found node and solved also the issue of not being able to get the found value up the recursion calls using a global variable, which is in my eyes a simpler to understand approach than smart usage of the return values as suggested by *trincot*. Further explanations are provided as comments in the code below:
```
import collections
foundNode=None
def inorderTraversal1(node, tval):
global foundNode
if node is not None and foundNode is None:
print( node.val )
if(node.val==tval):
print("nodeValue = ", node.val)
print("nodeType", type(node))
foundNode=node
else: # the node has other node.val as tval, so check its sub-nodes:
inorderTraversal1(node.left,tval)
if foundNode is None:
inorderTraversal1(node.right,tval)
def inorderTraversal2( root, tval ):
return root and (
# NOTICE that logical and does not return True/False but the first component
# which evaluates to False, or the last component if all evaluate to True
root if root.val == tval else (
inorderTraversal2(root.left, tval)
or
inorderTraversal2(root.right,tval)
# NOTICE that logical or does not return True/False but the first item
# which evaluates to True, or the last item if all evaluate to False
)
)
BTnode = collections.namedtuple('BTnode', ['left', 'right', 'val'])
root=BTnode( val='0',
left=BTnode( val='01',
left=BTnode( val='011',
left=BTnode( val='0111', left=None, right=None ),
right=BTnode( val='0112',
left=BTnode(val='01121', left=None, right=None ),
right=BTnode( val='01122', left=None, right=None )
)
),
right=BTnode( val='012', left=None, right=None )
),
right=BTnode( val='02',
left=BTnode( val='021', left=None, right=None ),
right=BTnode( val='022', left=None, right=None )
)
)
foundNode=None; inorderTraversal1(root, '022') # !!! WATCH OUT !!!
# ^-- initialize `foundNode=None` in front of every call
# of `inorderTraversal1()`
print(foundNode)
print( " ----- " )
print( inorderTraversal2(root, '022') )
print("===============")
foundNode=None; inorderTraversal1(root, '01122')
print(foundNode)
print( " ----- " )
print( inorderTraversal2(root, '01122') )
```
which outputs:
```
> cd /home/o/oOo/O@@/stackoverflow
> python3 -u "BTree.py"
0
01
011
0111
0112
01121
01122
012
02
021
022
nodeValue = 022
nodeType <class '__main__.BTnode'>
BTnode(left=None, right=None, val='022')
-----
BTnode(left=None, right=None, val='022')
===============
0
01
011
0111
0112
01121
01122
nodeValue = 01122
nodeType <class '__main__.BTnode'>
BTnode(left=None, right=None, val='01122')
-----
BTnode(left=None, right=None, val='01122')
> exit status: 0
``` |
I want to learn WordPress without purchasing domain and hosting |
|wordpress|web| |
null |
I did not realise that the full text index was actually still populating so it was returning what was populated so far. |
To achieve what you are after you need the following:
On your component, a function to get the file from the form:
onFileSelected(event: any) {
const file: File = event.target.files[0];
if (file) {
this.http.put(url, file, {
headers: {
'Content-Type': file.type
},
reportProgress: true,
observe: 'events'
}).subscribe({
next: (event) => {
console.log(event); // Handle the upload progress
},
error: (error) => {
console.error('Upload failed:', error);
},
complete: () => {
console.log('Upload complete');
}
});
}
Now on your template, something like this:
<input type="file" (change)="onFileSelected($event)">
**Some important notes:**
1. As you can see, although sending the file from the browser directly to s3 bucket is possible, it is very insecure and bad practice. Here we are assuming your bucket is completely public and will accept uploads from anyone, unless your application is a non-public app and the client has allowed access to the bucket *(which is technically possible via, for example, [direct connect][1] or a [vpn connection][2] to a [vpc][3] with a [gateway to s3][4])*.
2. A more appropriate way to achieve this is to either: a) have a backend processing the request (authenticating, authorizing and validating) and then forward to the s3 bucket; b) having a backend function - like a [lambda][5] - to return a [pre-signed url][6] for the s3 bucket
[1]: https://aws.amazon.com/pt/directconnect/
[2]: https://docs.aws.amazon.com/vpn/
[3]: https://aws.amazon.com/pt/vpc/
[4]: https://docs.aws.amazon.com/pt_br/vpc/latest/privatelink/vpc-endpoints-s3.html
[5]: https://docs.aws.amazon.com/lambda/latest/dg/welcome.html
[6]: https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html |
Don't split the `CLOB` into a table of values; instead you can find a sub-string match for the terms within the `CLOB` (matching preceding and following delimiters to ensure you are matching complete terms):
```lang-sql
SELECT *
FROM Abc a
WHERE EXISTS(
SELECT 1
FROM clob_tab c
WHERE ',' || c.col1 || ',' LIKE '%,' || a.Col2 || ',%'
)
```
Which, for the sample data:
```lang-sql
CREATE TABLE clob_tab (col1) as
SELECT EMPTY_CLOB()
|| '27,88,100,25,26,210,2,3,3000'
|| RPAD(',1', 4000, '0')
FROM DUAL
UNION ALL
SELECT EMPTY_CLOB() || LISTAGG(LEVEL, ',') WITHIN GROUP (ORDER BY LEVEL)
FROM DUAL
WHERE LEVEL < 20
OR LEVEL > 30
OR LEVEL IN (23, 25, 27)
CONNECT BY LEVEL <= 200;
```
Outputs:
| COL2 |
| ----:|
| 23 |
| 25 |
| 26 |
| 27 |
[fiddle](https://dbfiddle.uk/w2VDZjTy)
|
- In Desktop
(The emulator turns on automatically)
[npm start video](https://youtu.be/uUhNKguiao4)
[terminal(?) image](https://i.stack.imgur.com/k913N.png)
[emulator image](https://i.stack.imgur.com/GY4MG.png)
- On the laptop
After turning on the emulator
can activate the React-Native
Which program is the terminal image among the images?
(Powershell X, Azure X, cmd X, ...)
I want to use it like a desktop |
It's my first time deploying a website via github pages and I've noticed a problem with embedding videos (mp4 in my case). Everything else is working and loading fine (including images) however whenever I try to view any of the embedded videos on my website, I get the following black screen with the controls greyed out:
[Video not loading](https://i.stack.imgur.com/hjr6s.png)
(for reference the video in this screen shot is only 2.89 MB)
I found this weird, because while building the website and testing things on local host, everything was working fine and all embedded videos were working perfectly with full audio and video. I've researched a bit on what the issue is but can't seem to get a clear solution as some people recommend hosting the videos externally like on youtube and then embedding that link but I really want the videos to work embedded within the website without having to host the videos anywhere else which is a last resort.
For reference, following are the snippets of my code relating to how I'm displaying these videos and cannot seem to find any errors so far:
index.html:
```
<video class="responsive-video" id="knowPros_vid" controls>
<source src="./assets/knowPros_Demo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
```
style.css:
```
/* Applying CSS limits for videos used in the carousel to avoid distortion */
.responsive-video {
max-width: 100%;
height: auto;
display: block;
margin: 0 auto;
}
```
Out of the 3 videos I have on this webpage, only one is a large video file (143 MB) but the other two are both small video files (2.89 MB & 4.39 MB), however this issue is being had with all of them which is why I think it's safe to rule out a git-lfs problem since that's only used for the largest video file.
I also don't have a gitattributes file for this repository, idk if I should cause everything has been working fine without one. (don't know if it's important but just thought I should mention it just incase)
Getting no console errors and the page is still loading up just fine. No 404 errors or network issues.
Please let me know if anyone has faced a similar issue and if so how it can be tackled. Also if any methodologies have expired as of currently, plese let me know. Thanks :)
|
(defvar my/kill-buffer-exceptions '("Messages" "emacs-file" "scratch"))
(defun my/kill-buffer-testfn (key lcar)
;; (print (list lcar key (string-match-p (regexp-quote key) lcar)))
(string-match-p (regexp-quote key) lcar))
(defun my/kill-other-buffers ()
"Kill all other buffers."
(interactive)
(mapc 'kill-buffer
(delq (current-buffer) ; filter current buder
;; filter alive and not system
(seq-filter (lambda (b) (and (buffer-live-p b) ; filter alive
(/= (aref (buffer-name b) 0) ?\s) ; filter system
;; filter exceptions
(not (seq-contains-p my/kill-buffer-exceptions
(downcase (buffer-name b))
#'my/kill-buffer-testfn))))
(seq-uniq (buffer-list))))))
(global-set-key (kbd "C-!") #'my/kill-other-buffers) |
To expand on correct [Answer by rahulmohan][1], I will add some example code.
Define our `Item` & `User` classes.
```java
record Item( String description ) { }
```
```java
final class User
{
private final String name;
private final List < Item > items;
User ( String name , List < Item > items )
{
this.name = name;
this.items = items;
}
public String id ( ) { return name; }
public List < Item > items ( ) { return items; }
public void addItem ( final Item item )
{
this.items.addLast( item ); // Or, before Java 21: `List.add( this.items.size() , item )`.
}
@Override
public boolean equals ( Object obj )
{
if ( obj == this ) return true;
if ( obj == null || obj.getClass( ) != this.getClass( ) ) return false;
var that = ( User ) obj;
return Objects.equals( this.name , that.name ) &&
Objects.equals( this.items , that.items );
}
@Override
public int hashCode ( )
{
return Objects.hash( name , items );
}
@Override
public String toString ( )
{
return "User[" +
"id=" + name + ", " +
"items=" + items + ']';
}
}
```
Some example data.
```java
final List < Item > masterListOfItems =
new ArrayList <>(
List.of(
new Item( "Dog" ) ,
new Item( "Cat" ) ,
new Item( "Bird" )
)
);
final List < User > users =
new ArrayList <>(
List.of(
new User( "Alice" , new LinkedList <>( masterListOfItems ) ) ,
new User( "Bob" , new LinkedList <>( masterListOfItems ) ) ,
new User( "Carol" , new LinkedList <>( masterListOfItems ) )
)
);
```
Bob prefers cats. So he moves the second item `Cat` into the first position (index zero), above `Dog` item.
```java
// Bob prefers cats.
User bob = users.stream( ).filter( user -> user.id( ).equalsIgnoreCase( "Bob" ) ).findAny( ).get( );
System.out.println( "(before move) bob = " + bob );
Item cat = bob.items( ).stream( ).filter( item -> item.description( ).equalsIgnoreCase( "Cat" ) ).findAny( ).get( );
bob.items( ).remove( cat );
bob.items( ).addFirst( cat );
System.out.println( "(after move) bob = " + bob );
```
When run:
```none
(before move) bob = User[id=Bob, items=[Item[description=Dog], Item[description=Cat], Item[description=Bird]]]
(after move) bob = User[id=Bob, items=[Item[description=Cat], Item[description=Dog], Item[description=Bird]]]
```
You said:
> The size of the list is not constant.
I assume that means you want to add an item, and possibly remove. Let's look at addition. We need to add the new item to the master list, and then add the item to each `User` object’s own `List`.
```java
// Add new item.
Item hamster = new Item( "Hamster" );
masterListOfItems.addLast( hamster );
users.forEach( user -> user.addItem( hamster ) );
System.out.println( "(after add) bob = " + bob );
System.out.println( "masterListOfItems = " + masterListOfItems );
```
When run, we see that Bob has his own list ordered by his personal preference while the order of our master list remains undisturbed.
```none
(after add) bob = User[id=Bob, items=[Item[description=Cat], Item[description=Dog], Item[description=Bird], Item[description=Hamster]]]
masterListOfItems = [Item[description=Dog], Item[description=Cat], Item[description=Bird], Item[description=Hamster]]
```
Be aware that this use of multiple lists is efficient with memory. The content objects (`User` & `Item` objects) are *not* being duplicated. There is only **one instance of every `Item`** object in memory, shared amongst the many `List` objects each owned by a `User` object.
[1]: https://stackoverflow.com/a/5101103/642706 |
There is so much wrong with your dynamic SQL that I won't list it. And I won't comment on your design, it doesn't sound optimal, but as say the problem is a more complex than described its hard to comment.
Anyway, with what you have provided you can do the following:
- You can loop through all categories to avoid having to manually code them
- At a row level you need to `CONCAT` the values to create a dynamic string
- At a multi-row level you need to `STRING_AGG` the rows to build a single row
```
/* Dummy Table Creation */
DECLARE @DummyWeightageTable TABLE (
Category varchar(50)
, Fieldname varchar(50)
, Weightage real
);
INSERT INTO @DummyWeightageTable
VALUES
('Sniper', 'Eyesight', 40),
('Sniper', 'BMI', 10),
('Sniper', 'Height', 10),
('Sniper', 'Skill', 20),
('Fighter', 'Eyesight', 10),
('Fighter', 'BMI', 30),
('Fighter', 'Height', 20);
/* Actual Functionality */
DECLARE @Category TABLE (
Category varchar(50)
, Done bit NOT NULL DEFAULT(0)
);
-- Capture all categories so we can loop through them
INSERT INTO @Category (Category)
SELECT Category
FROM @DummyWeightageTable
GROUP BY Category;
-- Dynamic SQL must use nvarchar
DECLARE @sql NVARCHAR(MAX), @delta NVARCHAR(MAX), @CurrentCategory varchar(50);
-- Loop through all categories
WHILE EXISTS (SELECT 1 FROM @Category WHERE Done = 0) BEGIN
SELECT TOP 1 @CurrentCategory = Category FROM @Category WHERE Done = 0;
-- Display the category at least for debugging
SET @sql = 'SELECT Emp_Id, ' + @CurrentCategory + ', ';
-- First concat the values required from each row
-- Then string_agg then into a single string
SELECT @delta = STRING_AGG(CONCAT('(', Weightage, ' * ISNULL(', Fieldname, ',0))'), ' + ')
FROM @DummyWeightageTable
WHERE Category = @CurrentCategory;
SET @sql = @sql + @delta + ' from MyDataTable1;';
-- This is how you debug dynamic SQL
PRINT @sql;
--EXEC sp_executesql @sql;
UPDATE @Category SET Done = 1 WHERE Category = @CurrentCategory;
END;
```
Returns:
```
SELECT Emp_Id, (10 * ISNULL(Eyesight,0)) + (30 * ISNULL(BMI,0)) + (20 * ISNULL(Height,0)) from MyDataTable1;
SELECT Emp_Id, (40 * ISNULL(Eyesight,0)) + (10 * ISNULL(BMI,0)) + (10 * ISNULL(Height,0)) + (20 * ISNULL(Skill,0)) from MyDataTable1;
```
[DBFiddle](https://dbfiddle.uk/ThD8RG2d) |
I am working on a Angular project. My aim is to make a book finder application using Google Books API and the problem is that sometimes when i refresh the page or I go to a different component and go back to my homepage it sometimes doesnt show any books even though the status code is 200. I checked the console and its supposed to send an array named items. When the error occurs it doesnt send that array.
all-books.component.ts :
```
import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-all-books',
templateUrl: './all-books.component.html',
styleUrls: ['./all-books.component.css']
})
export class AllBooksComponent implements OnInit {
books: any[] = [];
loading: boolean = true;
error: string | null = null;
searchQuery: string = '';
searchBy: string = 'title';
constructor(private bookService: BookService, private router: Router) { }
ngOnInit(): void {
this.fetchBooks();
}
fetchBooks(): void {
this.loading = true;
this.bookService.getRandomBooks()
.subscribe(
(data: any) => {
console.log("API Response:", data);
if (data && data.items && data.items.length > 0) {
this.books = data.items.slice(0, 9);
this.error = null;
} else {
this.books = []; // Reset books array
this.error = 'No books found.';
}
this.loading = false;
},
(error) => {
console.error('Error fetching random books:', error);
this.error = 'Failed to fetch books. Please try again later.';
this.books = [];
this.loading = false;
}
);
}
search(): void {
this.loading = true;
this.bookService.searchBooks(this.searchQuery, this.searchBy)
.subscribe(
(data: any) => {
if (data && data.items && data.items.length > 0) {
this.books = data.items;
this.error = '';
} else {
this.books = [];
this.error = 'No books found.';
}
this.loading = false;
},
(error) => {
console.error('Error fetching search results:', error);
this.error = 'Failed to fetch search results. Please try again later.';
this.books = []; // Reset books array
this.loading = false;
}
);
}
}
```
all-books.component.html :
```
<div class="container">
<div class="row mt-5 justify-content-center">
<div class="col-md-6">
<div class="input-group">
<input type="text" [(ngModel)]="searchQuery" class="form-control" placeholder="Search for books..." />
<select [(ngModel)]="searchBy" class="form-select">
<option value="title">Title</option>
<option value="author">Author</option>
<option value="isbn">ISBN</option>
</select>
<button (click)="search()" class="btn btn-primary">Search</button>
</div>
</div>
</div>
<p class="text-center font fw-bold mt-5">Here are a selection of our books</p>
<div class="container mt-3">
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4 justify-content-center">
<div class="col" *ngFor="let book of books">
<div class="card h-100">
<img [src]="book.volumeInfo?.imageLinks?.thumbnail" alt="No Book Cover Available" class="card-img-top" style="height: 350px; object-fit: cover;">
<div class="card-body">
<h5 class="card-title">{{ book.volumeInfo?.title }}</h5>
<ul class="list-group list-group-flush text-center">
<li class="list-group-item">Author: {{ book.volumeInfo?.authors?.join(', ') || 'Unknown' }}</li>
<li class="list-group-item">Release date: {{ book.volumeInfo?.publishedDate || 'Unknown' }}</li>
<li class="list-group-item">Publisher: {{ book.volumeInfo?.publisher || 'Unknown' }}</li>
</ul>
</div>
<div class="card-footer d-flex justify-content-center">
<a [routerLink]="['/book-details']" [queryParams]="{ bookId: book.id }" class="btn btn-primary fixed-button-size">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
```
book.service.ts :
```
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class BookService {
private apiUrl: string = 'https://www.googleapis.com/books/v1/volumes';
private apiKey: string = 'AIzaSyCiA_B5vlrNQXJmtTBCUzbyn1L5MIhi4OA';
constructor(private http: HttpClient) { }
searchBooks(query: string, searchBy: string): Observable<any> {
let url: string;
if (searchBy === 'title') {
url = `${this.apiUrl}?q=intitle:${query}&key=${this.apiKey}`;
} else if (searchBy === 'author') {
url = `${this.apiUrl}?q=inauthor:${query}&key=${this.apiKey}`;
} else if (searchBy === 'isbn') {
url = `${this.apiUrl}?q=isbn:${query}&key=${this.apiKey}`;
} else {
url = `${this.apiUrl}?q=${query}&key=${this.apiKey}`;
}
return this.http.get(url);
}
getRandomBooks(): Observable<any> {
const randomPage = Math.floor(Math.random() * 100);
const query = 'fiction';
const url = `${this.apiUrl}?q=${query}&startIndex=${randomPage * 10}&maxResults=10&key=${this.apiKey}`;
return this.http.get(url);
}
getBookDetails(bookId: string): Observable<any> {
const url = `${this.apiUrl}/${bookId}?key=${this.apiKey}`;
return this.http.get(url);
}
}
```
I tried debugging and also tried fixing it with chatGPT but it didn't work. |
It doesnt always show all the books on my homepage |
|angular|typescript|google-books-api| |
null |
the problem is the display of LinearGradientBrush on the button, in Android it is correct, in iOS it is not
```
<Button Text="Войти" >
<Button.Background>
<LinearGradientBrush EndPoint="1,0">
<GradientStop Color="#DA8BFF" Offset="0.1" />
<GradientStop Color="#839BFF" Offset="1" />
</LinearGradientBrush>
</Button.Background>
</Button>
```[Android](https://i.stack.imgur.com/VLSnj.png)
[IOS](https://i.stack.imgur.com/StM8s.jpg)
I tried to set sizes, add them to different containers |
Incorrect display of LinearGradientBrush in IOS |
|c#|android|ios|maui| |
null |
I need to use "callable" Cloud functions both on the client and on the backend for AppCheck to work. I think this is not stressed enough in the documentation.
**On the client**
try await functions.httpsCallable("foo").call(params) // AppCheck works
let url = URL(string: "https://us-central1-myproject.cloudfunctions.net/foo")
var request: URLRequest = .init(url: url)
try await URLSession.shared.data(for: request) // AppCheck doesn't work
**On the backend**
exports.foo = functions
.runWith({enforceAppCheck: true})
.https.onCall((data, context) => { // AppCheck works
});
const app = express();
exports.foo = functions
.runWith({enforceAppCheck: true})
.https.onRequest(app); // AppCheck doesn't work |
I have registered an endpoint for the Webhook event ```subscription.created``` in Square. Every time I make a subscription, it triggers my webhook twice instead of once. Is there something that I missed? |
The Square webhook is being triggered twice for a single event (subscription.created) |
|payment|subscription|square| |
I have a dbt-core project with the following projects.yml:
test:
target: dev
outputs:
dev:
type: bigquery
method: oauth
project: my-project-id-123456
dataset: dbt_name
location: EU
threads: 8
I had 2 Google accounts (private + business) with the same email name for some unknown reason and had to delete the private account to be able to use the business account fully. But I had already used OAuth with the now deleted account and everytime I try to run dbt-core now I get the following error:
Runtime Error
Unable to generate access token, if you're using impersonate_service_account make sure your initial account has the "roles/iam.serviceAccountTokenCreator" role on the account you are trying to impersonate.
('invalid_grant: Account has been deleted', {error': 'invalid_grant', 'error_description': 'Account has been deleted'})
I can't find a way to use my other account for OAuth? Already deleted my whole .venv folder and reinstalled dbt-bigquery. |
How to use a different account for OAuth with dbt-core and profiles.yml? |
|google-bigquery|oauth|dbt| |
I have this JSON expression
`'{"uid":false,"token":null,"ma":null,"question":[{"questionId":47599,"answerId":190054,"answer":1}],"iframe":true,"ref":"<SOMEREFERRER","ts":1711214476}'`
that a webclient (in this case, Google Chrome and Firefox on iOS) wants to send to a webserver. It is a reply on a survey form another server (SOMEREFERRER) has sent. I am rather unfamiliar with JSON and wondering what this string is exactly doing when posted to the target server.
I have found that the survey server is accepting this string multiple times and counts it as a "vote". This is not supposed to happen. |
Unravel JSON expression |
|json|webserver| |
null |