instruction stringlengths 0 30k ⌀ |
|---|
Reinforcement learning pygame window is not shutting down with env.close() |
|python|reinforcement-learning|openai-gym| |
null |
pygame window is not shutting down with env.close() |
Telegram is very sensitive to userbots, you should have at least more than 50 seconds delay between each request. so you don't get flood wait again. |
I struggle with Swiper.js. I want to have looping swiper with autoplay, ken burns effect (zoom in from center) and fade onto the next one. I have everything coded, but I every slide transforms on X-axis and moves to the right ending outside of webpage display area.
I already have working homepage slider with Elementor plugin, which seems to utilize outdated Swiper.js version with specific classes that make it unclear on how to add paralax, pagination, navigation etc. Moreover it doesn't work properly with mobile devices.
I tried to replicate the same effects with newer version of Swiper.js and coded everything like dynamic bullets, navigation, zoom transition etc., but for some reason only the first slide displays correctly and then every other slide moves on X-Axis about 1365px to the right.
Here is a codepen of how it looks like:
<https://codepen.io/JUDr-Martin-Kov-cs/pen/poBWXzW>
HTML
```
<!-- Custom styles for fullscreen slider -->
<style>
body, html {
position: relative;
height: 100%;
}
.swiper-container {
width: 100%;
height: 100%;
}
.swiper-slide {
background-size: cover;
background-position: center;
display: flex;
justify-content: center;
align-items: center;
color: #fcfcfc;
font-size: 24px;
animation: zoom;
animation-duration: 20s;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
.swiper-android .swiper-slide,
.swiper-ios .swiper-slide,
.swiper-wrapper {
transform: translate3d(0, 0, 0);
}
@keyframes zoom {
from {
transform: scale(1);
}
to {
transform: scale(1.3);
}
}
</style>
</head>
<body>
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
<div class="swiper-slide" style="background-image: url('');"></div>
</div>
<!-- Add pagination -->
<div class="swiper-pagination"></div>
<!-- Add navigation arrows -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
</body>
</html>
```
JS
```
document.addEventListener('DOMContentLoaded', function () {
var mySwiper = new Swiper('.swiper-container', {
// Optional parameters
direction: 'horizontal', // or 'vertical'
loop: true, // Enable loop mode
// If we need pagination
pagination: {
el: '.swiper-pagination', // Specify the pagination container
clickable: true, // Allow clickable pagination bullets
dynamicBullets: true,
},
// Navigation arrows
navigation: {
nextEl: '.swiper-button-next', // Specify the next button selector
prevEl: '.swiper-button-prev', // Specify the previous button selector
},
// Autoplay
autoplay: {
delay: 5000, // Delay between transitions in milliseconds
disableOnInteraction: false, // Disable autoplay when user interacts with swiper
},
// Fade effect
speed: 2000,
effect: 'fade', // Specify the transition effect
fadeEffect: {
crossFade: true
}
});
});
```
I have no idea what causes the issue. I tried to replicade it on my codepen and it is doing exactly the same thing as on my webpage.
I tried to set these parameters, but they didn't help:
```
.swiper-slide {
background-size: cover;
background-position: center;
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
```
Any ideas how to solve this?
Thank you |
Swiper.js moves slides outside of viewport/page |
|plugins|slider|swiper.js| |
null |
grep -o 'CN=[^,]*' data | sed 's/^CN=//' |
I am making auto white balance calibration application.
I have a chromameter and api. So my application can measure CIExyY and CIEXYZ.
And my app can set R,G,B output value of my devices's LED panel.
I set R,G,B value combination and measureed CIEXYZ three times.
And then I evaluated follow matrix.
[matrix][1]
I thought that once I evaluated the matrix, I could calculate CIEXYZ with R,G,B output value.
But It's not correct value.
R,G,B output value is 0~1023. 0 doesn't mean 0 output. 0~1023 is just level.
[1]: https://i.stack.imgur.com/mhy6w.png |
Trying to parse C# isn't for the faint-hearted. Luckily, there's already a compiler you can use from a [NuGet package][1] :-) So, I had a go at using [Roslyn][2] for the first time, and it's fairly easy to accomplish what you want:
```
Install-Package Microsoft.CodeAnalysis.CSharp
```
Then, you can parse the C# code and analyze methods using `CSharpSyntaxWalker` (I found an example [here][3]):
```csharp
var code = File.ReadAllText(filePath);
var tree = CSharpSyntaxTree.ParseText(code);
var root = tree.GetRoot();
var walker = new MethodWalker();
walker.Visit(root);
class MethodWalker : CSharpSyntaxWalker
{
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
{
var lineSpan = node.GetLocation().GetLineSpan();
var start = lineSpan.StartLinePosition.Line;
var end = lineSpan.EndLinePosition.Line;
var count = end - start + 1; // including declaration
Console.WriteLine($"Method found: {node.Identifier.ValueText}, number of lines: {count}");
base.VisitMethodDeclaration(node);
}
}
```
Also [this post][4] gives a few more examples of walking the syntax tree, as well as creating an analyser.
I think the right approach, as already mentioned in the question comments, is by writing your own analyzer. However, you should also be able to use it within unit tests.
[1]: https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/
[2]: https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/
[3]: https://joshvarty.com/2014/07/26/learn-roslyn-now-part-4-csharpsyntaxwalker/
[4]: https://medium.com/pvs-studio/creating-roslyn-api-based-static-analyzer-for-c-c0d7c27489f9 |
Telegram is very sensitive to userbots, you should have at least more than 20, 30 seconds delay between each request. so you don't get flood wait again. |
I noticed that with this code:
```
public List<foo> FooList = new() { foo1, foo2, foo3 };
private List<foo> _fooList = new() { foo1, foo2, foo3 };
```
when the app runs, FooList has all three objects but _fooList has three nulls [null, null, null].
Why is this initialization occurring like this?


