instruction stringlengths 0 30k ⌀ |
|---|
What is the best way to load 2 million records from DataTable to CSV file in asp.net core c#? |
null |
your relation is incorrect.
change it to on `TeacherDetailModel`:
```php
public function ClassListModelHasMany(){
return $this->hasMany(ClassListModel::class,'teacher_id','id');
}
```
also can change query like this:
```php
$detail = ClassListModel::where('id',$post['body']['ID'])
->with('teacherElement')
->get();
return $detail;
``` |
What EsLint rules enforces the following?
```typescript
type Incorrect = Array< number >;
type Correct = Array<number>;
```
Every @typescript-eslint / @stylistic rule I have tried dodges it. |
Eslint rule to prevent space around a typescript generic |
|eslint|typescript-eslint| |
I'm starting to get pretty frustrated with Dart's `async` ...
All I want is lazily load some value and assign it to a property in my class:
```
Future<String> getMeSomeBar() async => "bar";
class Foo {
late String bar = await getMeSomeBar();
}
```
this doesn't work, of course.
But what really drives me mad is that I know Kotlin has a [`runBlocking`][1] function that is designed for cases exactly like that and there just doesn't seem to be a Dart equivalent or pattern that would allow me to do the same.
At least not one that I've found, so far.
I can't even do a basic spin-lock in Dart because there's no way to check for the state of a `Future`...
So because `getMeSomeBar` is outside of my control, I need to make`Foo.bar` a `Future<String>`.
Which means I have to make whatever function accesses `Foo.bar` an `async` function.
Which means I have to make whatever functions accesses *that* function, an `async` function.
Which means I have to make whatever functions accesses *those* function `async` too.
Which means ...
You get the point. In the end, the whole bloody app is going to be asynchronous simply because I seem to have absolutely no way to block a thread/isolate until a `Future` is completed.
That can't be the solution?!
Is there a way to avoid this?
(No, using `then` doesn't help because then you're either waiting for the completion of *that* `Future` - which again, you seem to only be able to do in an `async` function - or you're gambling on your `Future`s' returning "in time" - which is just plain stupid.)
[1]: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html |
null |
I am trying to run a pipeline in Azure DevOps that checks the code with Snyk and then validates the dependencies using Composer, builds the Docker image then pushes it to ACR, and finally I will implement either ArgoCD or FluxCD solution for a GitOps-based approach to fetch the new image from the Azure Repo when there's a new change.
However, I keep getting this error on the Docker build task as well as the Install dependencies task...I've been trying to troubleshoot the error but didn't find anything relevant.
Here's the YAML so far:
```
trigger:
- main
pr:
- main
pool:
vmImage: 'ubuntu-latest'
variables:
ACRServiceConnection: 'ACRServiceConEH'
jobs:
- job: security
displayName: 'Security'
steps:
- checkout: self
- task: SnykSecurityScan@1
inputs:
serviceConnectionEndpoint: 'SnykConnection'
testType: 'code'
codeSeverityThreshold: 'high'
failOnIssues: false
projectName: '$(SNYK_PROJECT)'
organization: '$(SNYK_ORG)'
- job: composer
dependsOn: security
displayName: 'Composer Validation'
steps:
- checkout: self
- task: Bash@3
inputs:
script: |
targetDirectory=$(System.DefaultWorkingDirectory)/my_project_directory
if [ ! -d "$targetDirectory" ]; then
mkdir -p "$targetDirectory"
fi
cd "$targetDirectory"
composer install --prefer-dist --no-progress
displayName: 'Install dependencies'
- task: Bash@3
inputs:
script: composer validate --strict
displayName: 'Validate composer.json and composer.lock'
- job: build
displayName: 'Build'
dependsOn: security
pool:
vmImage: 'ubuntu-latest'
steps:
- checkout: self
- task: Bash@3
inputs:
script: |
docker build . --file Dockerfile --tag $(imageName):$(Build.SourceVersion)
displayName: 'Docker build'
- task: Docker@2
inputs:
containerRegistry: $(ACRServiceConnection)
repository: $(imageName)
command: 'push'
tags: '$(Build.SourceVersion)'
displayName: 'Docker push'
```
Starting: Install dependencies
==============================================================================
Task : Bash
Description : Run a Bash script on macOS, Linux, or Windows
Version : 3.236.1
Author : Microsoft Corporation
Help : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/bash
==============================================================================
##[error]Invalid file path '/home/vsts/work/1/s'.
Finishing: Install dependencies
|
[Attched][1]I want to add an information column on the right side of the stack bar area (see the attached image). Like **Do at all** combines **Often** and **Occasionally**. I want to do this in R.
# Create the data frame
```
library(tidyverse)
data <- data.frame(
event = c("Talking with family", "Donating good", "Posting on social media", "Give interview", "Volunteering for a charity", "Speaking with a journalist", "Participating in protest"),
lk1 = c(23, 20, 21, 40, 36, 40, 23),
lk2 = c(10, 36, 30, 12, 12, 12, 25),
lk3 = c(36, 20, 37, 36, 40, 36, 40),
lk4 = c(31, 24, 12, 12, 12, 12, 12),
lk1_lk2 = c(33, 56, 51, 52, 48, 52, 48)
)
```
# Plotting
```
ggplot(data_long, aes(x = value, y = event, fill = likert)) +
geom_bar(stat = "identity") +
geom_text(aes(label = value), position = position_stack(vjust = 0.5), color = "white", size = 3) +
geom_text(data = data_long %>% filter(likert == "lk1"),
aes(label = lk1_lk2, x = max(value) + 2, y = event),
hjust = -50, color = "black", size = 3) +
scale_x_continuous(labels = scales::percent_format(), expand = expand_scale(add = c(1, 10))) + # Adjusting x-axis limits
labs(title = "Preference Distribution for Various Events",
x = "Percentage",
y = "Event") +
theme_minimal() +
theme(legend.position = "top") +
geom_text(data = NULL, aes(x = Inf, y = Inf, label = "Do at All"),
hjust = 1, vjust = 1, color = "black") + # Add text at right-top corner
scale_fill_discrete(labels = c("lk1" = "Often", "lk2" = "Occasionally", "lk3" = "Never", "lk4" = "Prefer not to say"))
```
[1]: https://i.stack.imgur.com/ojtZy.jpg |
I replicated your issue with your code and found out you are trying to [`update` documents](https://cloud.google.com/firestore/docs/manage-data/add-data#update-data) even before they are created or exist. Hence, you are getting `Error: 5 NOT\_FOUND`. And you are unable to create `documents` or `collections` as you are stuck at error.
## Update
Steps I followed are :
* Created [`Cloud Function 2nd gen` using console](https://cloud.google.com/firestore/docs/manage-data/add-data#update-data).
* Selected **Trigger Type : Cloud Storage** and **Event Type : [google.cloud.storage](http://google.cloud.storage).object.v1.finalized**
* Selected inline editor and selected `node.js20` runtime and added your code by making some changes as below
```
try {
await docRef.set({ labels, processedAt: Timestamp.now() }, { merge: true });
console.log(`Processed image ${fileName} and stored labels in Firestore.`);
} catch (error) {
console.error('Error writing to Firestore:', error);
}
```
`Package.json`
```
{
"dependencies": {
"@firebase/app": "^0.9.29",
"@firebase/auth": "^1.6.2",
"@firebase/firestore": "^4.5.0",
"@google-cloud/firestore": "^7.5.0",
"@google-cloud/vision": "^4.1.0"
}
}
```
* And left everything as default. Deployed the function.
* Made changes to `cloud storage` and finally, I can see changes in [`firestore`](https://ibb.co/3mzpDc1) as well. |
`gcloud info` will give the project.
|
I recommend replacing token.objects.create with the following logic in your RegisterView:
from django.urls import reverse
from django.contrib.sites.shortcuts import get_current_site
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import RegisterSerializer
from .models import User
from .utils import Util
class RegisterView(generics.GenericAPIView):
"""
Register a new user with email and password and send verification email (Student or Tutor)
"""
serializer_class = RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data["email"])
refresh_token = RefreshToken.for_user(user)
token = str(refresh_token.access_token)
relative_link = reverse("verify-email")
current_site = get_current_site(request).domain
abs_url = "http://" + current_site + relative_link + "?token=" + token
email_body = "Hi {}! Use the link below to verify your email:\n{}".format(
user.full_name, abs_url)
data = {
"to_email": user.email,
"email_body": email_body,
"email_subject": "Verify your email",
}
Util.send_email(data)
return Response(user_data, status=status.HTTP_201_CREATED)
This logic allows you to create a user and sends an email for email verification. Ensure that you have the necessary imports and configurations set up in your Django project.
|
Blocking wait on future OUTSIDE of async functions |
|flutter|dart|asynchronous|async-await|future| |
Here is the java function that I use to create a span associated to a trace/span created in another microservice:
import io.opentelemetry.api.trace.*;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
private Span createSpanLinkedToParent(String traceId, String spanId) {
SpanContext remoteContext = SpanContext.createFromRemoteParent(
traceId,
spanId,
TraceFlags.getSampled(),
TraceState.getDefault());
Tracer t = otel.getTracer("second-service");
SpanBuilder sb= t.spanBuilder("some-operation");
sb.setParent(Context.current().with(Span.wrap(remoteContext)));
return sb.startSpan();
}
(Tested with OpenTelemetry 1.36) |
I updated the IDE (VS Code). Then the error is gone.`
> sudo apt update
> sudo apt upgrade code
> code --version (to check the version)
` |
I believe it is connected with this question: https://stackoverflow.com/questions/43185605/how-do-i-read-an-image-from-a-path-with-unicode-characters
Basically opencv have problems with reading special symbols, you need to rename your files or use other methods to read files, proposed in link below. |
|reactjs|react-native|expo|socket.io-client|react-native-webrtc| |
|python|numpy| |
I have this perspective scrolling effect and I want to make three instances of it.
Each of the instances ultimately will have different content. And each instance would be in a modal popup.
The modal popup should be triggered by a link and they're closeable by an 'x' in the corner, and the key ESC. Ideally i would like to avoid bootstrap.
CSS
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const dom = {
container: document.getElementById('container'),
perspective: document.getElementById('perspective'),
zoom: document.getElementById('zoom')
};
const totalScrollDistance = 10000; // Scroll distance to reach max zoom
const maxZoomDistance = 40000; // Maximum depth of images, based on what you've set in CSS
let looping = false;
dom.container.style.height = `${totalScrollDistance}px`;
window.addEventListener('scroll', update);
function update() {
// Check if we are waiting for a frame to render
if (!looping) {
looping = true;
raf(zoom);
}
}
function zoom() {
const rect = dom.container.getBoundingClientRect(); // Get bounding rect of container, .top is relative to top of viewport
if (rect.top <= 0 && rect.top > -rect.height) { // Update zoom only when container is in viewport
dom.perspective.classList.add('perspective--is-fixed');
const scrollPos = -rect.top; // Get scroll position relative to zoom container
const progress = scrollPos / (totalScrollDistance - window.innerHeight); // Turn this into a number between 0 and 1 (0 is when top of zoom container is at top of viewport, 1 is when bottom of zoom container is at bottom of viewport)
dom.zoom.style.transform = `translate3d(0, 0, ${progress * maxZoomDistance}px)`; // Apply transform
} else {
dom.perspective.classList.remove('perspective--is-fixed');
}
looping = false;
}
// Runs callback on next available animation frame
function raf(cb) {
const raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (cb) { window.setTimeout(cb, 1000 / 60); };
raf.call(window, () => {
return cb();
});
}
<!-- language: lang-css -->
html,body,address,blockquote,div,form,fieldset,caption,h1,h2,h3,h4,h5,h6,hr,ul,li,ol,ul,dl,dt,dd,table,tr,td,th,p,img{margin:0;padding:0}
html{width:100%;height:100%;overflow-x:hidden}
body{font-family:'Times';position:relative;width:100%;min-height:100%;color:#272935;padding:0;margin:0}
body::before,body::after{display:flex;justify-content:center;width:100%;height:25vh;color:#000}
html{overflow:none;overflow-x:hidden;scroll-behavior:smooth;scrollbar-width:none}
::-webkit-scrollbar{width:0;background:transparent}
::-webkit-scrollbar-thumb{background:red}
*,:before,:after{box-sizing:border-box}
.container{position:relative;overflow:hidden}
.perspective{width:100vw;height:100vh;background:none;position:fixed;perspective:200px}
.perspective--is-fixed{position:fixed;top:0;left:0}
.caption{color:#000;font-size:1rem;text-align:center;padding-top:20px}
p{color:#000;text-align:left;}
.zoom{width:100%;height:100%;transform-style:preserve-3d}
video{position:relative;width:45%;box-shadow:26px 33px 121px 0 rgba(119,0,0,0.4)}
img{position:relative;width:45%;box-shadow:26px 33px 121px 0 rgba(119,0,0,0.4)}
.right{float:right}
.image{position:absolute;text-align:center}
.image:nth-child(1){width:100vw;height:100vh;transform:translate3d(1vw,1vh,-200px)}
.image:nth-child(2){width:100vw;height:100vw;transform:translate3d(2vw,6vh,-1700px)}
.image:nth-child(3){width:100vw;height:100vw;transform:translate3d(0vw,6vh,-3723px)}
.image:nth-child(4){width:100vw;height:100vw;transform:translate3d(7vw,13vh,-4835px)}
.image:nth-child(5){width:100vw;height:100vw;transform:translate3d(10vw,-1vh,-6791px)}
<!-- language: lang-html -->
<div class="container" id="container">
<div class="perspective" id="perspective">
<div class="zoom" id="zoom">
<!--Content01-->
<div class="image"><img src="https://dummyimage.com/700x600/4a1bf5/ffffff" />
<div class="caption">One</div>
</div>
<!--Content02-->
<div class="image"><video autoplay loop muted>
<source src="https://upload.wikimedia.org/wikipedia/commons/8/87/Schlossbergbahn.webm" type="video/webm"></video>
<div class="caption">Two</div>
</div>
<!--Content02-->
<div class="image"><img src="https://dummyimage.com/700x600/4a1bf5/ffffff" />
<div class="caption">Three</div>
</div>
</div>
</div>
</div>
<!-- end snippet -->
|
Perspective Scrolling Effect (Three Instances) |
|javascript|html|css| |
What you describe "it runs as the owner of the stored procedure and thus the permissions assigned to that owner" is similar to the concept of "[Authorized Routines](https://cloud.google.com/bigquery/docs/authorized-routines)". As of September 2023, [authorized routines support stored procedures](https://cloud.google.com/bigquery/docs/release-notes#September_25_2023).
Regarding the permissions needed, the `bigquery.routines.get` permission is required to execute a stored procedure or UDF. This is provided by `roles/bigquery.metadataViewer` and/or `roles/bigquery.dataViewer`. In addition, if it is not an authorized routine, then yes the query user also requires the appropriate permissions on the datasets affected by the stored procedure.
**Resources**:
* [BigQuery permissions](https://cloud.google.com/bigquery/docs/access-control#bq-permissions)
* [BigQuery roles](https://cloud.google.com/bigquery/docs/access-control#permissions_and_predefined_roles)
|
I updated the IDE (VS Code). Then the error is gone.`
- sudo apt update
- sudo apt upgrade code
- code --version (to check the version)
` |
null |
You would need to target your build to the latest version inside of the vite:
So `esnext` would work best, or you can target `es2020`-`es2024`
```javascript
export default defineConfig({
// ...
build: {
target: 'esnext',
},
optimizeDeps: {
esbuildOptions: {
target: 'esnext',
},
},
})
``` |
Cannot update shortcut (folder name with space) in Powershell |
|powershell| |
Thank you, your comment helped me find the solution. I tried the 'fa-meh-blank' Remove. When I clicked it worked. And when I clicked again, my icon disappeared completely.
My new JavaScript:
icone.addEventListener('click', function(){
//console.log('icône cliqué');
icone.classList.toggle('happy');
icone.classList.toggle('fa-meh-blank');
icone.classList.toggle('fa-smile-wink');
}); |
Suppose we have a system with radix 2^32 (x = a0 \* 2^0 + a1 \* 2^32 + a2 \* 2^64 +...) and we store the coefficients in a vector (a0 in position [0] , a1 in position [1] ...).
This function allows you to calculate the square of x (for simplicity the non-zero coefficients of x occupy only half of the vector).
#include <iostream>
#include <vector>
#include <cstdlib>
#include <stdint.h>
#include <vector>
#include <omp.h>
const int64_t esp_base_N = 32;
const uint64_t base_N = 1ull << esp_base_N;
void sqr_base_N(std::vector<uint64_t> &X, std::vector<uint64_t> &Sqr , const int64_t len_base_N)
{
std::vector<uint64_t> Sqr_t(len_base_N, 0ull);
uint64_t base_N_m1 = base_N - 1ull;
for (int64_t i = 0; i < (len_base_N / 2); i++)
{
uint64_t x_t = X[i];
for (int64_t j = i + 1; j < (len_base_N / 2); j++)
{
uint64_t xy_t = x_t * X[j];
Sqr_t[i + j] += 2ull * (xy_t & base_N_m1);
Sqr_t[i + j + 1] += 2ull * (xy_t >> esp_base_N);
}
x_t *= x_t;
Sqr_t[2 * i] += x_t & base_N_m1;
Sqr_t[2 * i + 1] += x_t >> esp_base_N;
}
uint64_t mul_t;
mul_t = Sqr_t[0] >> esp_base_N;
Sqr[0] = Sqr_t[0] & base_N_m1;
for (int64_t j = 1; j < len_base_N ; j++)
{
Sqr[j] = (Sqr_t[j] + mul_t) & base_N_m1;
mul_t = (Sqr_t[j] + mul_t) >> esp_base_N;
}
}
I don't know if it is possible to speed up the function using multithreading.
I tried using OpenMP but managed to get no error just by applying to the outer for loop, furthermore the function is slower than the previous one.
#pragma omp parallel for
for (int64_t i = 0; i < (len_base_N / 2); i++)
{
uint64_t x_t = X[i];
x_t *= x_t;
Sqr_t[2 * i] += x_t & base_N_m1;
Sqr_t[2 * i + 1] += x_t >> esp_base_N;
}
for (int64_t i = 0; i < (len_base_N / 2); i++)
{
uint64_t x_t = X[i];
for (int64_t j = i + 1; j < (len_base_N / 2); j++)
{
uint64_t xy_t = x_t * X[j];
Sqr_t[i + j] += 2ull * (xy_t & base_N_m1);
Sqr_t[i + j + 1] += 2ull * (xy_t >> esp_base_N);
}
}
Is there an easy way to use multithreading for the function (OpenMP or other) to speed it up?
Edit (to test the function):
int main()
{
int64_t len_base_N = 6;
std::vector<uint64_t> X_t(len_base_N, 0ull);
X_t[0] = 1286608618ull;
X_t[1] = 2;
std::vector<uint64_t> Sqr_X(len_base_N, 0ull);
sqr_base_N(X_t, Sqr_X , len_base_N);
for(int64_t i = 0; i < len_base_N - 1; i++)
std::cout << Sqr_X[i] << ", ";
std::cout << Sqr_X[len_base_N - 1] << std::endl;
return 0;
} |
I ran the command:
**sudo docker container prune**
I had a stopped postgres sql container and the data was in the container only. Is there any way to recover this data?
These are the docker events:
2024-03-28T16:13:33.986659248+05:30 container destroy 9df67ddcc79f895e4f4922187d32a2922520d6f2a94fb5b0bad60d1fb1965894 (image=postgres, name=postgres-container)
2024-03-28T16:13:34.025769814+05:30 container destroy bc6c56e1953bda5a6fd48c741ab8bffd38e1c5c176f5b82f6166424c5f76121e (com.microsoft.product=Microsoft SQL Server, com.microsoft.version=16.0.4105.2, image=mcr.microsoft.com/mssql/server:latest, name=sql, org.opencontainers.image.ref.name=ubuntu, org.opencontainers.image.version=22.04, vendor=Microsoft)
2024-03-28T16:13:34.064037404+05:30 container destroy 9d6ecf7fc406599ee846a16938408c8dfbebe0deb2e8d063ac2fdaa3efa070fe (image=blazr-api, name=blazr-container)
2024-03-28T16:13:34.064048454+05:30 container prune (reclaimed=1984382618)
Thanks in advance.
|
sudo docker container prune recovery |
|docker|docker-machine| |
The answer, as I thought, was simple. Because I'm new to android development. I was creating my own instance of the AccessibilityService class while the application creates it itself as a service. Based on your class. And you need to learn to communicate with him. |
Below I have a SubComponent and a MainComponent. This is meant to be a page that displays an image collection. In the Subcomponent using the ```onclick()``` event you can swap between pictures in that collection. **The MainComponent will also display links to other collections, but these are links to the same component itself.**
The problem is that when I click the link to go to a new collection, my SubComponent will often use the outdated ```mainImage``` to set the imageList state. It will fetch the correct response (data) however and also ```currentImage``` will still use the correct version of ```mainPicture``` and be set correctly. So in other words only the first image of the "image chooser" will use the outdated ```mainImage``` and be set incorrectly.
SubComponent.js
```react
import React, { useState, useEffect } from 'react'
import my_client
import stockimage
const Subcomponent = ({ mainPicture, my_url, identifier }) => {
const [ imagesList, setImageList ] = useState([])
const baseImageUrl = `${my_url}`
const [ currentImage, setCurrentImage ] = useState(`main/${mainPicture}`)
useEffect(() => {
const fetchList = async () => {
const { data, error } = await my_client
.fetch(`${identifier}`)
if (data) {
setImageList([`main/${mainPicture}`, ...(data.map(obj => `sub/${obj.name}`))])
}
if (error) {
console.log(error)
setImageList([])
}
}
fetchList()
console.log("fetched")
setCurrentImage(`main/${mainPicture}`)
}, [identifier, mainPicture])
return (
<div>
{mainPicture ? <img src={`${baseImageUrl}/${currentImage}`} /> : <img src={stockimage} />}
{ imagesList && imagesList.length > 1 &&
<div>
{ imagesList.map((item, item_index) => (
<div key={item_index}>
<img src={`${baseImageUrl}/${item}`} onClick={() => setCurrentImage(item)}/>
</div>
))}
</div>
}
</div>
)
}
export default SubComponent
```
MainComponent.js (simplified)
```react
import React, { useState, useEffect, useContext } from 'react'
import SubComponent from './SubComponent'
import Context from './Context'
import my_client
import { useLocation } from 'react-router-dom'
import fetchLinks from './Functions.js'
const MainComponent = () => {
const location = useLocation()
const [ mainPicture, setMainPicture ] =
useState(location.state?.paramPicture || null)
const { identifier } = useParams()
const my_url = useContext(Context)
const [ links, setLinks ] = useState(null)
useEffect(() => {
const my_fetch = async () => {
const { data, error } = await my_client
.fetch(`${identifier}/main`)
if (data) {
setMainImage(data.mainImage)
setLinks(data.otherImagesData)
}
if (error) {
console.log(error)
}
}
if (location.state.paramPicture) {
setMainPicture(location.state.paramPicture)
fetchLinks(identifier, setLinks)
} else {
my_fetch()
}
}, [identifier, location.state.paramPicture])
return (
<div>
<SubComponent mainPicture={mainPicture} my_url={my_url} identifier={identifier} />
{links.map(item => (<Link to={`/view/${item.link}`} state={{ paramPicture: item.picture }}>))}
</div>
)
}
export default MainComponent
```
App.js (router)
```react
return (
<div className="App">
<Switch>
<Route path='/view' element={<View />} />
<Route path='/view/:link' element={<MainComponent />} />
</Switch>
</div>
)
``` |
Whenever I enter play mode, my patrolling enemy moves as expected but it's sprite is partially behind the tilemap. I can still interact with the game object. The Z position for my enemy is closer to the camera than the tilemap as well as the two points the enemy moves between.
[This is the code I used](https://i.stack.imgur.com/5ULVE.png)
[This is the issue I'm having](https://i.stack.imgur.com/6xNgZ.gif)
From what was shown when the code was originally used, the object just moved back and forth between the two points in the same z position as before.
|
null |
I am trying to pass additional Request Header in WebSocket connection in Angular for Authorization, but i am not able to find library to achieve that. Is there any way do that ?
I tried using RxJs websocket and Websockets client API.
|
Passing Request Header in Websockets in Angular |
|javascript|angular|websocket| |
null |
I am trying to deploy my ASP.NET Core Web API project that I created using Clean Architecture and my Azure Student portal account. The deployment is successful however when I navigate to the API's URL endpoint it doesn't show the JSON object that I was expecting. I also checked the application event logs in Azure but found nothing.
Expected:
[![enter image description here][1]][1]
Actual:
[![enter image description here][2]][2]
The job records are stored in Azure's SQL Servers resource and when I ran the dotnet run, it lists all the records within the database. When I ran the command below it added the Release folders for each class libraries. I'm using Azure App Extension in VS Code to deploy the Web API.
Command:
`dotnet publish -c Release`
[![enter image description here][3]][3]
Application Event Log:
[![enter image description here][4]][4]
UPDATED: Added Program.cs
using Infrastructure;
using Application;
using Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Domain.Entities;
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
var worklogCorsPolicy = "WorklogAllowedCredentialsPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(worklogCorsPolicy,
policy =>
{
policy.WithOrigins("http://localhost:5173")
.WithMethods("GET", "POST")
.WithHeaders(HeaderNames.ContentType, "x-custom-header",
HeaderNames.Authorization, "true")
.AllowCredentials();
});
});
builder.Services.AddControllers();
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddApplication();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseHsts();
app.UseHttpsRedirection();
app.UseCors(worklogCorsPolicy);
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<WorklogDbContext>();
var userManager = services
.GetRequiredService<UserManager<AppUser>>();
await context.Database.MigrateAsync();
await Seed.SeedData(context, userManager,
builder.Configuration);
}
catch (Exception ex)
{
var logger = services
.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occured during migration.");
}
app.Run();
Other Things I tried:
1. I tried creating a separate .NET Core Web API called Weather that doesn't use the clean architecture approach, after I published the application using the Release build configuration, I deployed this in Azure.
I compared this with my project that uses clean architecture and I noticed that the worklog has Release build configuration for each layer(Domain, Application, Infrastructure and API) as shown in the screenshot below: I somehow think that this is where I'm having but since there's no error thrown I couldn't verify it.
[![enter image description here][5]][5]
To deploy the API I'm using Azure App Service Extension as shown below:
[![enter image description here][6]][6]
[1]: https://i.stack.imgur.com/kiDOi.png
[2]: https://i.stack.imgur.com/ZNcuQ.png
[3]: https://i.stack.imgur.com/Bqcm5.png
[4]: https://i.stack.imgur.com/cfWdw.png
[5]: https://i.stack.imgur.com/yYzaM.png
[6]: https://i.stack.imgur.com/CodSA.png
2. Publish Profile - I found that in Visual Studio, it is possible to deploy the API thru importing the publish profile downloaded from Azure, however since I'm using VS Code I won't be able to do this.
3. I tried searching online for other ways and I found that other options are using Bicep with Azure pipeline or using Bicep with GitHub action however I'm not sure if I'm on the right track. Another is learning curve since I have to learn both options to determine if this is what I need.
Any assistance would be appreciated. |
After setting up the GitHub path in the Jenkins pipeline definition SCM (using GitHub webhook), can set the Jenkinsfile script path below to be in another repository on GitHub?
[enter image description here][1]
Thanks.
For example:
Webhook repository (https://github.example.com/example/test.git
Jenkinsfile repository (https://github.example.com/jenkinsfile/jenkinsfile-test.git)
[1]: https://i.stack.imgur.com/lmM9t.png |
|reactjs|events|rendering| |
Need to get a number using only one loop for and `charCodeAt()`
We can't use native methods and concatenations, parseInt, parseFloat, Number, +str, 1 * str, 1 / str, 0 + str, etcc
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const text = ""In this market I lost 0,0000695 USDT, today is not my day"";
const parseBalance = (str) => {
const zero = "0".charCodeAt(0);
const nine = "9".charCodeAt(0);
const coma = ",".charCodeAt(0);
let num = 0,
factor = 1;
for (let i = str.length - 1; i >= 0; i--) {
const char = str.charCodeAt(i);
if (char >= zero && char <= nine) {
num += (char - 48) * factor;
factor *= 10;
}
}
return num;
};
console.log(parseBalance(text));
<!-- end snippet -->
Need result: `0,0000695`
My current result is `695`
Tell me how to correct the formula for writing zeros |
Terraform tfstate file getting repeated locked even after Break Lease. Tfstate file stored in Azure Storage Account Container.
How do I resolve the repeated tfstate file lock issue, The tfstate file is stored in Azure SA container. |
Terraform tfstate file getting repeated locked even after Break Lease. Tfstate file stored in Azure Storage Account Container |
|terraform|locking|tfstate| |
In my work I use both STATA and R. Currently I want to perform a dose-response meta-analysis and use the "dosresmeta" package in R. The following syntax is used:
```
DRMeta <- dosresmeta(
formula = logRR ~ dose,
type = type,
cases = n_cases,
n = n,
lb = RR_lo,
ub = RR_hi,
id = ID,
data = DRMetaAnalysis
)
```
When executing this syntax, however, I encounter a problem. The error message appears:
```
Error in if (delta < tol) break : missing value where TRUE/FALSE needed.
```
The reason for this error message is that I am missing some values for the variables "n_cases" and "n", which the authors have not provided. Interestingly, STATA does not require this information for the calculation of the dose-response meta-analysis.
Is there a way to perform the analysis in R without requiring the values for "n_cases" and "n"? What can I do if I have not given these values?
I have already asked the authors for the missing values, unfortunately without success. However, I need these studies for the dose-response meta-analysis, so it is not an option to exclude them. |
null |
null |
We need to try and simplify things -- and take them step-by-step.
So, let's use a simple game scene, where we'll define a `rect` and add a `SKShapeNode` with a rectangle path, and a `SKShapeNode` with an oval path:
import UIKit
import GameplayKit
class SimpleGameScene: SKScene {
override func didMove(to view: SKView) {
guard let thisSKView = self.view else { return }
let sz = thisSKView.frame.size
let offset: CGFloat = 80.0
let x: CGFloat = offset
let y: CGFloat = offset
let w: CGFloat = sz.width - (offset * 2.0)
let h: CGFloat = sz.height * 0.4
let myRect: CGRect = .init(x: x, y: y, width: w, height: h)
let shapeNodeRect = SKShapeNode(path: UIBezierPath(rect: myRect).cgPath)
shapeNodeRect.lineWidth = 7
shapeNodeRect.strokeColor = .darkGray
addChild(shapeNodeRect)
let shapeNodeOval = SKShapeNode(path: UIBezierPath(ovalIn: myRect).cgPath)
shapeNodeOval.lineWidth = 5
shapeNodeOval.strokeColor = .systemBlue
addChild(shapeNodeOval)
}
}
Looks like this:
[![enter image description here][1]][1]
and, as we know, y-axis is "inverted" with scene kit, so we have an origin of `80,80` and positive values for width and height:
[![enter image description here][2]][2]
If we use the same values to define the rect in a "normal" app, using `CAShapeLayer`s instead of scene kit nodes:
import UIKit
class ShapeTestVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .init(red: 0.148, green: 0.148, blue: 0.148, alpha: 1.0)
let thisSKView = UIView()
thisSKView.frame = view.bounds
view.addSubview(thisSKView)
let sz = thisSKView.frame.size
let offset: CGFloat = 80.0
let x: CGFloat = offset
let y: CGFloat = offset
let w: CGFloat = sz.width - (offset * 2.0)
let h: CGFloat = sz.height * 0.4
let myRect: CGRect = .init(x: x, y: y, width: w, height: h)
let shapeNodeRect = CAShapeLayer()
shapeNodeRect.path = UIBezierPath(rect: myRect).cgPath
shapeNodeRect.lineWidth = 7
shapeNodeRect.strokeColor = UIColor.darkGray.cgColor
shapeNodeRect.fillColor = UIColor.clear.cgColor
thisSKView.layer.addSublayer(shapeNodeRect)
let shapeNodeOval = CAShapeLayer()
shapeNodeOval.path = UIBezierPath(ovalIn: myRect).cgPath
shapeNodeOval.lineWidth = 5
shapeNodeOval.strokeColor = UIColor.systemBlue.cgColor
shapeNodeOval.fillColor = UIColor.clear.cgColor
thisSKView.layer.addSublayer(shapeNodeOval)
}
}
we get this:
[![enter image description here][3]][3]
with non-inverted y-axis:
[![enter image description here][4]][4]
What may be confusing the issue is the fact that an inverted rectangle or oval doesn't look any different.
So, let's add an "arrow" bezier path shape:
let p1: CGPoint = .init(x: myRect.midX - 60.0, y: myRect.minY + 80.0)
let p2: CGPoint = .init(x: myRect.midX, y: myRect.minY)
let p3: CGPoint = .init(x: myRect.midX + 60.0, y: myRect.minY + 80.0)
let p4: CGPoint = .init(x: myRect.midX, y: myRect.maxY)
let p5: CGPoint = .init(x: myRect.minX, y: myRect.maxY)
let p6: CGPoint = .init(x: myRect.maxX, y: myRect.maxY)
let pth = UIBezierPath()
pth.move(to: p1)
pth.addLine(to: p2)
pth.addLine(to: p3)
pth.move(to: p2)
pth.addLine(to: p4)
pth.move(to: p5)
pth.addLine(to: p6)
[![enter image description here][5]][5]
Let's add that as another `CAShapeLayer` in our "normal" app:
let shapeNodeArrow = CAShapeLayer()
shapeNodeArrow.path = pth.cgPath
shapeNodeArrow.lineWidth = 3
shapeNodeArrow.strokeColor = UIColor.systemRed.cgColor
shapeNodeArrow.fillColor = UIColor.clear.cgColor
thisSKView.layer.addSublayer(shapeNodeArrow)
and we get this (as expected):
[![enter image description here][6]][6]
If we then add that arrow bezier path as another `SKShapeNode` in our scene kit app:
let shapeNodeArrow = SKShapeNode(path: pth.cgPath)
shapeNodeArrow.lineWidth = 3
shapeNodeArrow.strokeColor = .systemRed
addChild(shapeNodeArrow)
we get this result:
[![enter image description here][7]][7]
and now it's pretty easy to see that the inverted y-axis ***also*** inverts the path(s) we've created.
-------------
Again, simplify what you're doing to make it easier to learn and understand what's going on. It also helps to add `print(...)` statements, or Debug Breakpoints, to evaluate your calculations.
Using the code you posted, if I set `trackOffset = 80.0` and then `print(trackRect)` at the end, I get (on an iPhone 15 Pro):
(-116.5, -215.6, 233.0, 260.8)
which is almost *certainly* not the rectangle origin you are going for.
--------------
Full code for each example...
**"normal" app with `CAShapeLayer`:**
class ShapeTestVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .init(red: 0.148, green: 0.148, blue: 0.148, alpha: 1.0)
let thisSKView = UIView()
thisSKView.frame = view.bounds
view.addSubview(thisSKView)
let sz = thisSKView.frame.size
let offset: CGFloat = 80.0
let x: CGFloat = offset
let y: CGFloat = offset
let w: CGFloat = sz.width - (offset * 2.0)
let h: CGFloat = sz.height * 0.4
let myRect: CGRect = .init(x: x, y: y, width: w, height: h)
let shapeNodeRect = CAShapeLayer()
shapeNodeRect.path = UIBezierPath(rect: myRect).cgPath
shapeNodeRect.lineWidth = 7
shapeNodeRect.strokeColor = UIColor.darkGray.cgColor
shapeNodeRect.fillColor = UIColor.clear.cgColor
thisSKView.layer.addSublayer(shapeNodeRect)
let shapeNodeOval = CAShapeLayer()
shapeNodeOval.path = UIBezierPath(ovalIn: myRect).cgPath
shapeNodeOval.lineWidth = 5
shapeNodeOval.strokeColor = UIColor.systemBlue.cgColor
shapeNodeOval.fillColor = UIColor.clear.cgColor
thisSKView.layer.addSublayer(shapeNodeOval)
let p1: CGPoint = .init(x: myRect.midX - 60.0, y: myRect.minY + 80.0)
let p2: CGPoint = .init(x: myRect.midX, y: myRect.minY)
let p3: CGPoint = .init(x: myRect.midX + 60.0, y: myRect.minY + 80.0)
let p4: CGPoint = .init(x: myRect.midX, y: myRect.maxY)
let p5: CGPoint = .init(x: myRect.minX, y: myRect.maxY)
let p6: CGPoint = .init(x: myRect.maxX, y: myRect.maxY)
let pth = UIBezierPath()
pth.move(to: p1)
pth.addLine(to: p2)
pth.addLine(to: p3)
pth.move(to: p2)
pth.addLine(to: p4)
pth.move(to: p5)
pth.addLine(to: p6)
let shapeNodeArrow = CAShapeLayer()
shapeNodeArrow.path = pth.cgPath
shapeNodeArrow.lineWidth = 3
shapeNodeArrow.strokeColor = UIColor.systemRed.cgColor
shapeNodeArrow.fillColor = UIColor.clear.cgColor
thisSKView.layer.addSublayer(shapeNodeArrow)
}
}
--------------
Full code for each example...
**scene kit app with `SKShapeNode`:**
class SimpleGameScene: SKScene {
override func didMove(to view: SKView) {
guard let thisSKView = self.view else { return }
let sz = thisSKView.frame.size
let offset: CGFloat = 80.0
let x: CGFloat = offset
let y: CGFloat = offset
let w: CGFloat = sz.width - (offset * 2.0)
let h: CGFloat = sz.height * 0.4
let myRect: CGRect = .init(x: x, y: y, width: w, height: h)
let shapeNodeRect = SKShapeNode(path: UIBezierPath(rect: myRect).cgPath)
shapeNodeRect.lineWidth = 7
shapeNodeRect.strokeColor = .darkGray
addChild(shapeNodeRect)
let shapeNodeOval = SKShapeNode(path: UIBezierPath(ovalIn: myRect).cgPath)
shapeNodeOval.lineWidth = 5
shapeNodeOval.strokeColor = .systemBlue
addChild(shapeNodeOval)
let p1: CGPoint = .init(x: myRect.midX - 60.0, y: myRect.minY + 80.0)
let p2: CGPoint = .init(x: myRect.midX, y: myRect.minY)
let p3: CGPoint = .init(x: myRect.midX + 60.0, y: myRect.minY + 80.0)
let p4: CGPoint = .init(x: myRect.midX, y: myRect.maxY)
let p5: CGPoint = .init(x: myRect.minX, y: myRect.maxY)
let p6: CGPoint = .init(x: myRect.maxX, y: myRect.maxY)
let pth = UIBezierPath()
pth.move(to: p1)
pth.addLine(to: p2)
pth.addLine(to: p3)
pth.move(to: p2)
pth.addLine(to: p4)
pth.move(to: p5)
pth.addLine(to: p6)
let shapeNodeArrow = SKShapeNode(path: pth.cgPath)
shapeNodeArrow.lineWidth = 3
shapeNodeArrow.strokeColor = .systemRed
addChild(shapeNodeArrow)
}
}
[1]: https://i.stack.imgur.com/05Mzh.png
[2]: https://i.stack.imgur.com/I5Mg1.png
[3]: https://i.stack.imgur.com/Sj6kq.png
[4]: https://i.stack.imgur.com/TrrQb.png
[5]: https://i.stack.imgur.com/hrfqr.png
[6]: https://i.stack.imgur.com/7FBrE.png
[7]: https://i.stack.imgur.com/gHPt3.png
|
I'm working on a VUE app. Part of the app is to show a table (team) with information from the backend (by axios / django rest_framework). This all works.
When I click "nieuwe categorie" the modal opens with a form. Onsubmit, the function "submitHandler" is used. However, in that function I can't get the form data? Which I need to "POST" with axios to the backend....
I've tried v-model on the modal form, but gives a reference error.
Anyway, any help would be appreciated.
The modal component:
```<script setup>
<script setup>
import { defineProps, defineEmits, ref } from "vue";
import { onClickOutside } from '@vueuse/core'
const offset = 6
const props = defineProps({
isOpen: Boolean,
isTest: String,
Categorie: String,
modalAction: String,
});
const emit = defineEmits(["modal-close"]);
const target = ref(null)
onClickOutside(target, () => emit('modal-close'))
</script>
<template>
<div v-if="isOpen" class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container" ref="target">
<div class="modal-header py-5">
<slot name="header">
<div v-if="modalAction === 'new'">
<h1>Nieuwe Categorie</h1>
</div>
<div v-else-if="modalAction === 'edit'"> {{ Categorie }}</div>
</slot>
</div>
<div class="modal-body">
<slot name="content">
<div class="mx-2" v-if="modalAction === 'new'">
<form class="w-full" @submit.prevent="submitHandler">
<div class="flex -mx-2">
<div class="items-center border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
Categorie
</label>
<select
class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
placeholder="1:1" aria-label="">
<option v-for="n in 14">Onder-{{ n + offset }}
</option>
</select>
</div>
</div>
<div class="flex -mx-2">
<div class="w-full items-center border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
T/M geboortejaar
</label>
<select
class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
placeholder="1:1" aria-label="">
<option v-for="n in 14">{{ n + 2003 }}</option>
</select>
</div>
<div class="w-10"></div>
<div class="w-full items-center border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
Aantal veldspelers
</label>
<select
class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
placeholder="1:1" aria-label="">
<option>4</option>
<option>6</option>
<option>8</option>
<option>11</option>
</select>
</div>
</div>
<div class="flex -mx-2">
<div class="items-center w-full border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
Veldomvang
</label>
<select
class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
type="select" placeholder="1:1" aria-label="veld">
<option>1:8</option>
<option>1:4</option>
<option>1:2</option>
<option>1:1</option>
</select>
</div>
<div class="w-10"></div>
<div class="items-center w-full border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
Wedstrijdduur
</label>
<select
class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
placeholder="1:1" aria-label="">
<option>12</option>
<option>2x20 (na 10min time-out)</option>
<option>2x25 (na 12,5min time-out)</option>
<option>2x30 (na 15min time-out)</option>
<option>2x30</option>
<option>2x35</option>
<option>2x40</option>
<option>2x45</option>
</select>
</div>
</div>
<div class="flex -mx-2">
<div class="w-full items-center border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
Dispensatie
</label>
<select
class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
placeholder="1:1" aria-label="">
<option v-for="n in 3">{{ n }}</option>
</select>
</div>
<div class="w-10"></div>
<div class="w-full items-center border-b border-teal-500 py-2 px-2">
<label
class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
for="grid-first-name">
Actief binnen club
</label>
<input
class="appearance-none bg-transparent border-blue text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
type="checkbox" placeholder="1" aria-label="dispensatie">
</input>
</div>
</div>
</form>
</div>
</slot>
</div>
<div class="modal-footer">
<slot name="footer">
<div>
<!--<button @click.stop="emit('modal-close')">Submit</button>-->
<button>Submit</button>
</div>
</slot>
</div>
</div>
</div>
</div>
</template>
<script>
</script>
<style scoped>
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-container {
width: 800px;
margin: 150px auto;
padding: 20px 30px;
background-color: #fff;
border-radius: 2px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
}
</style>
```
and the view:
```
<script setup>
import { ref } from "vue";
import ModalComponent from "../components/ModalComponent.vue";
import axios from 'axios'
const isModalOpened = ref(false);
const test = ref('')
const editCategorie = ref('')
const modalAction = ref('new')
const form = ref([])
const openModal = (cat, action) => {
if (!action) {
console.log('action: ', action)
action = 'new'
}
modalAction.value = action
editCategorie.value = cat.categorie
isModalOpened.value = true;
};
const closeModal = () => {
isModalOpened.value = false;
};
const submitHandler = () => {
//here I should be able to get the form data
console.log('data:', this.form) //this gives an error 'form not defined'
}
</script>
<template>
<div class="p-2 pt-20 sm:ml-64">
<div class="p-4 border-2 border-gray-200 border-dashed bg-gray-200 rounded-lg dark:border-gray-700 mt-14">
<!-- CRUD table goes here-->
<!-- Start block -->
<section class="bg-gray-50 dark:bg-gray-900 p-3 sm:p-5 antialiased">
<div class="mx-auto max-w-screen-xl px-4 lg:px-12">
<!-- Start coding here -->
<div class="bg-white dark:bg-gray-800 relative shadow-md sm:rounded-lg overflow-hidden">
<div
class="flex flex-col md:flex-row items-center justify-between space-y-3 md:space-y-0 md:space-x-4 p-4">
</div>
<div class="overflow-x-auto">
<table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
<thead
class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
<th scope="col" class="px-4 py-3">Actief binnen club</th>
<th scope="col" class="px-4 py-3">Categorie</th>
<th scope="col" class="px-4 py-3">t/m geboortejaar</th>
<th scope="col" class="px-4 py-3">Max. aantal veldspelers</th>
<th scope="col" class="px-4 py-3">Veldomvang</th>
<th scope="col" class="px-4 py-3">Wedstrijdduur</th>
<th scope="col" class="px-4 py-3">Dispensatie</th>
<th scope="col" class="px-4 py-3">Wijzig</th>
</tr>
</thead>
<tbody v-for="cat in teamcats">
<tr class="border-b dark:border-gray-700">
<td class="px-4 py-3">
<input v-model="cat.actief" type="checkbox" />
</td>
<th scope="row"
class="px-4 py-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">
{{ cat.categorie }}</th>
<td class="px-4 py-3">{{ cat.geboortejaar }}</td>
<td class="px-4 py-3">{{ cat.veldspelers }}</td>
<td class="px-4 py-3 max-w-[12rem] truncate">{{ cat.veldomvang }}</td>
<td class="px-4 py-3">{{ cat.wedstrijdduur }}</td>
<td class="px-4 py-3">{{ cat.dispensatie }}</td>
<td class="px-4 py-3"><button class="bg-blue-300"
@click="openModal(cat, mode = 'edit')">Wijzig</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="flex flex-col italic md:flex-row justify-between items-start md:items-center space-y-3 md:space-y-0 p-4"
aria-label="Table navigation">
<span class="text-sm font-normal text-gray-500 dark:text-gray-400">
Datum laatste wijziging:
<span class="font-semibold text-gray-900 dark:text-white">22-03-2024</span>
</span>
<div>
<!-- Modal toggle -->
<div>
<!--<button @click="openModal">Toevoegen Categorie</button>-->
<button @click="openModal">Toevoegen Categorie</button>
</div>
</div>
</div>
</div>
<!-- modal-->
<ModalComponent :isOpen="isModalOpened" :modalAction="modalAction" :Categorie="editCategorie"
@modal-close="closeModal" @submit="submitHandler" name="first-modal">
<template #header></template>
<template #content></template>
<template #footer><button @click="submitHandler">submit</button></template>
</ModalComponent>
<!-- modal-->
</div>
</section>
<!-- End block -->
<!-- END OF CRUD Table-->
</div>
</div>
</template>
<script>
import axios from 'axios'
import TestView from "./TestView.vue";
export default {
data() {
return {
teamcats: [],
}
},
mounted() {
this.getTeamCats()
},
methods: {
getTeamCats() {
axios
.get('/api/team/view')
.then(response => {
console.log(response.data)
this.teamcats = response.data
})
.catch(error => {
console.log('error', error)
})
},
}
}
</script>
|
How to get the form data from the modal-component into the submithandler |
|javascript|forms|vue.js|axios|modal-dialog| |
[![Backend call failure][1]][1]
Recently we started facing `Backend call failure` issue on the Nextjs app. (Failed to load resouce: the server responded with a status of 500)
We have tried enabling App insights but not able to find anything in the logs.
In Availability and Performance section we are able to see Number of backend errors stating `Failed invocation of backends and functions` but not able to find source of these issues. (ref below image)
One more thing, recently we had also created another deployment of the same app pointing to the staging branch (Intent is to have two different env), timing was almost similar when we started seeing this issue. But even after deleting the newly created deployment (Azure static web app resouce) the issue persists.
FYI:
1. The app is deployed on Azure Static Web App resource, currently we are using Free tier of azure.
2. We have only one static functions written in the `pages/api` folder of the nextjs app, other api call are direclty made from app to the backend (Hosted in azure).
3. The app keeps loading for 45 secs before throwning this error on the frontend.
4. App is working fine in local.
5. For deployment we are using github actions to build the app and deploy it on azure.
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/fjUB7.png
[2]: https://i.stack.imgur.com/Kq9kf.png |
"Backend call failure" error in Nextjs App deployed on Azure static web app |
|azure|next.js|backend|devops|azure-static-web-app| |
My fix was timeout. If you want your task to stay running permanently, then there are check boxes you might want to try unticking.
[] Stop the task if it runs longer than x
[] If the running task does not end when requested, force it to stop |
I'm on an AWS sagemaker instance, and I am trying to install nodejs so I can use CDK to deploy an app. I am using
!curl -sL https://rpm.nodesource.com/setup_14.x | sudo -E bash -
!sudo yum install -y nodejs
But when I install I keep getting the error below (tried different versions 14, 16 and 20):
Loaded plugins: dkms-build-requires, extras_suggestions, kernel-livepatch,
: langpacks, priorities, update-motd, versionlock
https://download.docker.com/linux/centos/2/x86_64/stable/repodata/repomd.xml: [Errno 14] HTTPS Error 404 - Not Found
Trying other mirror.
neuron | 2.9 kB 00:00
297 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package nodejs.x86_64 2:20.12.0-1nodesource will be installed
--> Processing Dependency: glibc >= 2.28 for package: 2:nodejs-20.12.0-1nodesource.x86_64
--> Processing Dependency: libm.so.6(GLIBC_2.27)(64bit) for package: 2:nodejs-20.12.0-1nodesource.x86_64
--> Processing Dependency: libc.so.6(GLIBC_2.28)(64bit) for package: 2:nodejs-20.12.0-1nodesource.x86_64
--> Finished Dependency Resolution
Error: Package: 2:nodejs-20.12.0-1nodesource.x86_64 (nodesource-nodejs)
Requires: libm.so.6(GLIBC_2.27)(64bit)
Error: Package: 2:nodejs-20.12.0-1nodesource.x86_64 (nodesource-nodejs)
Requires: libc.so.6(GLIBC_2.28)(64bit)
Error: Package: 2:nodejs-20.12.0-1nodesource.x86_64 (nodesource-nodejs)
|
Deploying CDK python app from Amazon Sagemaker Notebook instance |
|node.js|linux|amazon-sagemaker|amazon-linux| |
[In this link ][1], the precision recall curve is calculated for each class. So, can we calculate precision recall auc like OvO auc roc? How can we combine class 0 and 1 just like the graph ([in this link][2]) and then get ovo precision recall auc? [![OvO auc][3]][3]
[1]: https://stackoverflow.com/questions/56090541/how-to-plot-precision-and-recall-of-multiclass-classifier?rq=3
[2]: https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html
[3]: https://i.stack.imgur.com/6EWjA.png |
How to plot OvO precision recall curve for a multi-class classifier? |
|python|matplotlib|scikit-learn|precision|roc| |
You can use a recursive CTE for this. I would warn you that this is likely to be very slow on 1.5m rows.
It's a bit complicated to get attribute names, because it doesn't seem you can do `.nodes('@*')` to get all attributes.
Instead you need to `CROSS APPLY` a union of the node name and its atttributes.
```tsql
WITH cte AS (
SELECT
xpath = r.RemittanceInstr.value('local-name(.)[1]','nvarchar(max)'),
child = r.RemittanceInstr.query('*')
FROM Remittance r
UNION ALL
SELECT
xpath = CONCAT(cte.xpath, '/', v2.name),
v2.child
FROM cte
CROSS APPLY cte.child.nodes('*') x(nd)
CROSS APPLY (VALUES (x.nd.value('local-name(.)[1]','nvarchar(max)') )) v(name)
CROSS APPLY (
SELECT
v.name,
x.nd.query('./*')
UNION ALL
SELECT
CONCAT(v.name, '/@', x2.attr.value('local-name(.)[1]','nvarchar(max)')),
NULL
FROM x.nd.nodes('*/@*') x2(attr)
) v2(name, child)
)
SELECT DISTINCT
xpath
FROM cte;
``` |
null |
In swift
let rectInTableView = tableView.rectForRow(at: indexPath)
let rectInSuperview = tableView.convert(rectInTableView, to: tableView.superview)
|
Thanks to [@wOxxOm][1] I was able to properly handle removing the old event handler. I currently experience this issue due to trying to handle another issue that stemmed from re-injecting scripts when the extension reloads see: https://stackoverflow.com/questions/10994324/chrome-extension-content-script-re-injection-after-upgrade-or-install
## Content Script Code
```js
function onUnloadHandler() {
if (chrome.runtime.id) {
// perform cleanup here; save things, etc
}
else {
window.removeEventListener("beforeunload", onUnloadHandler);
}
}
window.addEventListener("beforeunload", onUnloadHandler);
```
## Explanation
This code is a basic example of handling some cleanup before the window closes, while also detecting if the old event handler is still in place and removing it. If utilizing the reinjection technique listed above there will be a new handler in place to handle the cleanup. Technically when this initially fires there will be the new handler and the old. We must make sure the old handler is removed and does not try to interact with the old `chrome.runtime` that is now disconnected. Utilizing `window.removeEventListener` is a better method than checking fo `chrome.runtime.id` and just returning. Otherwise these handlers would continue stacking up on pages every time the extension reloaded/reinjected. By utilizing the `window.removeEventLister` the garbage collector can clean it up.
## One Gotcha
One thing to be mindful of is that upon extension reload you will now have your new script re-injected, but the old handler code will be on the page, so it's possible you may need to give a restart of the extension, refresh the page (which will contain the old handler), restart the extension again, refresh the page -- this will now kick off the new handler.
[1]: https://stackoverflow.com/users/3959875/woxxom |
I am using PHP FFI to call a C++ DLL. I do not know how to pass PHP class objects to C++ DLL and convert the ptr sent back from C++ DLL to PHP objects.
I wrote a demo to illustrate my problem.
The C++ code:
```
typedef int(__stdcall* CALLBACKFUNC) (void* lpObj, int mtdId);
class MyClass {
private:
void* m_PhpObj;
CALLBACKFUNC m_Callback;
public:
MyClass(CALLBACKFUNC callback, void* phpObj) {
m_PhpObj = phpObj;
m_Callback = callback;
}
int doSomething1() {
int ret = (*m_Callback)(m_PhpObj, 1);
return ret;
}
int doSomething2() {
int ret = (*m_Callback)(m_PhpObj, 2);
return ret;
}
};
extern "C" __declspec(dllexport) void* __stdcall MyClass_Create(CALLBACKFUNC callback, void* phpObj) {
MyClass* obj = new MyClass(callback, phpObj);
return obj;
}
extern "C" __declspec(dllexport) int __stdcall MyClass_Do(void* lpObj, int mtdId) {
if (!lpObj) return 0;
MyClass* lpT = (MyClass*)lpObj;
if (mtdId == 1) {
return lpT->doSomething1();
} else {
return lpT->doSomething2();
}
}
```
The PHP code:
```
<?php
$ffi = FFI::cdef("
typedef int(__stdcall* CALLBACKFUNC) (void* lpObj, int mthId);
void* MyClass_Create(CALLBACKFUNC lpSink, void* phpObj);
int MyClass_Do(void* lpObj, int mtdId)",
"dllpath");
function callbackfunc($lpObj, $mthId) {
// The second question: how to convert $lpObj to MyClass object and call member function by this object
$obj = VoidPtrToObj($lpObj);
switch ($mthId) {
case 1:
return $obj->doSomething1();
case 2:
return $obj->doSomething2();
default:
return -1;
}
}
class MyClass{
var $cppObj;
var $count1 = 0;
var $count2 = 0;
public function __construct() {
global $ffi;
//The first question: how pass $this to void*
$this->cppObj = $ffi->MyClass_Create("callbackfunc", ObjToVoidPtr($this));
}
public function callCppDo1() {
global $ffi;
$ffi->MyClass_Do($this->cppObj, 1);
}
public function callCppDo2() {
global $ffi;
$ffi->MyClass_Do($this->cppObj, 2);
}
public function doSomething1() {
$this->count1++;
return $this->count1;
}
public function doSomething2() {
$this->count2++;
return $this->count2;
}
}
$obj = new MyClass();
$obj->callCppDo1();
$obj->callCppDo1();
$obj->callCppDo2();
//expect $obj->count1 == 2, $obj->count2 == 1
```
I tried:
1) pass serialize($this) to the C++ DLL, and call unserialize() at function callbackfunc(), but unserialize() will create a new object, miss property value;
2) create a global array, store array[spl_object_id($this)] = $this and pass spl_object_id($this) to the C++ DLL, then get object from array by id. However, it maybe inefficient.
|
I have a table I'm trying to sort by column values in Stage
It looks something like this:
|CaseID|Stage|EventDate|
|------|-----|---------|
|1 |A |01/01/10 |
|1 |B |01/03/10 |
|1 |B |01/04/10 |
|1 |C |01/05/10 |
|2 |A |02/01/10 |
|2 |B |02/02/10 |
|2 |C |02/03/10 |
|2 |C |02/05/10 |
I'm trying to organize the data by the Stage so that only the latest EventDate shows something like this
|CaseID|A |B |C |
|------|--------|--------|--------|
|1 |01/01/10|01/04/10|01/05/10|
|2 |02/01/10|02/02/10|02/05/10|
I did a group by statement
```
SELECT CaseID
,CASE WHEN Stage = 'A' THEN MAX(EventDate) END AS A
,CASE WHEN Stage = 'B" THEN MAX(EventDate) END AS B
,CASE WHEN Stage = 'C' THEN MAX(EventDate) END AS C
FROM StageTable
GROUP BY CaseID, Stage
```
But this returned too many rows with NULL placeholders
|CaseID|A |B |C |
|------|--------|--------|--------|
|1 |01/01/10|NULL |NULL |
|1 |NULL |01/04/10|NULL |
|1 |NULL |NULL |01/05/10|
|2 |02/01/10|NULL |NULL |
|2 |NULL |02/02/10|NULL |
|2 |NULL |NULL |02/05/10|
I'd like for each row to condense, but I don't know where I went wrong. I've seen other questions with similar questions, but they all seemed to have issues with joint tables showing duplicate results. Any suggestions would be helpful
|
[![My microsoft graph app permissions][1]][1]
[1]: https://i.stack.imgur.com/74H87.png
I am using microsoft graph api app to pull employee information and I am not Azure admin. Admin in my organization has authorized me attached permissions. Even with grated permissions am getting error,
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
I am getting Client correctly.
Can you please help to resolve this error ? |
Microsoft graph api app throwing error Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation |
|microsoft-graph-api| |
I fixed my issue by adding `app:labelVisibilityMode="unlabeled"` to my bottomNavigationView tag. This completely removed the animation. Thank you for your assistance ! |
Rather than using some kind of counter, put the URL components into a list then you can just iterate over that.
In this code the implementation of _get_rows() is a dummy.
from collections.abc import Iterable
parts = [
("chile", "primera-division", "Chi-A"),
("algeria", "ligue-1", "Alg-A"),
("australia", "a-league", "Aus-A"),
("austria", "bundesliga", "Aut-A")
]
def _get_rows(url: str) -> Iterable:
...
for country, division, _ in parts:
url = f"https://www.betexplorer.com/football/{country}/{division}/results"
_get_rows(url)
|
|neo4j|cypher|jqassistant| |
I have Ollama running in a Docker container that I spun up from the official image. I can successfully pull models in the container via interactive shell by typing commands at the command-line such as:
`ollama pull nomic-embed-text`
This command pulls in the model: nomic-embed-text.
Now I try to do the same via dockerfile:
```
FROM ollama/ollama
RUN ollama pull nomic-embed-text
# Expose port 11434
EXPOSE 11434
# Set the entrypoint
ENTRYPOINT ["ollama", "serve"]
```
and get
```
Error: could not connect to ollama app, is it running?
------
dockerfile:9
--------------------
7 | COPY . .
8 |
9 | >>> RUN ollama pull nomic-embed-text
10 |
11 | # Expose port 11434
--------------------
ERROR: failed to solve: process "/bin/sh -c ollama pull nomic-embed-text" did not complete successfully: exit code: 1
```
As far as I know, I am doing the same thing but it works in one place and not another. Any help?
Based on the error message, I updated the dockerfile to launch the ollama service before pulling the model. No change.
```
FROM ollama/ollama
# Expose port 11434
EXPOSE 11434
RUN ollama serve &
RUN ollama pull nomic-embed-text
```
It gave same error message.
|
The value that you are trying to store is not numeric.
See [TS.ADD][1]:
> value
is (double) numeric data value of the sample. The double number should follow RFC 7159 (JSON standard). In particular, the parser rejects overly large values that do not fit in binary64. It does not accept NaN or infinite values.
[1]: https://redis.io/commands/ts.add/ |
I found out that the way to do this is to grab the type of the object and mock the property of the type. The solution is therefore
```
def test_A(mocker):
myObj = A()
type(myObj).a2 = mocker.PropertyMock(
side_effect=iter([[2, 3], [3, 4], [4, 5]])
)
myObj.run()
``` |
Im still new to the programming and I was wondering what is the problem in the code:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#define MAX_ROOMS 100 // Maximum number of rooms in the map
#define INF INT_MAX // Infinity value for distances
// Structure to represent an edge in the graph
typedef struct {
int source;
int destination;
int weight;
} Edge;
// Structure to represent a graph
typedef struct {
int numRooms;
int numEdges;
Edge edges[MAX_ROOMS * MAX_ROOMS]; // Assuming each room can be connected to all other rooms
} Graph;
// Structure to represent a queue node for BFS
typedef struct {
int vertex;
int distance;
} QueueNode;
// Structure to represent a queue
typedef struct {
int front, rear;
int capacity;
QueueNode* array;
} Queue;
// Function to create a new queue
Queue* createQueue(int capacity) {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->capacity = capacity;
queue->front = queue->rear = -1;
queue->array = (QueueNode*)malloc(queue->capacity * sizeof(QueueNode));
return queue;
}
// Function to check if the queue is empty
bool isEmpty(Queue* queue) {
return queue->front == -1;
}
// Function to add an element to the queue
void enqueue(Queue* queue, int vertex, int distance) {
QueueNode newNode;
newNode.vertex = vertex;
newNode.distance = distance;
queue->array[++queue->rear] = newNode;
if (queue->front == -1) {
queue->front = 0;
}
}
// Function to remove an element from the queue
QueueNode dequeue(Queue* queue) {
QueueNode node = queue->array[queue->front];
if (queue->front == queue->rear) {
queue->front = queue->rear = -1;
}
else {
queue->front++;
}
return node;
}
// Function to read the map from a text file and construct the graph
Graph readMapFromFile(const char* filename) {
FILE* file;
errno_t err = fopen_s(&file, filename, "r");
if (err != 0) {
printf("Error opening file.\n");
exit(EXIT_FAILURE);
}
Graph graph;
fscanf_s(file, "%d %d", &graph.numRooms, &graph.numEdges);
for (int i = 0; i < graph.numEdges; i++) {
fscanf_s(file, "%d %d %d", &graph.edges[i].source, &graph.edges[i].destination, &graph.edges[i].weight);
}
fclose(file);
return graph;
}
// Function to perform BFS and find the center of Harry's friends' component
int bfsFindCenterOfFriendsComponent(Graph graph, int mainSourceRoom, int* numFriends) {
// Initialize distances array
int distances[MAX_ROOMS];
for (int i = 0; i < graph.numRooms; i++) {
distances[i] = INF;
}
// Initialize visited array
bool visited[MAX_ROOMS] = { false };
// Perform BFS
Queue* queue = createQueue(graph.numRooms);
enqueue(queue, mainSourceRoom, 0);
visited[mainSourceRoom] = true;
distances[mainSourceRoom] = 0;
while (!isEmpty(queue)) {
QueueNode current = dequeue(queue);
int currentRoom = current.vertex;
int currentDistance = current.distance;
for (int i = 0; i < graph.numEdges; i++) {
if (graph.edges[i].source == currentRoom) {
int neighbor = graph.edges[i].destination;
int weight = graph.edges[i].weight;
if (!visited[neighbor]) {
visited[neighbor] = true;
distances[neighbor] = currentDistance + weight;
enqueue(queue, neighbor, distances[neighbor]);
}
}
}
}
// Find the farthest room from the main source room
int farthestRoom = mainSourceRoom;
int maxDistance = 0;
for (int i = 0; i < graph.numRooms; i++) {
if (distances[i] > maxDistance && distances[i] != INF) {
maxDistance = distances[i];
farthestRoom = i;
}
}
// Now, we perform BFS again starting from the farthest room to find the center
// This time, we use the farthest room as the source
// We calculate distances from the farthest room to all other rooms
// The room with the minimum maximum distance to other rooms will be the center
// Reset distances array
for (int i = 0; i < graph.numRooms; i++) {
distances[i] = INF;
}
// Reset visited array
for (int i = 0; i < graph.numRooms; i++) {
visited[i] = false;
}
// Perform BFS from the farthest room
enqueue(queue, farthestRoom, 0);
visited[farthestRoom] = true;
distances[farthestRoom] = 0;
while (!isEmpty(queue)) {
QueueNode current = dequeue(queue);
int currentRoom = current.vertex;
int currentDistance = current.distance;
for (int i = 0; i < graph.numEdges; i++) {
if (graph.edges[i].source == currentRoom) {
int neighbor = graph.edges[i].destination;
int weight = graph.edges[i].weight;
if (!visited[neighbor]) {
visited[neighbor] = true;
distances[neighbor] = currentDistance + weight;
enqueue(queue, neighbor, distances[neighbor]);
}
}
}
}
// Find the room with the minimum maximum distance to other rooms
int centerRoom = farthestRoom;
int minMaxDistance = INF;
for (int i = 0; i < graph.numRooms; i++) {
if (distances[i] != INF && distances[i] < minMaxDistance) {
minMaxDistance = distances[i];
centerRoom = i;
}
}
*numFriends = 0;
// Count the number of friends (rooms with non-INF distances to the center)
for (int i = 0; i < graph.numRooms; i++) {
if (distances[i] != INF && i != centerRoom) {
(*numFriends)++;
}
}
// Return the center room of Harry's friends' component
return centerRoom;
}
// Function to find the shortest path from source to destination using Dijkstra's algorithm
void dijkstraShortestPath(int source, int destination, Graph graph) {
int distances[MAX_ROOMS];
bool visited[MAX_ROOMS]; // Added
// Initialize distances and visited arrays
for (int i = 0; i < graph.numRooms; i++) {
distances[i] = INF;
visited[i] = false;
}
// Set distance of source to 0
distances[source] = 0;
// Dijkstra's algorithm
for (int count = 0; count < graph.numRooms - 1; count++) {
int minDistance = INF;
int minIndex = -1;
// Find vertex with minimum distance
for (int v = 0; v < graph.numEdges; v++) { // Iterate over the number of edges
if (!visited[v] && distances[v] <= minDistance) {
minDistance = distances[v];
minIndex = v;
}
}
// Mark the picked vertex as visited
visited[minIndex] = true;
// Update distance value of the adjacent vertices
for (int v = 0; v < graph.numEdges; v++) { // Iterate over the number of edges
if (!visited[v] && graph.edges[v].weight && distances[minIndex] != INF && distances[minIndex] + graph.edges[minIndex].weight < distances[v]) {
distances[v] = distances[minIndex] + graph.edges[minIndex].weight;
}
}
}
// Print the shortest distance from source to destination
printf("Shortest distance from %d to %d: %d\n", source, destination, distances[destination]);
}
int main() {
const char* filename = "g1-8.txt"; // Change this to the name of your map file
// Step 1: Read the map from the file and construct the graph
Graph graph = readMapFromFile(filename);
// Step 2: Identify the main source room
int mainSourceRoom = 0; // Assume the first room as the main source room
// Step 3: Find the center of Harry's friends' component
int numFriends = 0; // Number of Harry's friends
int friendsComponentCenter = bfsFindCenterOfFriendsComponent(graph, mainSourceRoom, &numFriends); // Implement this function
// Step 4: Find the shortest path from the main source to Harry's room
int harrysRoom = friendsComponentCenter; // Placeholder
dijkstraShortestPath(mainSourceRoom, harrysRoom, graph);
// Step 5: Print out the questions and their answers
printf("2.1. In which room does Harry find himself lost, in the beginning? Room %d\n", mainSourceRoom);
printf("2.2. How many friends does Harry have on this map? %d\n", numFriends);
printf("2.3. What vertex is Harry's dorm room? Room %d\n", harrysRoom);
printf("2.4. What is a path with the least energy spending to safely reach his room? [Main Source Room -> Harry's Room]\n");
printf("2.5. How much energy does the path consume (or gain)? 0 \n(Since the distance from the main source room to Harry's room is 0)\n");
return 0;
}
```
the graph i used is
0 3 0 5 0 2 0 0
0 0 -4 0 0 0 0 0
0 0 0 0 0 0 0 4
0 0 0 0 6 0 0 0
0 0 0 -3 0 0 0 8
0 0 0 0 0 0 3 0
0 0 0 0 0 -6 0 7
0 0 0 0 0 0 0 0
but there is also another graph which is
0 2 0 0 1 0 0 0 0 0 0 0 2
0 0 0 0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 3 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 -2 0 0 0 0 0 0 0 0 0 -1
0 0 0 0 0 0 0 0 -2 0 0 0 0
0 -2 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 -2 0 0 0 0 0 0 0 0
2 4 0 0 0 0 0 0 0 -1 0 0 0
0 0 0 2 0 0 0 0 0 0 0 0 0
0 0 -1 0 0 0 7 0 0 0 0 0 0
0 0 0 3 0 0 0 0 0 0 3 0 3
0 0 2 0 0 0 0 0 0 3 0 0 0
the result is:
Shortest distance from 0 to 0: 0
2.1. In which room does Harry find himself lost, in the beginning? Room 0
2.2. How many friends does Harry have on this map? 0
2.3. What vertex is Harry's dorm room? Room 0
2.4. What is a path with the least energy spending to safely reach his room? [Main Source Room -> Harry's Room]
2.5. How much energy does the path consume (or gain)? 0
(Since the distance from the main source room to Harry's room is 0)
but its not quite right so anyone capable for helping me here? |
Weighted Graphs |
|c|algorithm|weighted-graph| |
null |
You should check the execution plan for your query. You can see it by adding EXPLAIN clause at the beginning of the query text:
```sql
EXPLAIN SELECT
timestamp,
first(price) AS open,
last(price) AS close,
min(price),
max(price),
sum(amount) AS volume
FROM trades
WHERE symbol = 'BTC-USD' AND timestamp > dateadd('d', -1, now())
SAMPLE BY 15m ALIGN TO CALENDAR;
```
If you see `Async ...` nodes in the output, e.g. `Async JIT Group By` or `Async JIT Filter`, it means that the corresponding parts of the query execution plan run in parallel, i.e. on multiple threads.
Note that by default, parallel execution is disabled on machines with less than 4 cores.
Also, in many cases, if your query runs on a single thread, you can rewrite it in a parallel-friendly way. Sometimes this can be as simple as moving the aggregates and the filter from the outer query for the sub-query.
Here is a simple example:
```sql
SELECT symbol, sum(price)
FROM (
SELECT symbol, price FROM trades
UNION ALL
SELECT symbol, price FROM trades
)
WHERE symbol = 'BTC-USD';
```
This query will run single-threaded since the GROUP BY and the filter is applied to a UNION ALL sub-query. But if you rewrite it in the following way, both parts of the sub-query will be handled on multiple threads:
```sql
SELECT symbol, sum(price)
FROM (
SELECT symbol, sum(price) FROM trades
WHERE symbol = 'BTC-USD'
UNION ALL
SELECT symbol, sum(price) FROM trades
WHERE symbol = 'BTC-USD'
);
``` |
{"OriginalQuestionIds":[16097955],"Voters":[{"Id":4108803,"DisplayName":"blackgreen"}]} |
Nested columns with DataFrame in Streamlit data_editor? |
I have a laravel 10 project that used livewire 3.
When I was on development I used Google Chrome devtools.
Today I deploy it on a local server and I turn the APP_ENV variable into production.
It works fine but I can see that the livewire devtools is still running so anyone can access the components and its data.
I wrongly thought it was handled by the value of the APP_ENV variable like the debugbar package.
Do you know if there is a way to disable it?
I did some research and found a few people had this problem but they never received any answers...
I'm surprised livewire didn't think of that. |
I don't 100% understand what you are after.
``<nobr>`` can keep content together:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
p {
width: 140px;
background: #eee;
}
<!-- language: lang-html -->
<p>This is some text that includes a link
<nobr>(
<a href="https://example.com">
<svg style="height: 1em; color: green;" viewbox="0 0 10 10" fill="currentColor"><circle cx="5" cy="5" r="5" /></svg>example example example example example
</nobr>
</a>)</p>
<!-- end snippet -->
|
first question ) is ist possible to get metrics.search_rank_lost_impression_share > 0 for keywords ?
um using for campaigns
AdsApp.campaigns().withCondition("Status = ENABLED").withCondition("metrics.search_rank_lost_impression_share > 0").forDateRange("YESTERDAY").get();
second question)
how can i make a or condition between two Conditions ?
i want to get all campaigns where metrics.search_rank_lost_impression_share > 0 or metrics.search_rank_lost_absolute_top_impression_share > 0
i tried everything i |
adwords script get metrics.search_rank_lost_impression_share > 0 for keywords |
|google-ads-api| |
null |
Git requires that you have checked our a branch before it makes a marge commit, the only exception is a fast forward.
The easiest in your situation is making a new worktree from master, then inside that worktree merging the branch, before deleting the worktree
```sh
git worktree add master
cd master
git merge feature --no-ff -m "commit msg"
# Do other things
cd ..
git worktree remove master
``` |
- **azure-storage-blob**:
- **12.19.1**:
- **Windows 10**:
- **3.10.6**:
**Describe the bug**
When attempting to retrieve the list of blob names from the Azure Blob Storage container, an "Incorrect padding" error is encountered. This issue seems to be causing a hindrance in fetching the blob names effectively, even though the blob upload and download operations have been successful.
**Code Snippet:**
```python
try:
# Get the list of blobs in the container
blob_list = self.container_client.list_blobs()
print("List of blobs:")
for blob in blob_list:
print(blob.name)
except Exception as e:
print(f"An error occurred while retrieving the list of blobs: {str(e)}")
```
**Error Message:**
`Incorrect padding`
**Additional Successful Operations:**
- Blob Upload
```Python
def upload(self, blob_data, blob_name):
try:
# Upload a blob to the container
self.container_client.upload_blob(name=blob_name, data=blob_data)
print(f"Blob '{blob_name}' uploaded successfully.")
except Exception as e:
print(f"An error occurred while uploading blob '{blob_name}': {str(e)}")
```
- Blob Download
```
def download(self, blob_name):
try:
# Get the BlobClient for the blob
blob_client = self.container_client.get_blob_client(blob_name)
# Download the blob to a local file
with open(blob_name, "wb") as blob:
download_stream = blob_client.download_blob()
blob.write(download_stream.readall())
print(f"Blob '{blob_name}' downloaded successfully.")
except Exception as e:
print(f"An error occurred while downloading blob '{blob_name}': {str(e)}")
```
|
How do i fetch api data that is a link? |
|reactjs|api| |
null |
I'm developing a Fortran parser using ANTLR4, adhering to the ISO Fortran Standard 2018 specifications. While implementing lexer rules, I encountered a conflict between the `NAME` and `LETTERSPEC` rules. Specifically, when the input consists of just a letter, it is always tokenized as `NAME` and never as `LETTERSPEC`. Here's a partial simplified version of the grammer:
```
lexer grammar FortrantTestLex;
// Lexer rules
WS: [ \t\r\n]+ -> skip;
// R603 name -> letter [alphanumeric-character]...
NAME: LETTER (ALPHANUMERICCHARACTER)*;
// R865 letter-spec -> letter [- letter]
LETTERSPEC: LETTER (MINUS LETTER)?;
MINUS: '-';
// R601 alphanumeric-character -> letter | digit | underscore
ALPHANUMERICCHARACTER: LETTER | DIGIT | UNDERSCORE;
// R0002 Letter ->
// A | B | C | D | E | F | G | H | I | J | K | L | M |
// N | O | P | Q | R | S | T | U | V | W | X | Y | Z
LETTER: 'A'..'Z' | 'a'..'z';
// R0001 Digit -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
DIGIT: '0'..'9';
// R602 UNDERSCORE -> _
UNDERSCORE: '_';
```
```
grammer FortranTest;
import FortranTestLex;
// Parser rules
programName: NAME;
// R1402 program-stmt -> PROGRAM program-name
programStmt: PROGRAM programName;
letterSpecList: LETTERSPEC (COMMA LETTERSPEC)*;
// R864 implicit-spec -> declaration-type-spec ( letter-spec-list )
implicitSpec: declarationTypeSpec LPAREN letterSpecList RPAREN;
implicitSpecList: implicitSpec (COMMA implicitSpec)*;
// R863 implicit-stmt -> IMPLICIT implicit-spec-list | IMPLICIT NONE [( [implicit-name-spec-list] )]
implicitStmt:
IMPLICIT implicitSpecList
| IMPLICIT NONE ( LPAREN implicitNameSpecList? RPAREN )?;
// R1403 end-program-stmt -> END [PROGRAM [program-name]]
endProgramStmt: END (PROGRAM programName?)?;
// R1401 main-program ->
// [program-stmt] [specification-part] [execution-part]
// [internal-subprogram-part] end-program-stmt
mainProgram: programStmt? endProgramStmt;
//R502 program-unit -> main-program | external-subprogram | module | submodule | block-data
programUnit: mainProgram;
//R501 program -> program-unit [program-unit]...
program: programUnit (programUnit)*;
```
In this case, the tokenization always results in NAME even though it could also be a valid LETTERSPEC. How can I resolve this conflict in my lexer rules to ensure correct tokenization?
I've tried adjusting the order of the lexer rules and refining the patterns, but I haven't been able to achieve the desired behavior. Any insights or suggestions on how to properly handle this conflict would be greatly appreciated. Thank you! |