I tried to use a debugger. |
|dynamic-programming| |
You can just observe the button's `configuration.isPressed` like @lorem said:
```swift
extension ButtonStyle where Self == AdditionalActionButtonStyle {
static func printWhenTapped(_ message: String) -> Self {
return Self(message: message)
}
}
struct AdditionalActionButtonStyle: ButtonStyle {
private var message: String
init(message: String) {
self.message = message
}
public func makeBody(configuration: Configuration) -> some View {
configuration.label.onChange(of: configuration.isPressed) { _, newValue in
if newValuw {
print(self.message)
}
}
}
}
```
Then you can use it like this:
```swift
Button("Tap me") {
print("tapped")
}
.buttonStyle(.printWhenTapped("tapped again"))
```
---
If you want to use it as a view modifier, you can wrap it:
```swift
extension View {
public func printWhenTapped(_ message: String) -> some View {
modifier(AdditionalActionButtonStyleViewModifier(message: message))
}
}
struct AdditionalActionButtonStyleViewModifier: ViewModifier {
private var message: String?
init(message: String) {
self.message = message
}
func body(content: Content) -> some View {
content.buttonStyle(.printWhenTapped(self.message))
}
}
```
So you can use it like this:
```swift
Button("Tap me") {
print("tapped")
}
.printWhenTapped("tapped again")
``` |
`mix-blend-mode: difference` will change white on white to black and white on black will be white.
However, the two elements have to be at the same level so z-index and transforms are removed in this snippet. The transform property is replaced by margin-top and -left (thanks to this [https://stackoverflow.com/questions/39369298/does-css-mix-blend-mode-work-with-transform][1])
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.addEventListener('DOMContentLoaded', () => {
const interBubble = document.getElementById('circle');
let curX = 0;
let curY = 0;
let tgX = 0;
let tgY = 0;
function move() {
curX += (tgX - curX) / 10;
curY += (tgY - curY) / 10;
//interBubble.style.transform = `translate(${Math.round(curX)}px, ${Math.round(curY)}px)`;
interBubble.style.marginTop = `${Math.round(curY)}px`;
interBubble.style.marginLeft = `${Math.round(curX)}px`;
requestAnimationFrame(() => {
move();
});
}
window.addEventListener('mousemove', (e) => {
tgX = e.clientX;
tgY = e.clientY;
if (e.target.tagName === 'P' ||
e.target.tagName === 'A' ||
e.target.tagName === 'BUTTON' ||
e.target.parentNode.tagName === 'BUTTON') {
interBubble.classList.add('big');
} else {
interBubble.classList.remove('big');
}
});
move();
});
<!-- language: lang-css -->
body {
background-color: black;
overflow: hidden;
}
div {
position: relative;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
p {
color: white;
font-size: 30px;
}
:root {
--trans-bounce: cubic-bezier(.4, 2.2, .6, 1.0);
--trans-time: .4s;
}
.mouseFollowCircle {
width: 30px;
height: 30px;
border-radius: 999px;
position: absolute;
top: -15px;
left: -15px;
box-shadow: 0 0 10px white;
background-color: white;
pointer-events: none;
/*backdrop-filter: blur(2px);*/
transition: width var(--trans-time) var(--trans-bounce), height var(--trans-time) var(--trans-bounce), top var(--trans-time) var(--trans-bounce), left var(--trans-time) var(--trans-bounce), background-color var(--trans-time) var(--trans-bounce);
}
.mouseFollowCircle.big {
width: 70px;
height: 70px;
border-radius: 999px;
position: absolute;
top: -35px;
left: -35px;
box-shadow: 0 0 10px white;
background-color: white;
pointer-events: none;
/*backdrop-filter: blur(2px);*/
transition: width var(--trans-time) var(--trans-bounce), height var(--trans-time) var(--trans-bounce), top var(--trans-time) var(--trans-bounce), left var(--trans-time) var(--trans-bounce), background-color var(--trans-time) var(--trans-bounce);
mix-blend-mode: difference;
}
<!-- language: lang-html -->
<div>
<p>Hello World</p>
</div>
<section class="mouseFollowCircle" id="circle"></section>
<!-- end snippet -->
Note I commented out the filter as I wasn't sure you wanted blurry text.
UPDate: the original question had a black background for which this answer works. The question has changed to have a gradient background for which this answer doesn’t work as the white circle picks up color.
[1]: https://stackoverflow.com/questions/39369298/does-css-mix-blend-mode-work-with-transform |
I am attempting to dynamically update filters in my shiny app. For example, if one selects `California` as a state then the only cities that populate in the City filter should be cities from California.
However, if I select `California`, the code shows all the cities in the dataframe regardless if they are in California or not.
I have tried various attempts but am unsure of how to update the filtered data without creating a continuous loop or selecting a filter and it resetting itself. The original data has roughly twelve columns I am looking to filter.
```lang-r
library(shiny)
library(data.table)
library(DT)
ui <-
fluidPage(
# Application title
titlePanel("Display CSV Data"),
# Sidebar layout with input and output definitions
sidebarLayout(
# Sidebar panel for inputs
sidebarPanel(
# No input needed if the CSV is static
# Use selectizeInput for filtering
uiOutput("filter_ui")
),
# Main panel for displaying output
mainPanel(
# Output: DataTable
dataTableOutput("table")
)
)
)
server <-
function(input, output, session) {
# Read the CSV file into a data table and display as a DataTable
cols_to_filter <- c('state', 'city', 'county')
data <- reactive({
tibble(
state = c("California", "California", "California", "New York", "New York", "Texas", "Texas", "Texas"),
city = c("Los Angeles", "San Francisco", "Claremont", "New York", "Buffalo", "Houston", "Austin", "San Marcos"),
county = c("Los Angeles", "San Francisco", "Los Angeles", "New York", "Erie", "Harris", "Travis", "Hays"),
population = c(3979576, 883305, 36161, 8336817, 256902, 2325502, 964254, 65053) # Fictional population figures
)
})
observe({
setkeyv(data(), cols_to_filter)
})
# Generate selectizeInput for filtering
output$filter_ui <- renderUI({
filter_inputs <- lapply(cols_to_filter, function(col) {
selectizeInput(
inputId = paste0("filter_", col),
label = col,
choices = c("", sort(unique(data()[[col]]))),
multiple = TRUE,
options = list(
placeholder = 'Select values'
)
)
})
do.call(tagList, filter_inputs)
})
# Filter the data table based on user selections
filtered_data <- reactive({
filtered <- data()
for (col in cols_to_filter) {
filter_values <- input[[paste0("filter_", col)]]
if (length(filter_values) > 0) {
filtered <- filtered[get(col) %in% filter_values]
}
}
filtered
})
# Display the filtered data table
output$table <- renderDataTable({
filtered_data()
})
}
shinyApp(ui = ui, server = server)
``` |
Dynamically update filters in Shiny |
|shiny| |
I encountered a roadblock while editing GLSL code for an image filtering app I'm developing.
The code runs without any errors, but there seems to be an issue with the image rendering process.
Instead of displaying the image, only a solid color screen is being output.
Here's my painter code:
```
class ImageShaderPainter extends CustomPainter {
final ui.Image? image;
final ui.FragmentProgram? fragmentProgram;
final double brightness;
final double temperature;
final double saturation;
ImageShaderPainter({
this.image,
this.fragmentProgram,
required this.brightness,
required this.temperature,
required this.saturation,
});
@override
void paint(Canvas canvas, Size size) {
if (image != null && fragmentProgram != null) {
final ui.FragmentShader shader = fragmentProgram!.fragmentShader();
shader.setFloat(0, brightness);
shader.setFloat(1, temperature);
shader.setFloat(2, saturation);
shader.setImageSampler(0, image!);
// Pass the image size to the shader
shader.setFloat(3, image!.width.toDouble());
shader.setFloat(4, image!.height.toDouble());
final paint = Paint()..shader = shader;
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}
}
// The rest of my code...
}
```
And here's my code from the .frag file:
```
#version 460 core
#include <flutter/runtime_effect.glsl>
// Uniforms
uniform float uBrightness;
uniform float uTemperature;
uniform float uSaturation;
uniform sampler2D uTexture;
uniform vec2 uCanvasSize;
// Output
out vec4 fragColor;
void main() {
vec2 uv = FlutterFragCoord().xy / uCanvasSize;
vec4 color = texture(uTexture, uv);
// Adjust brightness
color.rgb += vec3(uBrightness);
// Adjust temperature
vec3 temperatureAdjust = vec3(0.0);
temperatureAdjust.r = uTemperature > 0.0 ? uTemperature : 0.0;
temperatureAdjust.b = uTemperature < 0.0 ? abs(uTemperature) : 0.0;
color.rgb += temperatureAdjust;
// Adjust saturation
vec3 grey = vec3(dot(color.rgb, vec3(0.299, 0.587, 0.114)));
color.rgb = mix(grey, color.rgb, uSaturation + 1.0);
fragColor = color;
}
```
If anyone is well-versed in GLSL and Flutter fragment shaders, I would greatly appreciate your assistance. |
Aren't you meant to be passing a **blob-URL** for the image instead of just blob-plain?
Because it doesn't look like you're converting the blob to a URL with this...
canvas.toBlob(function (blob){
jQuery.ajax({
url:"//domain.com/wp-admin/admin-ajax.php",
type: "POST",
data: {action: "addblobtodb", image: blob},
success: function(id) {console.log("Succesfully inserted into DB: " + id);
}
});
So I would try this...
canvas.toBlob((blob)=>{
let Url=URL.createObjectURL(blob);
jQuery.ajax({
url:"//domain.com/wp-admin/admin-ajax.php",
type: "POST",
data: {action: "addblobtodb", image: Url}, // <-- Image blob url passed here
success: function(id) {console.log("Succesfully inserted into DB: " + id);}
});
},'image/png',1); // <--- specify the type & quality of image here
I hope it helps...
|
This is my ``Magento_Checkout/web/template/summary/cart-items.html``
```
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div class="block items-in-cart" data-bind="mageInit: {'collapsible':{'collapsible': true, 'openedState': 'active', 'active': isItemsBlockExpanded() }}">
<div class="title" data-role="title">
<strong role="heading" aria-level="1">
<translate args="maxCartItemsToDisplay" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate>
<translate args="'of'" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate>
<translate args="'Cart'" if="getCartSummaryItemsCount() === 1"></translate>
<translate args="'Cart'" if="getCartSummaryItemsCount() > 1"></translate>
(<span data-bind="text: getCartSummaryItemsCount().toLocaleString(window.LOCALE)"></span>
<span data-bind="i18n: 'items'"></span>)
</strong>
</div>
<div class="content minicart-items" data-role="content">
<div class="minicart-items-wrapper">
<ol class="minicart-items">
<each args="items()">
<li class="product-item">
<div class="product">
<each args="$parent.elems()" render=""></each>
</div>
</li>
</each>
</ol>
</div>
</div>
<div class="actions-toolbar" if="maxCartItemsToDisplay < getCartLineItemsCount()">
<div class="secondary">
<a class="action viewcart" data-bind="attr: {href: cartUrl}">
<span data-bind="i18n: 'View and Edit Cart'"></span>
</a>
</div>
</div>
</div>
```
Here, the checkout accordion is handled.
I want this accordion to be initially open at the first step (shipping step), and closed at the second step (payment step)
obviously, in both steps, I want there to be the possibility to open/close the accordion.
I created my own mixin, ``Magento_Checkout/web/js/view/summary/cart-items-mixin.js``
```
define(['Magento_Checkout/js/model/step-navigator'], function (stepNavigator) {
'use strict';
var mixin = {
isShippingState: function () {
return !stepNavigator.isProcessed('shipping');
},
isItemsBlockExpanded: function () {
return !stepNavigator.isProcessed('shipping');
}
};
return function (target) {
return target.extend(mixin);
};
});
```
in this way, it does not seem to achieve the desired effect.
I tried using the ``subscribe()``function of ``stepNavigator``
but I couldn't solve it.
it is as if the accordion maintains the same state in both steps.
Because if I open it in the first step, it will also be open in the second, and vice versa.
So, to recap, the result I want to get is:
- in the first step the accordion must initially be open (and interactable)
- in the second step tha accordion must be initially closed (and interactable)
PS: obviously, I've registered the mixin in a ``requirejs-config.js`` file as shown below:
```
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
var config = {
'config': {
'mixins': {
'Magento_Checkout/js/view/summary/cart-items': {
'Magento_Checkout/js/view/summary/cart-items-mixin': true
}
}
}
};
```
So, the mixin is correctly registered!
Do you guys have got any ideas to solve this? |
Before you set the path of jre check it's content, in my case the jre folder is empty, but there was a jbr folder.
If you are on a bash terminal, it might take a while to sync with your environmental variables you could easily set it on that terminal
export JAVA_HOME='C:\Program Files\Android\Android Studio\jbr'
or
export JAVA_HOME='C:\Program Files\Android\Android Studio\jre' |
def function1(ss:pd.Series):
date4curr=df1.loc[ss.max(),'date']
dd1=df1.loc[ss].loc[df1.date!=date4curr]
df1.loc[ss.max(),'fraud_count']=dd1.fraud.sum()
fraud_sum=dd1.loc[dd1.fraud.eq(1)].amount.sum()
df1.loc[ss.max(),'fraud_sum']=fraud_sum
return 1
df1.assign(col1=df1.index).groupby(['customer_id']).apply(lambda dd:dd.col1.expanding().apply(function1))
df1
:
date customer_id transaction_id amount fraud fraud_count fraud_sum
2020-01-01 1 10 25 0 0 0
2020-01-01 2 11 14 1 0 0
2020-01-02 1 12 48 1 0 0
2020-01-02 2 13 12 1 1 14
2020-01-02 2 14 41 1 1 14
2020-01-03 1 15 30 0 1 48
2020-01-03 2 16 88 0 3 67 |
I'm making an Aqua button (from Mac OS X) and one of the many things I have to fix is pulse.
However, I found a quarter-working fix which "technically" pulses, but that doesn't fix a new problem of making the entire background pulse instead of the background size. What it does is just move the color of choice (more specifically the `background`) of the `@keyframe` up and down. So what I want is the entire background of the button to pulse instead of `background-size`.
Here's the CSS code:
```css
@keyframes color {
from {
background-size:50% 50%;
}
to {
background-size:100% 100%;
}
}
:root {
--confirm: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207));
--cancel: linear-gradient(#AAAAAA,#FFFFFF);
--altconfirm: linear-gradient(rgb(0, 100, 240),rgb(200, 200, 210))
}
button {
-webkit-appearance: none;
-moz-appearance: none;
border: 1px solid #ccc;
border-radius: 125px;
box-shadow: inset 0 13px 25px rgba(255,255,255,0.5), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.1);
cursor: pointer;
font-family: 'Lucida Sans Unicode', Helvetica, Arial, sans-serif;
font-size: 1.5rem;
margin: 1rem 1rem;
padding: .8rem 2rem;
position: relative;
transition: all ease .3s;
}
button:hover {
box-shadow: inset 0 13px 25px rgba(255,255,255,.7), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.2);
transform: scale(1.001);
}
button::before {
background: linear-gradient(rgba(255,255,255,.8) 7%, rgba(255,255,255,0) 50%);
border-radius: 125px;
content:'';
height: 97.5%;
left: 5%;
position: absolute;
top: 1px;
transition: all ease .3s;
width: 90%;
}
button:active{
box-shadow: inset 0 13px 25px rgba(255, 255, 255, 0.2), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.2);
transform: scale(1);
}
button::before:active{
box-shadow: inset 0 13px 25px rgba(255, 255, 255, 0.01), 0 3px 5px rgba(0,0,0,0.418), 0 10px 13px rgba(0, 0, 0, 0.418);
transform: scale(1);
}
button.confirm {
background: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207));
animation-name: color;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-timing-function: ease;
}
button.cancel {
background: var(--cancel);
border: 1.7px solid #AAA;
color: #000;
}
```
And the HTML code:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./Test.css">
</head>
<body>
<button class="confirm" style="background-color: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207))">Push Button</button><br>
<button class="cancel">Push Button</button><br>
<p>EEE</p>
</body>
</html>
``` |
AWS Dns record A not navigate to elb |
|amazon-web-services|dns|amazon-route53| |
I have an api endpoint stored in an String url = "API_endpoint". I want to upload an image through my app to that API endpoint using Volley or Retrofit library. I need to give the ("Authorisation",token) as header and the photo will be send in the form data ("file",image). Can anyone help me out to do so.
I am trying to upload an image to the server using my API endpoint but I tried almost everything but I was not able to do so. |
I am working on an Android app and want to upload image to the server so can anyone give me the Java code in Android Studio to do so |
|java|android|android-volley| |
null |
I'm using **Auto** mode in Blazor Web App. I tried to use Authentication and authorization in the server project. But I cannot use authorization in the client project. I want to add `<AuthorizeView>` tag in some components exist in the client project. I cannot add related namespace to the `_imports.razor` in the client project. How can I use `<AuthorizeView>`tag in the client project? |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LogisticRegression()
model.fit(X_train, y_train)
22 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
23 model = LogisticRegression()
\---\> 24 model.fit(X_train, y_train)
27 app = Flask(__name__)
29 @app.route('/')
30 def home():
After encode the non-numerical value into one-hot encoding, i noticed that the model fit function cannot be executed. Is there problem with my code? |
Why this model fit function has value error? I have no idea how to solve it |
|jupyter-notebook| |
null |
I'm using google analytics 4 in my test website made with WordPress. I have successfully configured Google Tag and connect GA4 with my website.
I have a situation where i have an event tag sent to GA4 account but i cant see anything neither in real-time reports nor in my debug view. Other event such as page_view and User engagement appear like normal.
These are the events:
[![enter image description here][1]][1]
And they are fired successfully as you can see:
[![enter image description here][4]][4]
[![enter image description here][5]][5]
The measurement ID is correct and the connection is valid and there is no internal filter set.
Any ideas?
[1]: https://i.stack.imgur.com/RgMIj.png
[2]: https://i.stack.imgur.com/ebeVP.png
[3]: https://i.stack.imgur.com/LzASY.png
[4]: https://i.stack.imgur.com/EgMzg.png
[5]: https://i.stack.imgur.com/TKuxm.png |
Given a
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<div
lang="en"
style="
overflow-wrap: word-break;
hyphens: auto;
width: 8.6em;
background-color: highlight;
color: highlightText;
font-size: 20px;
">
This is a text that is long enough
to cause a line break if set so.
By using words like
"incomprehensibilities",
we can demonstrate word breaks.
</div>
<!-- end snippet -->
I would like to access the formatted text with hyphenations with JavaScript to get a string similar to:
`"This is a text that is long enough to cause a line break if set so. By using words like "incomprehensibilit-ies", we can demon-strate word breaks."`.
N.B. hyphens in `incomprehensibilit-ies` and `demon-strate`.
Is this possible?
The use case is that I need a way to break and hyphenate text in a `<text>` element of an SVG by only using SVG elements.
|
[](https://i.stack.imgur.com/WSrCO.png)
`program.cs`:
```
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Default");
// Add services to the container.
builder.Services.AddDbContext<GerenciadorContext>(opts =>
{
opts.UseMySql(connectionString,ServerVersion.AutoDetect(connectionString));
});
builder.Services.AddIdentity<IdentityUser,IdentityRole>()
.AddEntityFrameworkStores<GerenciadorContext>();
builder.Services.AddTransient<IUserDao, UserDao>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
```
As soon as I make a request it returns this error, I don't know if it's something in .NET 8 |
I'm trying to create a user with identity in .NET 8 with Entity Framework and I'm getting the following error, both in MySQL and SQL Server |
|c#|entity-framework|.net-8.0| |
App is crashing in sometime unable to find the root cause.
Java.Lang.IllegalArgumentException
Java.Lang.IllegalArgumentException: Cannot setMaxLifecycle for Fragment not attached to FragmentManager FragmentManager{f4b285a in null}}
Provide the resolution of this exception, current using .NET MAUI 0.7 version android. |
App is crashing and getting Java.Lang.IllegalArgumentException: Cannot setMaxLifecycle for Fragment not attached to FragmentManager |
|.net|xamarin|xamarin.forms|xamarin.android|maui| |
null |
If I understand correctly, you want to be able to drag the blue button along the arc of the progress bar and the progress should be filled with color to correspond to the button position.
I don't quite understand why it would make sense to be able to adjust the progress manually like this, but anyway, if this is the right understanding then the following changes can be used to get it working:
- Use the limits consistently. The function `updateProgress` was using min/max limits of -110 degrees to +110 degrees, but then it was capping the result at 88.8 degrees for some reason. Also, the progress arc was being drawn from 0.3 to 0.9, which would represent an angle of 216 degrees. I've stuck with -110 degrees to +110 degrees (= 220 degrees total) and adapted the other limits accordingly.
- If the blue button is positioned at 12 o' clock when the angle is 0, then the computed progress angle can simply be applied as a rotation effect, instead of adjusting x and y offsets. To position the button at 12 o' clock, all it takes is a negative y-offset equal to the radius.
- Likewise, it is much simpler if the progress bar starts at 0 and then a rotation effect is used to change the start position to -110 degrees, instead of trimming from 0.3 to 0.9 and applying a rotation effect of 54.5 degrees (which should have actually been 54 degrees).
- I would suggest using `Double` for `progressValue` as it simplifies some of the computation.
- The function `angle` needs to take the size of the button into consideration.
- To make the animation more responsive to small drag movements, supply a `minimumDistance` to the `DragGesture`, for example, `minimumDistance: 1`.
- The progress bar does not need to be passed a binding to the progress level, because it is read-only. It can be a `let` property instead.
- The button does not need to be passed the progress level at all.
- Large movements can be smoothed by adding an `.animation` modifier to the `ZStack`.
Here you go, hope it helps:
```swift
struct SemiCircularProgressBar: View {
@State private var progressValue: Double = 0.0
@State private var degrees: Double = -110
var body: some View {
VStack {
ZStack {
ProgressBar(progress: progressValue) // self.$progressValue
.frame(width: 250.0, height: 250.0)
.padding(40.0)
ProgressThumb() // self.$progressValue
.frame(width: 30, height: 30)
.offset(y: -125) // circle radius
.rotationEffect(.degrees(degrees))
// .offset(x: self.thumbOffset().x, y: self.thumbOffset().y)
// .rotationEffect(.degrees(54.5))
.gesture(
DragGesture(minimumDistance: 1)
.onChanged { gesture in
// let angle = self.angle(for: gesture.location)
let angle = location2Degrees(location: gesture.location)
updateProgress(for: angle)
}
)
}
.animation(.easeInOut(duration: 0.15), value: degrees)
Spacer()
}
}
// private func angle(for location: CGPoint) -> Double {
// let vector = CGVector(dx: location.x, dy: location.y)
// let angle = atan2(vector.dy, vector.dx)
// return Double(angle * 180 / .pi)
// }
private func location2Degrees(location: CGPoint) -> Double {
let halfButtonSize = 30.0 / 2
let radians = atan2(location.x - halfButtonSize, halfButtonSize - location.y)
let degrees = radians * 180 / .pi
return degrees < -180
? degrees + 360
: degrees > 180 ? degrees - 360 : degrees
}
private func updateProgress(for angle: Double) {
let totalAngle: Double = 220
let minAngle: Double = -110
let maxAngle: Double = minAngle + totalAngle
let normalizedAngle = min(max(minAngle, angle), maxAngle)
// if normalizedAngle > 88.8 {
// normalizedAngle = 88.8
// }
self.progressValue = (normalizedAngle - minAngle) / totalAngle
self.degrees = normalizedAngle
}
// private func thumbOffset() -> CGPoint {
// let thumbRadius: CGFloat = 125 // half of progress bar diameter
// let radians = CGFloat(degrees) * .pi / -100
// let x = thumbRadius * cos(radians)
// let y = thumbRadius * sin(radians)
// return CGPoint(x: x, y: y)
// }
}
struct ProgressBar: View {
let progress: Double // @Binding var progress: Float
var body: some View {
ZStack {
Circle()
.trim(from: 0, to: 220.0 / 360) // (from: 0.3, to: 0.9)
.stroke(style: StrokeStyle(lineWidth: 12.0, lineCap: .round, lineJoin: .round))
.opacity(0.3)
.foregroundColor(Color.gray)
.rotationEffect(.degrees(-90 - 110)) // .degrees(54.5)
Circle()
.trim(from: 0, to: (progress * 220.0) / 360) // (from: 0.3, to: CGFloat(self.progress))
.stroke(style: StrokeStyle(lineWidth: 12.0, lineCap: .round, lineJoin: .round))
.fill(AngularGradient(gradient: Gradient(stops: [
.init(color: Color(hex: "ED4D4D"), location: 0), // 0.39000002
.init(color: Color(hex: "E59148"), location: 65.0 / 260), // 0.48000002
.init(color: Color(hex: "EFBF39"), location: 110.0 / 360), // 0.5999999
.init(color: Color(hex: "EEED56"), location: 175.0 / 360), // 0.7199998
.init(color: Color(hex: "32E1A0"), location: 220.0 / 360), // 0.8099997
.init(color: Color(hex: "ED4D4D"), location: 1)
]),center: .center))
.rotationEffect(.degrees(-90 - 110)) // .degrees(54.5)
VStack {
Text("824").font(Font.system(size: 44)).bold().foregroundColor(Color(hex: "314058"))
Text("Great Score!").bold().foregroundColor(Color(hex: "32E1A0"))
}
}
}
}
struct ProgressThumb: View {
var body: some View {
Circle()
.fill(Color.blue)
.frame(width: 30, height: 30)
}
}
```
 |
CSS "position: fixed" respects parent's margin property and moves. Why? |
As it stands, I have a game I writing, utilizing PCG (Procedural Content Generation). I was wondering if there was a better way to store the vertices of my polygon with certain library restrictions (Box2D is my chosen physics engine). Currently, I have this:
```
std::vector<b2Vec2> topChain;
std::vector<b2Vec2> bottomChain;
std::vector<b2Vec2> eastCap;
std::vector<b2Vec2> westCap;
```
Box2D has a limitation ( as far as I'm aware ) that polygon fixtures can contain at most 8 vertices. Given I have sloping terrain, 8 vertices isn't enough for the smooth terrain I'm looking for. The solution was to slice each sloping section into a quad.
However, my concern here is efficiency, and one thing I noticed is the time and memory it requires to fill these vectors.
Hovering over each class name in Visual Studio, shows that b2Vec2 is a whopping 8 bytes per.
The container class of std::vector takes another 32 bytes.
What would be the most efficient data structure for this problem? |
Force Magento 2's checkout accordion to be open on first step, closed on second step |
|javascript|knockout.js|magento2| |
I made a page with a websocket using Flask-socketio worked on joining and disconnecting rooms, and one of the important ones is the chat. it works, but not as it should, messages are shown only after the page is refreshed, although they should appear as they arrive
here is an excerpt of the code that is responsible for this processing
```
@app.route("/room/<nameRoom>", methods=['GET', 'POST'])
@login_required
def join_room(nameRoom): # room page
session["room"] = nameRoom
if nameRoom in rooms:
url = rooms[nameRoom]['url']
return render_template('roomyutube.html', id=get_video_id(url), messages=rooms[nameRoom]["messages"])
else:
error = 'not_room'
return render_template('error.html', error=error)
@socketio.on("connect")
def connect(auth):
room = session.get("room")
name = User.query.filter_by(id=current_user.get_id()).first().username
if not room or not name:
return 404
if room not in rooms:
leave_room(room)
return
join_room(room)
send({"name": name, "message": "has entered the room"}, to=room)
rooms[room]['members'].append(User.query.filter_by(id=current_user.get_id()).first().username)
print(rooms[room])
print(f"{name} joined room {room}")
@socketio.on("disconnect")
def disconnect():
room = session.get("room")
name = User.query.filter_by(id=current_user.get_id()).first().username
leave_room(room)
if room in rooms:
rooms[room]['members'].remove(name)
if len(rooms[room]["members"]) <= 0:
del rooms[room]
send({"name": name, "message": "has left the room"}, to=room)
print(rooms[room])
print(f"{name} has left the room {room}")
@socketio.on("message")
def message(data):
room = session.get("room")
name = User.query.filter_by(id=current_user.get_id()).first().username
if room not in rooms:
return
content = {
"name": name,
"message": data["data"]
}
send(content, to=room)
rooms[room]["messages"].append(content)
print(f"{name} said: {data['data']}")
if __name__ == '__main__':
socketio.run(app, debug=True, allow_unsafe_werkzeug=True)
```
The code of the page with js
```
<body>
<div id="video-container">
<iframe width="800" height="450"
src="https://www.youtube.com/embed/{{ id }}" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
</div>
<div class="chat-input" id="messages"></div>
<input id="message" name="message" type="text" placeholder="Введите сообщение" class="text-light"/>
<button type="button" name="send" id="send-btn" onClick="sendMessage()">
--->
</button>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"
integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA=="
crossorigin="anonymous"
></script>
<script type="text/javascript">
var socketio = io();
const messages = document.getElementById("messages");
const createMessage = (name, msg) => {
const content = `
<div class="text">
<span>
<strong>${name}</strong>: ${msg}
</span>
</div>
`;
messages.innerHTML += content;
};
socketio.on("message", (data) => {
createMessage(data.name, data.message);
});
const sendMessage = () => {
const message = document.getElementById("message");
if (message.value == "") return;
socketio.emit("message", { data: message.value });
message.value = "";
};
</script>
{% for msg in messages %}
<script type="text/javascript">
createMessage("{{msg.name}}", "{{msg.message}}");
</script>
{% endfor %}
</body>
```
|
Issue with Loading Images in Flutter FragmentShader and GLSL Code |
|flutter|dart|glsl| |
null |
Here is a working example of what I think you are asking for.
https://jsfiddle.net/m2w6egn9/
<div id="demo">
<div v-show="active">Show</div>
<div @mouseover="mouseOver">Hover over me!</div>
</div>
var demo = new Vue({
el: '#demo',
data: {
active: false
},
methods: {
mouseOver: function(){
this.active = !this.active;
}
}
}); |
A preload script has to be attached to a window to be accessible:
```js
new BrowserWindow({
...
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
```
Additionaly, if you want to use the same preload for both window, it means you need to move your window creation code on the main process, outside of the preload file, because you can't link a file if you're within it. It simply means adding an extra IPC handler, as per [the official example in the docs][1]:
**renderer**
```js
window.myWindowAPI?.createWindow();
```
**electron-preload.ts**
```js
contextBridge.exposeInMainWorld('myWindowAPI', {
createWindow: () => ipcRenderer.send('create-window'),
...
}
```
**electron-main.ts**
```js
const createWindow = () => {
...
};
ipcMain.on('create-window', createWindow);
```
[1]: https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-1-renderer-to-main-one-way |
I was running this code to show a dataframe[df.show()]:
```python
from pyspark.sql import *
spark=SparkSession.builder\
.appName("Hello Spark")\
.master("local[2]")\
.getOrCreate()
def spark_practice():
date_list = [("Ravi",28),
("David",45),
("Mani",27)]
df=spark.createDataFrame(date_list).toDF("Name","Age")
df.printSchema()
df.show()
spark_practice()
```
However, I got the following error:
>File "C:\Program Files\Hadoop\spark-3.5.1\python\lib\py4j-0.10.9.7-src.zip\py4j\protocol.py", line 326, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o46.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0) (Prince-PC executor driver): org.apache.spark.SparkException: Python worker exited unexpectedly (crashed)
I have tried to set the path variable `PYSPARK_DRIVER_PYTHON` to the latest version of Python, which is same as the one used in project, but it did not help. |
Error from PySpark code to showdataFrame : py4j.protocol.Py4JJavaError |
`var testInodes []Inode` had to be in the form `var testInodes [120]Inode` as my global variable Inode array that was initially encoded is initialized to 120 |
In EF terms it seems like it could just be:
var d = db.Users
.OrderByDescending(u => u.Xp)
.AsEnumerable()
.Select((u, i) => new { Rank=i+1, User = u })
.ToDictionary(at => at.Rank, at=>at.User);
You list all your users out of the DB in order of XP, and you use the overload of `Select((user,index)=>...)` to assign the rank (the index + 1) and for convenience let's put them in a dictionary indexed by rank
Now you have a dictionary you can keep and repeatedly look up in where, for any given user, you can get the surrounding users by the rank of the user you already know:
var user = d.Values.FirstOrDefault(u => u.Name == "user6");
var prev = d[user.Rank - 1];
var next = d[user.Rank + 1];
You need some code to prevent a KeyNotFoundException if you find the top or bottom ranked user because if you find the user with Rank 1 by name, you cannot retrieve the user with Rank 0 (they don't exist). You didn't say what to do in this situation in your original post, you can use ContainsKey to test if the dictionary contains a particular rank, or you can use GetValueOrDefault, or TryGetValue to attempt to get a user - these methods don't crash if the user isn't found but you will need to decide what to do if they aren't |
Why is the chat message not showing immediately |
|flask-socketio| |
null |
please enter this command with SSH;
docker exec -it greenlight-v3 bundle exec rake admin:create['Your Name','email@example.com','!Example11Password']
|
I found the reason behind this issue. When I checked the **AWS console**. It was showing the cpu usage graph getting the peek value after each 3 hrs. then I checked my crons and found that there was a cron to upload the videos to youtube. Cron used to create multiple process for each video upload to avoid script timeout situation. Now in that script I have to fetch the video from my another server. The main reason was this. the streamname I was providing to the fetch the video from another server resulted in continues waiting state. Due to that the php-fpm also starts waiting for that script to exit. Hence unresolved state occurred every 3 hrs.
So If you guys are getting the same error as shown in above screenshot then check your time when your cpu system is getting peek value and try to figure out what's running at that time. There must be something in your php script which is responsible for the php-fpm to wait endlessly.
if php-fpm started then it should stop if it is not then try to improve your code.
I think you have got the main idea. Try to find if you found something the same as in my case and get your server running smoothly. I also have summarized the entire situation in detail with possible reasons and with respective solutions on my blog. Check it out here. [Too many process created by PHP-FPM][1]
cheers :)
[1]: https://orgfoc.com/php-fpm-with-nginx-config-too-many-process/ |
Aren't you meant to be passing a **blob-URL** for the image instead of just blob-data?
Because it doesn't look like you're converting the blob to a URL with this...
canvas.toBlob(function (blob){
jQuery.ajax({
url:"//domain.com/wp-admin/admin-ajax.php",
type: "POST",
data: {action: "addblobtodb", image: blob},
success: function(id) {console.log("Succesfully inserted into DB: " + id);
}
});
So I would try this...
canvas.toBlob((blob)=>{
let Url=URL.createObjectURL(blob);
jQuery.ajax({
url:"//domain.com/wp-admin/admin-ajax.php",
type: "POST",
data: {action: "addblobtodb", image: Url}, // <-- Image blob url passed here
success: function(id) {console.log("Succesfully inserted into DB: " + id);}
});
},'image/png',1); // <--- specify the type & quality of image here
I hope it helps...
|
I get an ogg-encoded audio stream received chunk by chunk via `tornado.websocket.WebSocketHandler`. My task is to decode it on-the-fly into PCM samples to feed into another algorithm. So the ideal decoding API for me would be something like:
```python
class Decoder():
def push_encoded(self, chunk: bytes):
# TODO: Implement this.
def pop_decoded(self) -> PCMSamples:
# TODO: Implement this.
```
In other words I need a decoder that internally holds two buffers: the first is to accumulate non yet decoded bytes, the second for already decoded samples.
Alternatively it might be a callback-driven API like:
```python
class Decoder(callback: Callable[[PCMSamples], None]):
def push_encoded(self, chunk: bytes):
# TODO: Implement this.
```
I tried to use `torchaudio.io.StreamReader` to implement the API above since I already use this package, but as it turns out it's not that obvious to achieve.
Is there an easy way to implement one of the APIs above using `torchaudio` or there're other packages more suitable for the task? |
Take a close look at the URL, which is the result from `getResource`
(URL is already the first warning sign). It starts like a regular
`file://` URL but then has a `!...` in it - this the JVM telling you,
that the file you want is inside this archive.
`FileInputStream` only really can load files from the file-system, hence
the error. At best `FileInputStream` could read the `.jar`-file for
you.
So you need a way read the content of your file from "the class-path"
and the shortest route is to request an `InputStream` from the
class-loader and pass that to load your properties:
```groovy
Properties appProps = new Properties().tap{
load(
Thread.currentThread().contextClassLoader.getResourceAsStream("conf/Config.properties")
)
}
```
|
Basically, the answer is essentially **"1 background color + `n` specified background images"**.
[The specification is:][1]
>Each box has a background layer that may be fully transparent (the default), or filled with a color and/or one or more images. The background properties specify what color (background-color) and images (background-image) to use, and how they are sized, positioned, tiled, etc.
>
>The background properties are not inherited, but the parent box’s background will shine through by default because of the initial transparent value on background-color.
>
>The background of a box can have multiple background image layers. The number of layers is determined by the number of comma-separated values in the background-image property. Note that a value of none still creates a layer.
An "additional" layer is available if `border-image` is used
>NOTE: The border-image properties can also define a background image, which, if present, is **painted on top of the background layers** created by the background properties.
[1]: https://drafts.csswg.org/css-backgrounds/#backgrounds |
This solution work as well
```ts
type Merge<T extends object[]> = T extends [infer First, ...infer Rest]
? First extends object
? Rest extends object[]
? Omit<First, keyof Merge<Rest>> & Merge<Rest>
: never
: never
: object
export const merge = <T extends object[]>(...objects: T): Merge<T> => Object.assign({}, ...objects)
``` |
Vue SFC aren't spec-compliant, their support depends on a tool. The use of TypeScript in <template> is more exotic and can cause problems.
It makes sense to write all scripts in `<script>` section, this makes a template more readable and allows for proper typing:
@change="onChange"
Otherwise this is avoided by using local `$event` value:
@change="crewEntryUpdated($event, props)" |
**Explanation**
I have Visual Studio v17.9.5. When I publish an existing project or create a new one and publish it, it shows me only the http:5000 port.
It does not run neither on cloud.
**Question**
Why is the https port disabled on publish? How can it be enabled?
The output I get when I run the app, after publish:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
|
Navigate from app.js, that is outside of the BrowserRouter wrapping |
|reactjs|firebase-authentication|react-router-dom| |
null |
The `nextTick` or microtask will be queued from somewhere, which will be one of the phases of the event-loop. So their callback will be called right after this *somewhere*, in the same phase.
Remember that `nextTick` isn't one of the phases, to quote [the docs][1]:
> This is because `process.nextTick()` is not technically part of the event loop. Instead, the `nextTickQueue` will be processed after the current operation is completed, regardless of the current phase of the event loop. Here, an *operation* is defined as a transition from the underlying C/C++ handler, and handling the JavaScript that needs to be executed.
[1]: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick#understanding-processnexttick |
I have MySQL table similar to below table
| id | Source | Destination |
| -- | ------ | ----------- |
| 1 | BLR | ATH |
| 2 | ATH | BLR |
| 3 | BLR | HKG |
| 4 | HKG | BLR |
| 5 | DEL | ATH |
| 6 | ATH | DEL |
| 7 | DEL | HKG |
| 8 | HKG | DEL |
| 9 | BLR | DEL |
| 10 | DEL | BLR |
| 11 | BLR | ATH |
| 12 | ATH | BLR |
| 13 | DEL | ATH |
| 14 | ATH | DEL |
I want to generate the combination of source and destination based on unique city, along with count like
| CITY | ATH | BLR | DEL | HKG |
| ---- | --- | --- | --- | --- |
| ATH | 0 | 2 | 2 | 0 |
| BLR | 2 | 0 | 1 | 1 |
| DEL | 2 | 1 | 0 | 1 |
| HKT | 0 | 1 | 1 | 0 |
It is possible to generate the complete table using SQL query ?
Thanks.
I'm not sure how this combination is called in SQL. All the searches returned table to generate unique combination of source/destination but not a table like this. Not sure what this kind of table where row title and column title are same, is called. |
SQL: Generate combination table based on source and destination column from same table |
|sql|mysql| |
null |
So I want to create a website on Flask where users can create a route. I have no problem creating a route with just Folium, but I need to use nodes from the map so I decided to use OSMnx. However, when I use OSMnx, the website only displays the map without the route.
So here is my code:
```
from flask import render_template
import folium
import osmnx as ox
import networkx as nx
@views.route('/', methods=['GET', 'POST'])
def test():
mapObj = folium.Map(location=[40.748441, -73.985664], zoom_start=15, width=1850, height=900)
ox.config(log_console=True, use_cache=True)
G_walk = ox.graph_from_place('Manhattan Island, New York City, New York, USA',
network_type='walk')
orig_node = ox.nearest_nodes(G_walk, Y=40.748441, X=-73.985664)
dest_node = ox.nearest_nodes(G_walk, Y=40.748441, X=-73.3)
route = nx.shortest_path(G_walk,
orig_node,
dest_node,
weight='length')
route = ox.plot_route_folium(G_walk, route, width=1850, height=910).add_to(mapObj)
mapObj.get_root().render()
header = mapObj.get_root().header.render()
body_html = mapObj.get_root().html.render()
script = mapObj.get_root().script.render()
return render_template('home.html', user=current_user,
header=header, body_html=body_html, script=script)
```
I also tried to render the "route", but then map wasn't displayed either. |
What would be the most efficient way to store multiple sets of fixed arrays (std::vector)? |
|c++|data-structures|time|processing-efficiency|space-efficiency| |
null |
I've just installed Wordpress 6.4.3 & MAMP and managed to edit functions.php and saved my changes.
When I tried to make more changes to the file, Wordpress started displaying the following error message:
> Something went wrong. Your change may not have been saved. Please try again. There is also a chance that you may need to manually fix and upload the file over FTP.
When I try to edit my website pages, I started getting the following error message now:
> Updating failed. The response is not a valid JSON response.
This is what I've added to functions.php successfully and cannot edit it anymore
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = sanitize_text_field($_POST["name"]);
$email = sanitize_email($_POST["email"]);
$message = sanitize_textarea_field($_POST["description"]);
// Add code to save the form data to the database
global $wpdb;
$table_name = $wpdb->prefix . 'request_form';
$data = array(
'name' => $name,
'email' => $email,
'description' => $message,
'submission_time' => current_time('mysql')
);
$insert_result = $wpdb->insert($table_name, $data);
if ($insert_result === false) {
$response = array(
'success' => false,
'message' => 'Error saving the form data.',
);
} else {
$response = array(
'success' => true,
'message' => 'Form data saved successfully.'
);
}
// Return the JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
What I have done:
- I've checked permissions of the file and gave read and write access to everyone on my localhost.
- Restarted the server
- When I changed http to https for wordpress Address (URL) and Site Address (URL) under Settings > General and saved the changes, I was redirected to the following address http://localhost:8888/wp-admin/options.php and can see the following:
<br />
<b>Notice</b>: Undefined index: name in
<b>/Applications/MAMP/htdocs/wp-
content/themes/twentytwentyfour/functions.php</b> on line
<b>209</b><br />
<br />
<b>Notice</b>: Undefined index: email in
<b>/Applications/MAMP/htdocs/wp-
content/themes/twentytwentyfour/functions.php</b> on line
<b>210</b><br />
<br />
<b>Notice</b>: Undefined index: description in
<b>/Applications/MAMP/htdocs/wp-
content/themes/twentytwentyfour/functions.php</b> on line
<b>211</b><br />
<div id="error"><p class="wpdberror"><strong>WordPress database
error:</strong> [Unknown column 'submission_time' in
'field list']<br /><code>INSERT INTO `wp_request_form`
(`name`, `email`, `description`, `submission_time`) VALUES
('', '', '', '2024-03-30
07:10:51')</code></p></div>{"success":false,"message":"Error
saving the form data."}
|
Upd1. Answer contains errors and will be updated. Thank's for @gordy.
See example. Recursive assembling expression formula from expression_tree table.
```
with -- recursive -- for PostgreSql
cte as(
select expression_id,oid
,concat(
case when lv in('*','+','-','/') then concat('{',lid,'}')
else cast(lv as varchar) end
,ov
,case when rv in('*','+','-','/') then concat('{',rid,'}')
else cast(rv as varchar) end
)frm
,case when lv in('*','+','-','/') then lid else 0 end lid
,case when rv in('*','+','-','/') then rid else 0 end rid
from(
select o.expression_id,o.node_id oId,o.value oV,o.side oSide
,l.node_id lId,l.value lV,l.side lSide
,r.node_id rId,r.value rV,r.side rSide
from expression_tree O
inner join expression_tree L on l.expression_id=o.expression_id
and l.parent_node_id=o.node_id and l.side='L'
inner join expression_tree R on r.expression_id=o.expression_id
and r.parent_node_id=o.node_id and r.side='R'
)t
)
,r as(
select 0 lvl, expression_id,0 xeid,oid,cast(frm as varchar)frm,lid,rid
from cte
where lid>0 or rid>0
union all
select lvl+1,r.expression_id,t1.expression_id,r.oid
,cast(
case when t1.oid=r.lid then replace(r.frm,concat('{',t1.oid,'}'),concat('(',t1.frm,')'))
when t1.oid=r.rid then replace(r.frm,concat('{',t1.oid,'}'),concat('(',t1.frm,')'))
else r.frm
end as varchar)frm
,case when t1.oid=r.lid then t1.lid else r.lid end lid
,case when t1.oid=r.rid then t1.rid else r.rid end rid
from r
inner join cte t1 on t1.expression_id=r.expression_id
and ((t1.oid=r.lid) or (t1.oid=r.rid))
)
select *
from (select *,row_number()over(partition by expression_id order by lvl desc) rn
from r)x
where rn=1
order by expression_id,lvl;
```
For test I take 3 expressions:
1. 7-(2*3)
2. 9-(3*(4+5))
3. (13+14)*(15+16)
Query from 3 parts:
1.Take all three-nodes.
```
<Left(l)-parent(o)-right(r)>
```
Parent is operation ('+','-','*')
If child node (l and/or r) is value (not operation '*','+','-') we taken ``value`` and node_id -> lid=0 or rid=0.
If child node is operation, we take link to ``node_id`` as '{id}' and lid=id or rid=id.
There oid - center id from triple(lid-oid-rid). We take ``value``.
CTE (cte) result is
|expression_id|oid|frm|lid|rid|
|-:|-:|:-----|-:|-:|
|1| 1| 7-{3}| 0| 3|
|1| 3| 2*3 | 0| 0|
|2| 1| 9-{3}| 0| 3|
|2| 3| 3*{5}| 0| 5|
|2| 5| 4+5 | 0| 0|
|3| 1|{2}*{3}| 2| 3|
|3| 2| 13+14| 0| 0|
|3| 3| 15+16| 0| 0|
2. Recursive assembling the formula (CTE r).
Assembling process shown in table.
There frm - expression formula.
We will explicitly denote the order of execution with parentheses so that we do not have to take into account the priorities of arithmetic operations.
|lvl|expression_id|oid|frm|lid|rid| rn|
|-:|-:|-:|:------------|-:|-:|-:|-:|
|0| 1| 1| 7-{3} there{3}=(2*3)|0| 3| 2|
|1| 1| 1| 7-(2*3) |0| 0| 1|
|0| 2| 1| 9-{3} there {3}=3*{5}|0| 3| 4|
|0| 2| 3| 3*{5} there {5}=(4+5)|0| 5| 5|
|1| 2| 3| 3*(4+5) |0| 0| 2|
|1| 2| 1| 9-(3*{5}) |0| 5| 3|
|2| 2| 1| 9-(3*(4+5))|0| 0| 1|
|0| 3| 1| {2}*{3} |2| 3| 5|
|1| 3| 1| (13+14)*{3}|0| 3| 3|
|1| 3| 1| {2}*(15+16)|2| 0| 4|
|2| 3| 1| (13+14)*(15+16)|0| 0| 1|
|2| 3| 1| (13+14)*(15+16)|0| 0| 2|
For example ``(13+14)*(15+16)``
```
1.1 {2}*{3} where {2}=(13+14) and {3}=(15+16)
```
Next step generate 2 rows.
You say ``My difficulty in the above is basically that I need both node child node values at the same time otherwise, it will keep overwriting the L child when it gets the R child. How could that be fixed?``.
We can take any option. We take all rows.
```
2.1 (13+14)*{3}
2.2 {2}*(15+16)
```
Next step generate also 2 rows from 2 rows of previous level. And can take any of them.
```
3.1 (13+14)*(15+16)
3.2 (13+14)*(15+16)
```
We take all rows.
3. Take result row - any of rows with max level of recursion (row_number()...).
Test expressions
1. 7-(2*3)
2. 9-(3*(4+5))
3. (13+14)*(15+16)
as expression_tree:
```
CREATE TABLE expression_tree (expression_id INT, node_id INT, value VARCHAR(3)
, side VARCHAR(1), parent_node_id INT);
INSERT INTO expression_tree VALUES
(1, 1, '-', NULL, NULL), -- "-" at top
(1, 2, '7', 'L', 1),
(1, 3, '*', 'R', 1),
(1, 4, '2', 'L', 3),
(1, 5, '3', 'R', 3),
(2, 1, '-', NULL, null), -- "-" at top
(2, 2, '9', 'L', 1),
(2, 3, '*', 'R', 1),
(2, 4, '3', 'L', 3),
(2, 5, '+', 'R', 3),
(2, 6, '4', 'L', 5),
(2, 7, '5', 'R', 5),
(3, 1, '*', NULL, null), -- "-" at top
(3, 2, '+', 'L', 1),
(3, 3, '+', 'R', 1),
(3, 4, '13', 'L', 2),
(3, 5, '14', 'R', 2),
(3, 6, '15', 'L', 3),
(3, 7, '16', 'R', 3);
```
Tested for SQL Server and PostgreSQL
[Demo](https://dbfiddle.uk/QgYU3Wb8) |
I run my training on HPC. I set up python virtual environment for this. However, python virtual environment get deleted very often and I have to set it up again. I would appreciate if you would help to cure this. Setting up my python virtual environment takes quite some time as I have to reinstall many packages and ... |
Why https is disabled on publish in .NET Core 7.0 |
|asp.net-core|.net-7.0| |
I have Cloudflare SSL secured Domain. My Angular 14 Frontend is deployed on DigitalOcean Droplet A. I am able to open my website homepage with https://my-domain. I have a number of SpringBoot Microservices deployed on DigitalOcean Droplet B. Please note that all my microservices are deployed with the help of Docker containers. I have Eureka Discovery Service and API Gateway also deployed on droplet B. I am able to access all the services from Postman as http reqeusts which means all my services including my API Gateway, Eureka Discovery Service is working fine. The issue is when I am sending the same requests from my domain, I am getting failed request. I am sure it is because my frontend which is SSL secured is sending http request to backend. I am using Load Balancing in my Gateway. My Gateway is accessible on droplet via droplet-ip:8082 port. This is the first time I am implementing website with SSL and https. How can I resolve this issue? My website was working fine before I implemented SSL.
I am totally new to this type of implementation. I am really not sure where to start exploring this issue as answers on several forums, although talk about similar issue, don't really help solve this kind of issue. |
HTTP Requests from SSL Secured(HTTPS) Domain Failing |
|spring-boot|docker|ssl|https|microservices| |
null |
Please consider the following case that would result in memory getting written after being deallocated.
The reason being that in `class PoorlyOrderedMembers` the member `m_pData` is declared after the member `m_nc` which means that the `std::unique_ptr` d'tor will be called and the instance of `ClassWithData` will be deleted just before the d'tor of `class NaughtyClass` will write to it.
While _writing_ it, you could probably get hints for a problem if you try to put both member initializations in the initializer list and get an error or a warning. Alternatively, you could change `NaughtyClass` and `PoorlyOrderedMembers` to use `std::shared_ptr` but, these are only obvious after you know that there's a problem here.
What would be the tell that something is wrong here when reviewing the code after the mistake was already made?
```c++
#include <cstring>
#include <memory>
class ClassWithData
{
char m_carray[32]{};
public:
char* data() { return m_carray; }
static constexpr size_t capacity() { return sizeof(m_carray); }
};
class NaughtyClass
{
ClassWithData* m_p = nullptr;
public:
~NaughtyClass()
{
char const m[] = "d'tor called";
memcpy(m_p->data(), m, sizeof m);
static_assert(sizeof(m) <= ClassWithData::capacity(), "the string doesn't fit in the capacity");
}
void set(ClassWithData* p) { m_p = p; }
};
class PoorlyOrderedMembers
{
NaughtyClass m_nc;
std::unique_ptr<ClassWithData> m_pData;
public:
PoorlyOrderedMembers() :
m_pData(std::make_unique<ClassWithData>())
{
m_nc.set(m_pData.get());
}
};
int main()
{
PoorlyOrderedMembers poom;
return 0;
}
```
|
I'm facing an issue with an ASP.NET 8 Web API.
While running the project in the console with `dotnet run`, it is not running completely or showing any error either. The console screen is as follows:
[![Console Log][1]][1]
[1]: https://i.stack.imgur.com/K3TzF.png
But the application is running in debug mode from the Visual Studio 2022 without any issue.
Here's my `program.cs`:
```
using Institutor.Data;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
System.Environment.SetEnvironmentVariable("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", "0");
// Create a WebApplication builder with the arguments passed to the program
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Add the DbContext and configure it to use SQLite with the connection string from the configuration
builder.Services.AddDbContext<InstitutorDataContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Identity services to the DI container and configure it to use the DbContext for storage
builder.Services.AddIdentity<IdentityUser, IdentityRole>() // Add IdentityRole here
.AddEntityFrameworkStores<InstitutorDataContext>()
.AddDefaultTokenProviders(); // Add this to add the default token providers
// Add JWT authentication services to the DI container and configure it
builder.Services.AddAuthentication(x=>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
options.IncludeErrorDetails = true
;
});
// Add controllers to the DI container
builder.Services.AddControllers();
// Add API explorer services to the DI container
builder.Services.AddEndpointsApiExplorer();
//Adding Azure Services logging
builder.Services.AddLogging(builder =>
{
builder.AddAzureWebAppDiagnostics();
});
// Add Swagger services to the DI container and configure it
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "Institutor API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Just paste the token (No need to add Bearer)",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
// Build the application
var app = builder.Build();
// Configure the HTTP request pipeline.
// Use Swagger in development environment
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Use HTTPS redirection middleware
app.UseHttpsRedirection();
// Use authentication middleware
app.UseAuthentication();
// Use authorization middleware
app.UseAuthorization();
// Map controller routes
app.MapControllers();
// Run the application
app.Run();
```
Here's the `.csproj` file for project:
```
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="8.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.4.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Data\Data.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup>
</Project>
```
Please let me know if any more details required in this regards. |
So I am basically very new to Assembly in general. I was trying to write this simple code where I need to sort numbers in an ascending order from source data and rewrite it into destination data.
and whenever I run it, it shows: executables selected for download on to the following processors doesn't exist...
here is the code, maybe something wrong with it:
.global main
main:
ldr r0, =src_data // load the input data into r0
ldr r1, =dst_data // load the output data into r1
mov r2, #32 // word is 32
first_loop:
ldr r3, =Input_data // load the input data into r3
ldr r4, [r3], #4 // load the 1st elem of input data into r4
mov r5, r0 // move to the second loop
second_loop:
ldr r6, [r1] // load the value of output data into r6
cmp r4, r6 // compare the current element eith the value in output data
ble skip_swap // if the current element is less than or equal, continue
// swap the elements:
str r6, [r1]
str r4, [r1, #4]
skip_swap:
// move to the next elem in output data
add r1, r1, #4
// decrement by one remaining elements (r2 was 32)
subs r2, r2, #1
// check if we have reached the end of input_data
cmp r3, r0
// if not, continue to the second loop
bne second_loop
// if the first loop counter is not zero, continue to the first loop
subs r2, r2, #1
bne first_loop
// exit
mov r7, #0x1
svc 0 // software interrupt
.data
.align 4
src_data: .word 2, 0, -7, -1, 3, 8, -4, 10
.word -9, -16, 15, 13, 1, 4, -3, 14
.word -8, -10, -15, 6, -13, -5, 9, 12
.word -11, -14, -6, 11, 5, 7, -2, -12
// should list the sorted integers of all 32 input data
// like if saying: .space 32
dst_data: .word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
well, basically registers were all blank in Vitis IDE, even though I think it is supposed to be working.. |
ARM Assembly code is not executing in Vitis IDE |
|sorting|assembly|x86|arm|armv7| |
null |