instruction stringlengths 0 30k β |
|---|
I think a good and simple solution is to use an adorner to render the masking symbols as an overlay of the original input.
Show the adorner to render the masking characters while hiding the password by setting the foreground brush to the background brush.
The following example shows how to use an `Adorner` to decorate the `TextBox`.
I have removed some code to reduce the complexity (the original library code also contained validation of input characters and password length, event logic, routed commands, `SecureString` support, low-level caret positioning to support any font family for those cases where the font is not a monospace font and password characters and masking characters won't align correctly etc. and a much more complex default `ControlTemplate`). The current version therefore only supports monospace fonts. The supported fonts have to be registered in the constructor. You could implement monospace font detection instead.
However, it's a fully working example (happy easter!).
**UnsecurePasswodBox.cs**
```c#
public class UnsecurePasswodBox : TextBox
{
public bool IsShowPasswordEnabled
{
get => (bool)GetValue(IsShowPasswordEnabledProperty);
set => SetValue(IsShowPasswordEnabledProperty, value);
}
public static readonly DependencyProperty IsShowPasswordEnabledProperty = DependencyProperty.Register(
"IsShowPasswordEnabled",
typeof(bool),
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(default(bool), OnIsShowPasswordEnabledChaged));
public char CharacterMaskSymbol
{
get => (char)GetValue(CharacterMaskSymbolProperty);
set => SetValue(CharacterMaskSymbolProperty, value);
}
public static readonly DependencyProperty CharacterMaskSymbolProperty = DependencyProperty.Register(
"CharacterMaskSymbol",
typeof(char),
typeof(UnsecurePasswodBox),
new PropertyMetadata('β', OnCharacterMaskSymbolChanged));
private FrameworkElement? part_ContentHost;
private AdornerLayer? adornerLayer;
private UnsecurePasswordBoxAdorner? maskingAdorner;
private Brush foregroundInternal;
private bool isChangeInternal;
private readonly HashSet<string> supportedMonospaceFontFamilies;
private FontFamily fallbackFont;
static UnsecurePasswodBox()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(typeof(UnsecurePasswodBox)));
TextProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(OnTextChanged));
ForegroundProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceForeground));
FontFamilyProperty.OverrideMetadata(
typeof(UnsecurePasswodBox),
new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceFontFamily));
}
public UnsecurePasswodBox()
{
this.Loaded += OnLoaded;
// Only use a monospaced font
this.supportedMonospaceFontFamilies = new HashSet<string>()
{
"Consolas",
"Courier New",
"Lucida Console",
"Cascadia Mono",
"Global Monospace",
"Cascadia Code",
};
this.fallbackFont = new FontFamily("Consolas");
this.FontFamily = fallbackFont;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.Loaded -= OnLoaded;
FrameworkElement adornerDecoratorChild = this.part_ContentHost ?? this;
this.adornerLayer = AdornerLayer.GetAdornerLayer(adornerDecoratorChild);
if (this.adornerLayer is not null)
{
Rect contentBounds = LayoutInformation.GetLayoutSlot(adornerDecoratorChild);
this.maskingAdorner = new UnsecurePasswordBoxAdorner(adornerDecoratorChild, this)
{
Foreground = Brushes.Black
};
HandleInputMask();
}
}
private static void OnIsShowPasswordEnabledChaged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var unsecurePasswordBox = (UnsecurePasswodBox)d;
unsecurePasswordBox.HandleInputMask();
Keyboard.Focus(unsecurePasswordBox);
}
private static void OnCharacterMaskSymbolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((UnsecurePasswodBox)d).RefreshMask();
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((UnsecurePasswodBox)d).RefreshMask();
private static object OnCoerceForeground(DependencyObject d, object baseValue)
{
var unsecurePasswordBox = (UnsecurePasswodBox)d;
// Reject external font color change while in masking mode
// as this would reveal the password.
// But store new value and make it available when exiting masking mode.
if (!unsecurePasswordBox.isChangeInternal && !unsecurePasswordBox.IsShowPasswordEnabled)
{
unsecurePasswordBox.foregroundInternal = baseValue as Brush;
}
return unsecurePasswordBox.isChangeInternal
? baseValue
: unsecurePasswordBox.IsShowPasswordEnabled
? baseValue
: unsecurePasswordBox.Foreground;
}
private static object OnCoerceFontFamily(DependencyObject d, object baseValue)
{
var unsecurePasswordBox = (UnsecurePasswodBox)d;
var desiredFontFamily = baseValue as FontFamily;
return desiredFontFamily is not null
&& unsecurePasswordBox.supportedMonospaceFontFamilies.Contains(desiredFontFamily.Source)
? baseValue
: unsecurePasswordBox.FontFamily;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.part_ContentHost = GetTemplateChild("PART_ContentHost") as FrameworkElement;
}
private void HandleInputMask()
{
this.isChangeInternal = true;
if (this.IsShowPasswordEnabled)
{
this.adornerLayer?.Remove(this.maskingAdorner);
SetCurrentValue(ForegroundProperty, this.foregroundInternal);
}
else
{
this.foregroundInternal = this.Foreground;
SetCurrentValue(ForegroundProperty, this.Background);
this.adornerLayer?.Add(this.maskingAdorner);
}
this.isChangeInternal = false;
}
private void RefreshMask()
{
if (!this.IsShowPasswordEnabled)
{
this.maskingAdorner?.Update();
}
}
private class UnsecurePasswordBoxAdorner : Adorner
{
public Brush Foreground { get; set; }
private readonly UnsecurePasswodBox unsecurePasswodBox;
private const int DefaultTextPadding = 2;
public UnsecurePasswordBoxAdorner(UIElement adornedElement, UnsecurePasswodBox unsecurePasswodBox) : base(adornedElement)
{
this.IsHitTestVisible = false;
this.unsecurePasswodBox = unsecurePasswodBox;
}
public void Update()
=> InvalidateVisual();
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
var typeface = new Typeface(
this.unsecurePasswodBox.FontFamily,
this.unsecurePasswodBox.FontStyle,
this.unsecurePasswodBox.FontWeight,
this.unsecurePasswodBox.FontStretch,
this.unsecurePasswodBox.fallbackFont);
double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
ReadOnlySpan<char> maskedInput = MaskInput(this.unsecurePasswodBox.Text);
var maskedText = new FormattedText(
maskedInput.ToString(),
CultureInfo.CurrentCulture,
this.unsecurePasswodBox.FlowDirection,
typeface,
this.unsecurePasswodBox.FontSize,
this. Foreground,
pixelsPerDip)
{
MaxTextWidth = ((FrameworkElement)this.AdornedElement).ActualWidth + UnsecurePasswordBoxAdorner.DefaultSystemTextPadding;
Trimming = TextTrimming.None;
};
var textOrigin = new Point(0, 0);
textOrigin.Offset(this.unsecurePasswodBox.Padding.Left + UnsecurePasswordBoxAdorner.DefaultSystemTextPadding, 0);
drawingContext.DrawText(maskedText, textOrigin);
}
private ReadOnlySpan<char> MaskInput(ReadOnlySpan<char> input)
{
if (input.Length == 0)
{
return input;
}
char[] textMask = new char[input.Length];
Array.Fill(textMask, this.unsecurePasswodBox.CharacterMaskSymbol);
return new ReadOnlySpan<char>(textMask);
}
}
}
```
**Generic.xaml**
```xaml
<Style TargetType="local:UnsecurePasswodBox">
<Setter Property="BorderBrush"
Value="{x:Static SystemColors.ActiveBorderBrush}" />
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="Background"
Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:UnsecurePasswodBox">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<AdornerDecorator Grid.Column="0">
<ScrollViewer x:Name="PART_ContentHost" />
</AdornerDecorator>
<ToggleButton Grid.Column="1"
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsShowPasswordEnabled}"
Background="Transparent"
VerticalContentAlignment="Center"
Padding="4,0">
<ToggleButton.Content>
<TextBlock Text=""
FontFamily="Segoe MDL2 Assets" />
</ToggleButton.Content>
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<ContentPresenter Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
``` |
The best way to test more complex AWS lambda functions where development time and local infrastructure is the key. Is usage of their official [AWS Lambda docker image][1].
Simple Dockerfile example from documentation:
```
FROM public.ecr.aws/lambda/python:3.8
# Copy function code
COPY app.py ${LAMBDA_TASK_ROOT}
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "app.handler" ]
```
[1]: https://hub.docker.com/r/amazon/aws-lambda-python |
I have a Discord bot and I want it to delete a "Loading..." message. However it just deletes the user message for the command
```
@client.command()
async def run(ctx):
await ctx.send("Loading...")
await ctx.message.delete()
await ctx.send("Loading Complete!")
```
This raises insufficient permissions as it is trying to delete the user message instead of the message it just sent.
What am I doing wrong here? |
How to make a bot delete a message sent from itself |
|python|discord.py|nextcord| |
null |
Just set the major unit to 1 so the axis counts 1 - 8 by 1s.
Add to the x-axis setting
```
chart.set_x_axis({'name': 'X Axis'})
```
```
chart.set_x_axis({
'name': 'X Axis',
'major_unit': 1, # set major unit to 1
})
```
[![Chart with major unit set to 1][1]][1]
<br>
You could also add a label to the Trend Line like;
```
# Add line series to the chart
chart.add_series({
'categories': '=Sheet1!$C$1:$C$2', # Adjusted for new data range
'values': '=Sheet1!$D$1:$D$2', # Adjusted for new data range
'line': {'type': 'linear'}, # Adding linear trendline
'data_labels': {'value': False, # Add Data Label
'position': 'below',
'category': True,
}
})
```
All this is doing is labeling your trend line, with the lower label sitting on the X-Axis.<br>
You'll notice the value is set at start and end points but I don't think there is any means to remove the top textbox using Xlsxwriter. It can be removed manually however simply by clicking the textbox twice and then use the delete key.<br>
And for that matter you could manually move the bottom textbox to align with the other numbers too if you like
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/cZLFl.png
[2]: https://i.stack.imgur.com/wvyu6.png |
When I debug locally and run `GetEntityReport` with no results, I get a http 404, which is great. When I post this to the remote server the logs report 404, but 403 seems to be returned...which is not great.
Here is my controller, I only included the function that is causing an issue:
namespace ReportServices.Controllers
{
private readonly IReportServiceRepo _repository;
private readonly IMapper _mapper;
private readonly ILogger<ReportServicesController> _logger;
public ReportServicesController(IReportServiceRepo repository, IMapper mapper, ILogger<ReportServicesController> logger)
{
_repository = repository;
_mapper = mapper;
}
// GET api/reportservice/entities/{id}/2022/11/test
[AllowAnonymous]
[HttpGet]
[Route("entities/{entityId:int}/{year:int:maxlength(4)}/{month:int:maxlength(2)}/{title}", Name = "GetEntityReport")]
[ProducesResponseType(typeof(IList<ReportReadSimpleDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<IList<ReportReadSimpleDto>> GetEntityReport(int entityId, int year, int month, string title)
{
var reportsItem = _repository.SearchForReport(entityId, year, month, title);
if (reportsItem != null && reportsItem.Count > 0)
{
return Ok(_mapper.Map<IEnumerable<ReportReadSimpleDto>>(reportsItem));
}
return NotFound("No report found for this criteria.");
}
}
Log stuff:
Request starting HTTP/1.1 GET
https://www.skagitcounty.net/Apps/REST/ReportService/api/reportservice/entities/1/2021/1/test
Request finished HTTP/1.1 GET
https://www.skagitcounty.net/Apps/REST/ReportService/api/reportservice/entities/1/2021/1/test - - - 404 - text/plain;+charset=utf-8 38.6428ms
This is a screenshot of Swagger query (https://i.stack.imgur.com/4v3xX.png)
The hosting bundle is installed on the remote server and is .NET 8. Could that be causing this? Maybe an IIS setting?
Any ideas?
Thank you in advance!
If I use a query that has a resulting object, the result is perfect (200 OK). Weird. |
C# ASP.NET Core Web API incorrectly returning 403 on remote server |
To expand on Guru's answer, When you specify `AsNoTracking()` EF populates entities based on only what comes back from the database, it will not go to the tracking cache to fill in references, and the returned entities will not work with lazy loading which would otherwise fill in non-included references if you have lazy loading enabled.
In the case where you want to load *all* entity1's then using `AsNoTrackingWithIdentityResolution` should be enough. However, if you put any kind of filter on which Entity1's you load initially then you should eager load those as well, as per cleftharis's comment, but also use `AsNoTrackingWithIdentityResolution` to ensure that the Entity2.Entity1 referencing back to the initial one you load point to the same reference:
var entities = Context.Entity1s
.Where(x => /* some condition */)
.Include(x => x.Entity2)
.ThenInclude(x => x.Entity1s)
.AsNoTrackingWithIdentityResolution();
The reason is that otherwise `AsNoTrackingWithIdentityResolution` will only populate the Entity1 references in the Entity2s based on which Entity1s were loaded. So if an entity2 had a reference to an entity 1 that wasn't returned in the root query's conditions, it won't be populated in the results.
Alternatively, If you instead use:
var entities = Context.Entity1s // with, or without a Where condition...
.Include(x => x.Entity2)
.ThenInclude(x => x.Entity1s)
.AsNoTracking();
... then the results will appear to work, but a big problem is that:
var first = entities.First();
var childsParent = first.Entity2.Entity1s.Single(x => x.Id == first.Id);
bool sameReference = object.ReferenceEquals(first, childsParent);
"sameReference" in this case would be `false`. While they contain the same row they would be different, separate instances of an entity class. Ensuring the references to the same row use the same instance is the primary purpose for using `AsNoTrackingWithIdentityResolution`.
|
node:9720) [DEP0170] DeprecationWarning: The URL http://proxy.example.com:port is invalid. Future versions of Node.js will throw an error.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:5040) [DEP0170] DeprecationWarning: The URL http://proxy.example.com:port is invalid. Future versions of Node.js will throw an error.
(Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! code ERR_INVALID_URL
npm ERR! Invalid URL
expectiing get solution as possible |
NPM packages installation error ...... its not only about vite its same problem during installing any packages |
|javascript|reactjs|node.js| |
null |
I'm practicing using React queries.
In this code, I expected to invalidate only the ['test'] query key.
However, the ['todos'] query is invalidated and the data is received again from the server.
Applying useQuery options does not change the results.
I would appreciate some help as to what the problem is.
```
const { data: todos } = useQuery({
queryKey: ["todos"],
queryFn: () => getTodos(),
});
const { mutate: handleAddTodo } = useMutation({
mutationFn: addTodo,
onSuccess: () => {
queryClient.invalidateQueries(["test"]);
},
});
```
- Applying useQuery options,
- Applying default options
```
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
```
but result is not defferent
===========================
```
App.js
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: 10000,
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
<Todos />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}
export default App;
//Todos.js
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { useState } from "react";
const getTodos = async (filter) => {
const { data } = await axios.get(
`http://localhost:3000/todos${filter ? `?type=${filter}` : ""}`
);
return data;
};
const addTodo = async ({ newTodo, newType }) => {
console.log(newTodo, newType);
await axios.post("http://localhost:3000/todos", {
text: newTodo,
type: newType,
});
return;
};
const deleteTodo = async (id) => {
await axios.delete(`http://localhost:3000/todos/${id}`);
};
const Todos = () => {
const [newTodo, setNewTodo] = useState("");
const [newType, setNewType] = useState("study");
const [filter, setFilter] = useState("");
const queryClient = useQueryClient();
const [count, setCount] = useState(0);
const { data: todos } = useQuery({
queryKey: ["todos"],
queryFn: () => getTodos(),
});
const { mutate: handleAddTodo } = useMutation({
mutationFn: addTodo,
onSuccess: () => {
queryClient.invalidateQueries(["test"]);
},
});
const handleFilter = (e) => {
setFilter(e.target.value);
};
return (
<div>
<input
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Add new todo"
/>
<select value={newType} onChange={(e) => setNewType(e.target.value)}>
<option value="study">Study</option>
<option value="exercise">Exercise</option>
</select>
<button onClick={() => handleAddTodo({ newTodo, newType })}>
Add Todo
</button>
<div>
<span>Filter: </span>
<select value={filter} onChange={handleFilter}>
<option value="">All</option>
<option value="study">Study</option>
<option value="exercise">Exercise</option>
</select>
</div>
<ul>
{todos &&
todos.map((todo) => (
<li key={todo.id}>
{todo.text} ({todo.type})
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default Todos;
```
|
{"Voters":[{"Id":740553,"DisplayName":"Mike 'Pomax' Kamermans"},{"Id":367865,"DisplayName":"Ouroborus"},{"Id":5468463,"DisplayName":"Vega"}],"SiteSpecificCloseReasonIds":[18]} |
{"Voters":[{"Id":3744304,"DisplayName":"connexo"}]} |
When using **kubectl get nodes**, the connection refused error you are experiencing is probably caused by the way your Ansible playbook handles the kubeconfig file.
**See how to resolve the problem and make calico deployment possible here.**
- Make sure the master node's Kubernetes API server is up and working by checking its port 6443 This can be accomplished by confirming that no firewall rules are preventing the connection and monitoring the kube-apiserver service's status.
- Due to security considerations, it is generally discouraged to run Ansible jobs with root capabilities. Instead, create a special user for Kubernetes management and configure Ansible to utilize that user.
- Inside the playbook once the kubeconfig has been copied to a non-root user's home directory.Ensure that the user has the necessary permissions, and utilize the file module's owner and group options to properly specify ownership and group.
- Change the playbook's kubectl get nodes task to point to the non-root user's kubeconfig directory.
- Using the official calico for Kubernetes CNI provider on [Ansible Galaxy][1], you can deploy calico once you have a functional kubeconfig established for your non-root user.
Instead of pasting the kubeconfig directly into the playbook of enhanced security advantage, think about storing it as a Kubernetes secret. Using [Ansible Vault][2] to safely handle private data, such as Kubeadm tokens
[1]: https://galaxy.ansible.com/ui/repo/published/community/kubernetes/
[2]: https://docs.ansible.com/ansible/latest/cli/ansible-vault.html |
In my case, I was receiving a custom class on the hub method, but the properties of that class had no setters, so all properties were default values.
So each property needs `{ get; set; }` to be assigned during deserialization. |
In this app the login screen has 3 buttons forget password, sign in and sign up the explicit intent for sign up is working properly but for forget password it force closes the app
LoginPage.java
```
package com.example.myapplication;
#*REMOVED IMPORTS FOR SIMPLICITY*#
import com.google.android.material.textfield.TextInputLayout;
public class LoginPage extends AppCompatActivity {
// Varaibles
Button signup,signin,forgetpass;
ImageView logo;
TextInputLayout username,password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_login_page);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
signup = findViewById(R.id.signUpBtn);
logo = findViewById(R.id.logo);
signin = findViewById(R.id.signInBtn);
username = findViewById(R.id.username);
password = findViewById(R.id.pass);
forgetpass = findViewById(R.id.forgetBtn);
DBHelper dbHelper = new DBHelper(this);
**forgetpass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this,ForgetPasswordPage.class);
startActivity(intent);
}
});**
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, SignUpPage.class);
Pair[] pair = new Pair[3];
pair[0] = new Pair<View,String>(logo,"logo_img");
pair[1] = new Pair<View,String>(signin,"sign_up_in");
pair[2] = new Pair<View,String>(signup,"back_sign_up_in");
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(LoginPage.this,pair);
startActivity(intent,options.toBundle());
}
});
**signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uname = username.getEditText().getText().toString();
String pass = password.getEditText().getText().toString();
if (dbHelper.checkUsername(uname))
{
if (dbHelper.checkusernamePassword(uname,pass))
{
Intent intent = new Intent(LoginPage.this, HomePage.class);
startActivity(intent);
}else {
password.setError("Incorrect password");
}
}else {
username.setError("Username not found");
}
}
});
**
}
}
```
ForgetPasswordpage.java
```
package com.example.myapplication;
#*REMOVED IMPORTS FOR SIMPLICITY*#
import com.google.android.material.textfield.TextInputLayout;
public class ForgetPasswordPage extends AppCompatActivity {
ImageView back;
Button forgetPass;
TextInputLayout uname,pass,repass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_forget_password_page);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
uname = findViewById(R.id.Fusername);
pass = findViewById(R.id.NewPassword);
repass = findViewById(R.id.NewRePassword);
forgetPass = findViewById(R.id.ForgetBtn);
DBHelper dbHelper = new DBHelper(this);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ForgetPasswordPage.this, LoginPage.class);
startActivity(intent);
}
});
forgetPass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getEditText().getText().toString();
String password = pass.getEditText().getText().toString();
String rePassword = repass.getEditText().getText().toString();
if (!password.equals(rePassword))
{
repass.setError("Password dose not match");
pass.setError("Password dose not match");
} else if (!dbHelper.checkUsername(username)) {
uname.setError("User dose not exist");
} else if (password.equals(rePassword) && dbHelper.checkUsername(username)) {
dbHelper.changePassword(username,password);
}
}
});
}
}
```
also in when signing in even if my uname and pass are correct the app force closes i think there may some problem in DBHelper.java
DBHelper.java
```
package com.example.myapplication;
#*REMOVED IMPORTS FOR SIMPLICITY*#
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "login.db";
public DBHelper(Context context) {
super(context, DBNAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create TABLE users(unsername TEXT primary key,password TEXT,fullName TEXT,email TEXT,phone TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop Table if exists users");
}
public boolean insertData(String username, String password, String fullName, String email,String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("unsername",username);
contentValues.put("password",password);
contentValues.put("fullName",fullName);
contentValues.put("email",email);
contentValues.put("phone",phone);
long results = db.insert("users",null,contentValues);
if (results == -1)
return false;
else
return true;
}
public boolean checkUsername (String username) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE usnername = ?",new String[] {username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public boolean checkusernamePassword (String username, String password) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE usnername = ? and password = ?",new String[] {username,password});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public boolean changePassword (String username, String password) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("UPDATE users SET passwod = ? WHERE username = ?",new String[] {password,username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
}
```
i don't know the intent code are same but still it is not working as for sign in there must be problem in my query execution |
Explicit intent not working with forget password button also unable to read data from DB during sign in |
|android|android-intent|android-sqlite| |
null |
Try implementing Serializable
public class AccountDTO implements Serializable {
//your fields, constructors, methods etc.
}
[Here][1] is the reference.
[1]: https://stackoverflow.com/a/57866376/17718213 |
1. Return a pointer to the `Node` of interest instead of updating the out parameter `head_dest`. The stack will implicitly hold `cur_list_dest`.
1. The original implementation changes the original list. To create a new list you need to return a pointer to *copy* of the smallest node or NULL. To emphasize that I made the argument constant with `const Node *head`.
1. Observe that `pairWiseMinimumInNewList_Rec()` either returns a copy of 1st node, 2nd node or NULL (3 values). The recursive call is either two nodes head or NULL (2 values). For a total of 6 cases. If you make the values conditional instead of expressions you can collapse that into a single return statement.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int val;
struct Node *pt_next;
} Node;
Node *linked_list_new(int val, Node *pt_next) {
Node *n = malloc(sizeof *n);
if(!n) {
printf("malloc failed\n");
exit(1);
}
n->val = val;
n->pt_next = pt_next;
return n;
}
Node *linked_list_create(size_t n, int *vals) {
Node *head = NULL;
Node **cur = &head;
for(size_t i=0; i < n; i++) {
*cur = linked_list_new(vals[i], NULL);
if(!head) head = *cur;
cur = &(*cur)->pt_next;
}
return head;
}
void linked_list_print(Node *head) {
for(; head; head=head->pt_next)
printf("%d->", head->val);
printf("NULL\n");
}
void linked_list_free(Node *head) {
while(head) {
Node *tmp = head->pt_next;
free(head);
head=tmp;
}
}
Node *pairWiseMinimumInNewList_Rec(const Node* head) {
return head ?
linked_list_new(
(head->pt_next && head->val < head->pt_next->val) || !head->pt_next ?
head->val :
head->pt_next->val,
pairWiseMinimumInNewList_Rec(head->pt_next ? head->pt_next->pt_next : NULL)
) :
NULL;
}
int main() {
Node *head=linked_list_create(7, (int []) {2,1,3,4,5,6,7});
Node* head_dest=pairWiseMinimumInNewList_Rec(head);
linked_list_free(head);
linked_list_print(head_dest);
linked_list_free(head_dest);
}
```
Example run of a test case that exercises more of the code paths than what was given:
```
1->3->5->7->NULL
``` |
my problem solved after changing from wayland to x11, logout and change from plasma(wayland) to plasma(x11) |
I have modified the httpd.conf file as below to open apache server on localhost:81 port instead default port 80.
#Listen 12.34.56.78:81
Listen 81
and
ServerName localhost:81
OR
If we don't want use both the servers at a time, you can simply stop one server and start the another on which you want to work. |
i have a Steam Deck and would like to install GLFW on a Steamdeck, so that VSCode can find the Libary, i use Cmake. I used Cmake on another linux machine with no problems. I think its related to the steam deck and steam os.
I a location in with the following files in usr/lib/cmake/glfw3 :
- glfw3Targets.cmake,
- glfw3Targets-noconfig.cmake,
- glfw3ConfigVersion.cmak,
- glfw3Config.cmake
Also there are two header files in /usr/include/GLFW called:
- glfw3.h
- glfw3native.h
Also i have this so's:
- /usr/lib/libglfw.so
- /usr/lib/libglfw.so.3
- /usr/lib/libglfw.so.3.3
In the main.cpp file the #include \<GLFW/glfw3.h\> do not work.
My Cmake file looks now like this:
```
cmake_minimum_required(VERSION 3.12)
project(test)
# Add executable
add_executable(test src/main.cpp)
# Specify the path to GLFW include directory
set(GLFW_INCLUDE_DIR "/usr/include" CACHE PATH "Path to GLFW include directory")
# Specify the path to GLFW library directory
set(GLFW_LIBRARY_DIR "/usr/lib" CACHE PATH "Path to GLFW library directory")
# Add GLFW include directory
target_include_directories(test PRIVATE ${GLFW_INCLUDE_DIR})
# Link GLFW library to your executable
target_link_libraries(test ${GLFW_LIBRARY_DIR}/libglfw.so)
```
Maybe some one with a better understanding of cmake, c and linux can help me.
Thank you in advance.
I tried different combinations of cmake files with find() and so on. Looked into the internet, and used Chat GPT to find a solution.
Reinstalled with
```
sudo pacman -S glfw-x11
```
glfw again on the steam deck.
EDIT:
Here is the full error when i start the building:
```
[main] Building folder: game_engine all
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all --
[build] ninja: error: '/usr/lib/libglfw.so', needed by 'test', missing and no known rule to make it
[proc] The command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all -- exited with code: 1
[driver] Build completed: 00:00:00.029
[build] Build finished with exit code 1
```
EDIT2:
When i safe the CMakeList.txt i get following message in VSCode:
```
[main] Configuring project: game_engine
[proc] Executing command: /usr/bin/cmake --no-warn-unused-cli -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc -DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++ -S/home/deck/Programming/game_engine -B/home/deck/Programming/game_engine/build -G Ninja
[cmake] Not searching for unused variables given on the command line.
[cmake] -- Configuring done (0.0s)
[cmake] -- Generating done (0.0s)
[cmake] -- Build files have been written to: /home/deck/Programming/game_engine/build
```
Permission of usr/lib/libglfw.so:
with following command: ```ls -l libglfw.so```
lrwxrwxrwx 1 root root 12 Jul 23 2022 libglfw.so -> libglfw.so.3
EDIT3:
if i change my ```target_link_libraries(test ${GLFW_LIBRARY_DIR}/libglfw.so)``` to ```target_link_libraries(test $usr/lib/libglfw.so.3.3)```
Permission is set to: -rwxr-xr-x 1 root root 278200 Jul 23 2022 /usr/lib/libglfw.so.3.3
i get this error in the build process:
```
[main] Building folder: game_engine
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all --
[build] [1/2 50% :: 0.022] Building CXX object CMakeFiles/test.dir/src/main.cpp.o
[build] FAILED: CMakeFiles/test.dir/src/main.cpp.o
[build] /usr/bin/g++ -g -std=gnu++11 -MD -MT CMakeFiles/test.dir/src/main.cpp.o -MF CMakeFiles/test.dir/src/main.cpp.o.d -o CMakeFiles/test.dir/src/main.cpp.o -c /home/deck/Programming/game_engine/src/main.cpp
[build] /home/deck/Programming/game_engine/src/main.cpp:3:10: fatal error: GLFW/glfw3.h: No such file or directory
[build] 3 | #include <GLFW/glfw3.h>
[build] | ^~~~~~~~~~~~~~
[build] compilation terminated.
[build] ninja: build stopped: subcommand failed.
[proc] The command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all -- exited with code: 1
[driver] Build completed: 00:00:00.054
[build] Build finished with exit code 1
``` |
I run my training on HPC. I set up Python virtual environment for this. However, Python virtual environment gets 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 ... |
Python virtual environment get deleted on HPC automatically |
I saw this piece of code in MDN while I was learning some syntax about Class in JavaScript today, which really confused me. [Here it is][1]:
```javascript
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
```
If I create an instance of Rectangle without passing into any arguments, the default value of height 0 doesn't work on the instance.
```javascript
const rec = new Rectangle();
// { height: undefined, width: undefined }
```
My question is "Is this piece of code is a bad practice?". If a class filed has been assigned inside the constructor, we shouldn't give a defalut valut to the class outside the constructor because it will always not work. Instead, we can set a default of a class field that hasn't been assigned inside the constructor like below:
```javascript
class Rectangle {
height = 10;
width;
constructor(width) {
this.width = width;
}
}
const rec = new Rectangle();
console.log(rec);
// { height: 10, width: undefined }
```
The defalut value works in this case.
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#field_declarations:~:text=class%20Rectangle%20%7B%0A%20%20height%20%3D%200%3B%0A%20%20width%3B%0A%20%20constructor(height%2C%20width)%20%7B%0A%20%20%20%20this.height%20%3D%20height%3B%0A%20%20%20%20this.width%20%3D%20width%3B%0A%20%20%7D%0A%7D |
I am using voila Jupyter lab extension. Voila renders all plots, ipywidgets and markdown on one system but not in another system. All my package versions, browsers are up to date
[Plots not rendering on one system](https://i.stack.imgur.com/DgvHd.png)
[Plots rendering on another system](https://i.stack.imgur.com/xXb28.png)
I updated all the package versions, ipywidgets voila versions and browser versions for both the systems |
Voila is rendering plots, ipywidgets and markdown on one system but only markdown in another system |
|plotly|ipywidgets|voila| |
null |
I'm unable to ping/or perform curl to any website from an instance which has only ipv6 address assigned whereas I'm able to ping/access internet if I create a windows instance with same settings (Ubuntu or Amazon Linux instances are not working), some of the details of the ec2 Instance are as follows
ip -6 addr:

Route Table for subnet:

Network ACL for subnet:

Ping command response (Stuck with no output): https://i.stack.imgur.com/gYY0j.png
Security Group Outbound Rules https://i.stack.imgur.com/ODGEf.png |
|mysql|mysql-8.0|mysql-spatial| |
I have a ksqldbcluster with 2 nodes. Sometimes i might receive an alert from grafana(which i monitor the cluster) that some queries are in error state. When i check the show queries i see that a number of queries have 1 PERSISTENT running and 1 ERROR. I restart first the second ksqdb docker instance. Sometimes is fixed sometimes is not. If is not i restart the first ksqldb docker instance and then is fixed. Any ideas?
version: '3'
services:
ksqldb-server:
container_name: ksqldb-server
hostname: ksqldb.cablenet-as.net
network_mode: host
image: confluentinc/ksqldb-server:latest
environment:
KSQL_HOST_NAME: ksqldb.xxxxxxxx
KSQL_BOOTSTRAP_SERVERS: xxxxxx:9093
KSQL_SECURITY_PROTOCOL: SSL
KSQL_LISTENERS: http://xxxxxx:8088,https://xxxxxx:8443
KSQL_KSQL_SCHEMA_REGISTRY_URL: http://xxxxxxxx-as.net:8081,http://xxxxxx:8082
KSQL_SSL_CLIENT_KEY_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_CLIENT_KEY_STORE_PASSWORD: xxxxxx
KSQL_SSL_CLIENT_TRUST_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_CLIENT_TRUST_STORE_PASSWORD: xxxxxxx
KSQL_SERVER_ID: id1
KSQL_STREAMS_NUM_STANDBY_REPLICAS: 1 # Corrected property name
KSQL_LOG4J_ROOT_LOGLEVEL: "ERROR"
KSQL_QUERY_PULL_ENABLE_STANDBY_READS: true
KSQL_HEARTBEAT_ENABLE: true
KSQL_QUERY_PULL_THREAD_POOL_SIZE: "30"
KSQL_LAG_REPORTING_ENABLE: true
KSQL_INTERNAL_LISTENER: http://xxxxxxx:8080
KSQL_SSL_TRUSTSTORE_LOCATION: /etc/kafka/secrets/ksqldb.truststore.jks
KSQL_SSL_TRUSTSTORE_PASSWORD: xxxxxx
KSQL_SSL_KEYSTORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_KEYSTORE_PASSWORD: xxxxxxx
KSQL_JMX_OPTS: -Dcom.sun.management.jmxremote -javaagent:/etc/kafka/secrets/jmx_prometheus_javaagent-0.17.2.jar=4000:/etc/kafka/secrets/ksql.yaml
ports:
- 8088:8088
- 4000:4000
- 8443:8443
volumes:
- /ksqldata/data:/var/lib/ksqldb-server/data
- /ksqldata/newssl/:/etc/kafka/secrets/
ksqldb-cli:
image: confluentinc/ksqldb-cli:latest
container_name: ksqldb-cli
entrypoint: /bin/sh
tty: true # Corrected indentation
telegraf:
image: telegraf
restart: always
volumes:
- ./telegraf.conf:/etc/telegraf/telegraf.conf:ro
- /var/run/docker.sock:/var/run/docker.sock
~
When restarting ksqldb instance the issue is resolved. Maybe i am missing something in my parameters or how to fix the error? |
I'm encountering an issue with building a responsive webpage. When testing the page's responsiveness, the width extends beyond the device's width for some reason.
I've tried removing various parts of the code, and I've found that the "introduction" div seems to be causing the problem. When I remove it, the webpage returns to the normal width. Can anyone help me identify what's wrong with my code?
Here's the relevant HTML and CSS for the introduction div :-
(HTML):
<div class="introduction row align-items-start">
<div class="gap row">
<!-- Gap in between a ID and text and image -->
</div>
<div class="row">
<div class="intro-text col">
Over the past few years, information technology has exploded, becoming a major force driving innovation and change. But here's the thing: even though women and folks of color have been rocking it in IT, there's still a big lack of diversity in many areas.
</div>
<div class="col">
<img src="/img/women-in-tech.png" alt="Women In IT">
</div>
</div>
</div>
(CSS):
.introduction {
position: relative;
}
.intro-text {
font-family: "Noto Sans", sans-serif;
font-optical-sizing: auto;
font-weight: 300;
font-style: normal;
font-variation-settings: "wdth" 100;
font-size: 2.5vw;
color: white;
margin-left: 3vw;
}
.col img {
margin-top: 1.5vw;
max-width: 100%;
height: auto;
margin-left: 7vw;
}
/* When width of device is less than 1150px, change the image height and width to 70% */
@media screen and (max-width: 1150px) {
.col img {
height: 70%;
}
}
.gap {
height: 100px;
} |
I have a program written in the Delphi Programming Language that I have to convert to C# using Visual Studio. I have done most of the conversion but ran into a couple of challenges with `VarArrayCreate`.
What I have is this: `Line := VarArrayCreate([0, 1], varVariant);`
I can't seem to figure out a conversion or substitute for the `VarArrayCreate`.
I know that the object in C# can be used for a Variant substitute but the above has me stuck.
any help would be great.
I have added the Delphi code below. I am interested in the procedure `TForm1.Button3Click(Sender: TObject);` procedure:
unit Unit1;
(*------------------------------------------------------------------------------
DX Atlas Automation demo #2 (early binding)
Make sure that DX Atlas is installed.
Requires DxAtlas_TLB. You can either generate this file in Delphi
(Project -> Import Type Library -> DxAtlas) or use the one included
with this demo.
http://www.dxatlas.com
------------------------------------------------------------------------------*)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OleServer, StdCtrls, DxAtlas_TLB, ActiveX, AxCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
CheckBox1: TCheckBox;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
public
Atlas: IAtlas;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
//------------------------------------------------------------------------------
// Start DX Atlas
//------------------------------------------------------------------------------
procedure TForm1.FormCreate(Sender: TObject);
begin
//connect to Dx Atlas on program startup
try
Atlas := CoAtlas.Create;
except on E: Exception do
begin
ShowMessage('Cannot connect to DX Atlas: ' + E.Message);
Application.Terminate;
end;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
var
WorkArea: TRect;
begin
//get Desktop work area dimensions
SystemParametersInfo(SPI_GETWORKAREA, 0, @WorkArea, 0);
//form placement
Top := WorkArea.Top;
Left := WorkArea.Left;
Height := WorkArea.Bottom - WorkArea.Top;
//atlas placement
//stop repainting
Atlas.Map.BeginUpdate;
//place window
Atlas.Top := Top;
Atlas.Left := Left + Width;
Atlas.Width := WorkArea.Right - Left - Width;
Atlas.Height := Height;
//hide prefixes
Atlas.Map.PrefixesVisible := false;
//now allow repainting
Atlas.Map.EndUpdate;
//show the Atlas window
Atlas.Visible := true;
end;
//------------------------------------------------------------------------------
// Points
//------------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
Pt, Points: OleVariant;
i: integer;
Layer: ICustomLayer;
begin
Randomize;
//create Variant array for data
Points := VarArrayCreate([0, 999], varVariant);
//fill the array with random points
for i:=0 to 999 do
begin
//each point is a variant array with 2 elements
Pt := VarArrayCreate([0,1], varVariant);
//point coordinates are random (decimal degrees)
Pt[0] := Random(360) - 180; //longitude
Pt[1] := Random(180) - 90; //latitude
//add point to the data array
Points[i] := Pt;
end;
//show data on the map
Atlas.Map.BeginUpdate;
with Atlas.Map do
try
Projection := PRJ_RECTANGULAR;
Dimmed := false;
CustomLayers.Clear;
//add new custom layer
Layer := CustomLayers.Add(LK_POINTS);
with Layer do
begin
//set layer attributes
PenColor := clBlue;
BrushColor := clLime;
PointSize := 2;
//set data
SetData(Points);
end;
finally
EndUpdate;
end;
end;
//------------------------------------------------------------------------------
// Labels
//------------------------------------------------------------------------------
procedure TForm1.Button2Click(Sender: TObject);
var
//Lb: Variant;
Labels: Variant;
i: integer;
Layer: ICustomLayer;
begin
Randomize;
Labels := VarArrayCreate([0, 999], varVariant);
for i:=0 to 999 do
begin
//each label is a variant array of 3 Variants
Labels[i] := VarArrayOf([Random(360) - 180, //longitude
Random(180) - 90, //latitude
Format(' LABEL #%d ', [i])]); //label text
//alternate way of creating and filling the array
{
Lb := VarArrayCreate([0,2], varVariant);
Lb[0] := Random(360) - 180;
Lb[1] := Random(180) - 90;
Lb[2] := Format(' Label #%d ', [i]);
Labels[i] := Lb;
}
end;
Atlas.Map.BeginUpdate;
with Atlas.Map do
try
Projection := PRJ_RECTANGULAR;
Dimmed := false;
CustomLayers.Clear;
Layer := CustomLayers.Add(LK_LABELS);
with Layer do
begin
LabelsTransparent := CheckBox1.Checked;
//label BG if not transparent
BrushColor := clAqua;
//font attributes
with (Font as IFont) do
begin
Put_Name('Courier New');
Put_Italic(true);
Put_Size(9);
//Put_Name('Small fonts');
//Put_Size(5);
end;
//font color
PenColor := clBlue;
//data
SetData(Labels);
end;
finally
EndUpdate;
end;
end;
//------------------------------------------------------------------------------
// Lines
//------------------------------------------------------------------------------
procedure TForm1.Button3Click(Sender: TObject);
var
Pt, Line, Meridians, Parallels: OleVariant;
i, j: integer;
begin
//generate meridians
Meridians := VarArrayCreate([0, 7], varVariant);
for i:=0 to 7 do
begin
Line := VarArrayCreate([0, 36], varVariant);
for j:=0 to 36 do
begin
Pt := VarArrayCreate([0, 1], varVariant);
Pt[0] := i*45 - 180;
Pt[1] := j*5 - 90;
Line[j] := Pt;
end;
Meridians[i] := Line;
end;
//generate parallels
Parallels := VarArrayCreate([0, 2], varVariant);
for i:=0 to 2 do
begin
Line := VarArrayCreate([0, 72], varVariant);
for j:=0 to 72 do
begin
Pt := VarArrayCreate([0, 1], varVariant);
Pt[0] := j*5 - 180;
Pt[1] := i*45 - 45;
Line[j] := Pt;
end;
Parallels[i] := Line;
end;
//show on the map
Atlas.Map.BeginUpdate;
with Atlas.Map do
try
Projection := PRJ_AZIMUTHAL;
Dimmed := false;
CenterLatitude := 43;
CenterLongitude := -79;
CustomLayers.Clear;
//show meridians
with CustomLayers.Add(LK_LINES) do
begin
PenColor := clBlue;
SetData(Meridians);
end;
//show parallels
with CustomLayers.Add(LK_LINES) do
begin
PenColor := clRed;
SetData(Parallels);
end;
finally
EndUpdate;
end;
end;
//------------------------------------------------------------------------------
// Area
//------------------------------------------------------------------------------
procedure TForm1.Button4Click(Sender: TObject);
var
Pt, Area, Areas: OleVariant;
i: integer;
begin
//single area
Areas := VarArrayCreate([0, 0], varVariant);
//generate area data
Area := VarArrayCreate([0, 72], varVariant);
for i:=0 to 72 do
begin
Pt := VarArrayCreate([0, 1], varVariant);
Pt[0] := -79 + 20 * cos(i*5/180*Pi);
Pt[1] := 43 + 20 * sin(i*5/180*Pi);
Area[i] := Pt;
end;
Areas[0] := Area;
//show on the map
Atlas.Map.BeginUpdate;
with Atlas.Map do
try
Projection := PRJ_RECTANGULAR;
Dimmed := true;
CustomLayers.Clear;
with CustomLayers.Add(LK_AREAS) do
begin
AreaBrightness := 12; //0..15, 15=max
SetData(Areas);
end;
finally
EndUpdate;
end;
end;
//------------------------------------------------------------------------------
// Glyphs
//------------------------------------------------------------------------------
procedure TForm1.Button5Click(Sender: TObject);
var
Glyphs: Variant;
i: integer;
Layer: ICustomLayer;
begin
Randomize;
//create array of Variants
Glyphs := VarArrayCreate([0,333], varVariant);
//each element of the array is a variant array with 3 elements
for i:=0 to 333 do
Glyphs[i] := VarArrayOf([Random(360)-180, //longitude -180..180
Random(180)-90, //latitude -90..90
Random(10)]); //image index 0..9
Atlas.Map.BeginUpdate;
with Atlas.Map do
try
Projection := PRJ_RECTANGULAR;
Dimmed := false;
//delete all layers
CustomLayers.Clear;
//add layer
Layer := CustomLayers.Add(LK_GLYPHS);
//Glyphs.bmp is a bitmap 160x16 that contains 10 glyphs, 16x16 each
//the color of lower left pixel (clFuchsia) is considered transparent
//the hot spot of the glyph is at (1, 15).
Layer.LoadGlyphsFromFile(ExtractFilePath(ParamStr(0)) + 'Glyphs.bmp', 1, 15);
//send locations to the layer
Layer.SetData(Glyphs);
finally
//now allow repainting
EndUpdate;
end;
end;
//------------------------------------------------------------------------------
// Great Circle paths
//------------------------------------------------------------------------------
procedure TForm1.Button6Click(Sender: TObject);
var
Pt, Line, Lines: Variant;
i, j: integer;
begin
//generate an array of Great Circle paths
Lines := VarArrayCreate([0, 33], varVariant);
for i:=0 to 33 do
begin
//a Great Circle path is defined by its end points
Line := VarArrayCreate([0, 1], varVariant);
Line[0] := VarArrayOf([-79, 43 {Toronto}]);
Line[1] := VarArrayOf([Random(360) - 180, Random(180) - 90]);
//add path to the array
Lines[i] := Line;
end;
//show paths on the map
Atlas.Map.BeginUpdate;
with Atlas.Map do
try
Projection := PRJ_RECTANGULAR;
Dimmed := false;
CustomLayers.Clear;
with CustomLayers.Add(LK_LINES) do
begin
PenColor := clBlue;
SetData(Lines);
end;
finally
EndUpdate;
end;
//Note that Delphi automatically releases the variant arrays when they go out of scope.
//In other languages you may have to release them explicitly.
end;
end.
|
What is the Delphi `VarArrayCreate` alternative for C#? |
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-js -->
import {
NameServices
} from '../../@core/utils/NameServices.service';
@Component({
selector: 'your-component',
standalone: true,
imports: [
NameServices
],
templateUrl: './your.component.html',
styleUrl: './your.component.scss',
})
export class YourComponent {
constructor(private nameServices: NameServices) {}
}
<!-- end snippet -->
|
I'm developing a Javascript animation using matter.js. Here is the link:
https://codepen.io/Sergio-Escalona/pen/VwNrwbw
```
document.addEventListener("DOMContentLoaded", function () {
// Basic setup
let Engine = Matter.Engine,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body;
let engine = Engine.create();
engine.world.gravity.y = 0; // No gravity for a space-like effect
let render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
background: 'transparent',
wireframes: false // for sprite rendering
}
});
// Create static walls
let thickness = 50; // Ensures ducks don't escape through fast movements
let wallOptions = { isStatic: true, restitution: 1.0 }; // Perfectly elastic collisions
let ground = Bodies.rectangle(window.innerWidth / 2, window.innerHeight + thickness / 2, window.innerWidth, thickness, wallOptions);
let leftWall = Bodies.rectangle(-thickness / 2, window.innerHeight / 2, thickness, window.innerHeight, wallOptions);
let rightWall = Bodies.rectangle(window.innerWidth + thickness / 2, window.innerHeight / 2, thickness, window.innerHeight, wallOptions);
let topWall = Bodies.rectangle(window.innerWidth / 2, -thickness / 2, window.innerWidth, thickness, wallOptions);
World.add(engine.world, [ground, leftWall, rightWall, topWall]);
// Function to add a new duck with random selection for black duck
function addDuck() {
let safeMargin = 100; // A margin to avoid spawning too close to the edge
let radius = 25;
// Randomly choose the texture for the duck
let textureUrl = Math.random() < 0.9 ?
'https://assets.codepen.io/12210161/duckling-svgrepo-com.svg' :
'https://assets.codepen.io/12210161/duckling-svgrepo-com-bk.svg';
let duck = Bodies.circle(Math.random() * (window.innerWidth - 2 * safeMargin) + safeMargin, Math.random() * (window.innerHeight - 2 * safeMargin) + safeMargin, radius, {
restitution: 0.9,
friction: 0.0,
frictionAir: 0.0,
density: 0.001,
render: {
sprite: {
texture: textureUrl,
xScale: 0.1,
yScale: 0.1
}
}
});
// Apply an initial force to ensure movement
Body.applyForce(duck, {x: duck.position.x, y: duck.position.y}, {x: (Math.random() - 0.5) * 0.05, y: (Math.random() - 0.5) * 0.05});
World.add(engine.world, duck);
}
document.getElementById("oneMoreBtn").addEventListener("click", addDuck);
// Start the engine and renderer
Engine.run(engine);
Matter.Render.run(render);
// Initially add a duck to start with
addDuck();
});
```
I don't know why black ducks are smaller than the regular ones. The svg files dimensions (px) are exactly the same and I can't find where is the problem.
Can anyone help me to solve it?
Thanks in advance!!!
I've checked the svg files and both are exactly the same size. About the Javascript code I can't find anything beyond the render scale but I think it shouldn't be the problem. |
Selenium code working fine on main laptop, but not on my other one |
|python|pycharm| |
null |
I am trying to create a structure `Student` which contains q substructures named `Course`. Each `Course` is a structure with a credit and point `int` values.
How do I set up my `Student` structure to have an integer number of `Course` structures within it? Thanks
```
struct Student{
int q;
Course course[q];
};
struct Course{
int credit;
int point;
};
```
I tried this but VSC is telling me it is wrong.
Edit error:
```
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
using namespace std;
struct Course{
string name;
int credit;
int point;
};
typedef struct Student{
vector<Course> courses;
};
int main() {
Student student;
system("cls");
int input;
int input2;
string strinput;
cout<<"--------------------------------------------------------------------------"<<endl;
cout<<" GPA & CGPA Calculator (Developed by Ohid) "<<endl;
cout<<"--------------------------------------------------------------------------\n"<<endl;
cout<<"Set up the student!"<<endl;
sub:
cout<<"Add a course"<<endl;
cout<<"Course name: ";
cin>>strinput;
cout<<"Course points: ";
cin>>input;
cout<<"Course credits ";
cin>>input2;
student.courses.push_back({strinput,input,input2});
cout<<"Add another course (1/0)?: ";
cin>>input;
switch(input)
{
case 1:
goto sub;
break;
case 2:
break;
}
int numCourses = student.courses.size();
cout<<"--------------------------------------------------------------------------\n"<<endl;
cout<<"Student created with "<<student.q<<" courses!"<<endl;
cout<<"--------------------------------------------------------------------------\n"<<endl;
cout<<" MENU:"<<endl;
cout<<" 1. Calculate GPA (Grade Point Average)"<<endl;
cout<<" 2. Calculate CGPA (Cummulative Grade Point Average)"<<endl;
cout<<" 3. Method that is applied here for calclating GPA & CGPA"<<endl;
cout<<" 4. Exit Application"<<endl;
cout<<"--------------------------------------------------------------------------"<<endl;
sub:
cout<<"Enter your choice: ";
cin>>input;
switch(input)
{
case 1:
cout<<"You chose calculate GPA";
calculateGPA();
break;
case 2:
cout<<"You chose calculate CGPA";
calculateCGPA();
break;
case 3:
cout<<"You chose method";
method();
break;
case 4:
cout<<"You chose to exit";
exit(EXIT_SUCCESS);
break;
default:
cout<<"You are stupid";
goto sub;
break;
}
}
void calculateGPA()
{
}
void calculateCGPA()
{
}
void method()
{
}
```
Error text!
'Course': undeclared identifiercpp(C2065)
'std::vector': 'Course' is not a valid template type argument for parameter '_Ty'cpp(C2923)
'std::vector': too few template argumentscpp(C2976)
class std::vector<Course>
Fixed std etc.
```
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <string>
struct Course{
std::string name;
int credit;
int point;
};
typedef struct Student{
std::vector<Course> courses;
};
int main() {
Student student;
system("cls");
int input;
int input2;
std::string strinput;
std::cout<<"--------------------------------------------------------------------------"<<std::endl;
std::cout<<" GPA & CGPA Calculator (Developed by Ohid) "<<std::endl;
std::cout<<"--------------------------------------------------------------------------\n"<<std::endl;
std::cout<<"Set up the student!"<<std::endl;
sub:
std::cout<<"Add a course"<<std::endl;
std::cout<<"Course name: ";
std::cin>>strinput;
std::cout<<"Course points: ";
std::cin>>input;
std::cout<<"Course credits ";
std::cin>>input2;
student.courses.push_back({strinput,input,input2});
std::cout<<"Add another course (1/0)?: ";
std::cin>>input;
switch(input)
{
case 1:
goto sub;
break;
case 2:
break;
}
int numCourses = student.courses.size();
std::cout<<"--------------------------------------------------------------------------\n"<<std::endl;
std::cout<<"Student created with "<<numCourses<<" courses!"<<std::endl;
std::cout<<"--------------------------------------------------------------------------\n"<<std::endl;
std::cout<<" MENU:"<<std::endl;
std::cout<<" 1. Calculate GPA (Grade Point Average)"<<std::endl;
std::cout<<" 2. Calculate CGPA (Cummulative Grade Point Average)"<<std::endl;
std::cout<<" 3. Method that is applied here for calclating GPA & CGPA"<<std::endl;
std::cout<<" 4. Exit Application"<<std::endl;
std::cout<<"--------------------------------------------------------------------------"<<std::endl;
sub:
std::cout<<"Enter your choice: ";
std::cin>>input;
switch(input)
{
case 1:
std::cout<<"You chose calculate GPA";
calculateGPA();
break;
case 2:
std::cout<<"You chose calculate CGPA";
calculateCGPA();
break;
case 3:
std::cout<<"You chose method";
method();
break;
case 4:
std::cout<<"You chose to exit";
exit(EXIT_SUCCESS);
break;
default:
std::cout<<"You are stupid";
goto sub;
break;
}
}
void calculateGPA()
{
}
void calculateCGPA()
{
}
void method()
{
}
``` |
I am trying to understand the internal workings of RowSet.
How does it set the properties data and create a connection?
RowSetFactory factory = RowSetProvider.newFactory();
JdbcRowSet jdbcRowSet = factory.createJdbcRowSet();
jdbcRowSet.setUrl("..................");
jdbcRowSet.setUsername(".............");
jdbcRowSet.setPassword("..............");
jdbcRowSet.setCommand("...............");
jdbcRowSet.execute();
|
This is because the generic type `S` can have more keys than just `"a"` and `"b"` βΒ that's what the `extends` keyword means in that position: that the generic type `S` must be [constrained](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints) by `Pick<Test, "a" | "b">` (not that it ONLY has keys `"a"` and `"b"`.
TypeScript is [structurally-typed](https://www.typescriptlang.org/docs/handbook/type-compatibility.html) (more [here](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#structural-type-system) and [here](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#structural-typing)), so supplying a generic type that satisfies `Pick<Test, "a" | "b">` that **also** has an [index signature](https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures) of `symbol` keys with `unknown` values will be accepted by the compilerβ¦
[TS Playground](https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&removeComments=true&target=99&jsx=4&exactOptionalPropertyTypes=true&inlineSourceMap=true&inlineSources=true&isolatedModules=true&noImplicitOverride=true&noErrorTruncation=true&ssl=13&ssc=1&pln=21&pc=75#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFACQcAXMllKAOYDchARqSAK4C2d0tBCpdA9rwBsIcELQC+ePEOxwoUUuSoBtALrIAvMlW08MJiARhgvEMkhYAPAGVkEAB6QQAEwzIACsAQBrC+iwAaZAAiOCDkAB9guiCAPkDUWwcIZ1cvCABPXhhkKxiACgA3OAFSVFUASlxCWSgNZCKBcUkwdIAHFAAxfjr8IgUwChAaekZWdihOJTT0hXS2QRVSfS8QXgB3UTwxHQQTLGRQVqYwUjzprOQu3nLVOqUrOb4BPKCYfiDywJCgr+iVHXMYAsV0C52yV3yh2O5WoyAA9HDkAB5LyBOjHMiPQQHVyrGQYDDASggOB0IRmXhkAZUPBAA)
```lang-ts
type Foo = {
a: string;
b: number;
[key: symbol]: unknown;
};
const input: (keyof Foo)[] = [Symbol("foo"), "a", "b"];
test<Foo, keyof Foo>(input); // Ok, but symbol is not assignable to string
```
β¦but `symbol` is not assignable to `string`, so it would be a type error to accept an array of such values (or any other non-string value).
In the second code block example of your question you provided this code and question:
```lang-ts
type S = Pick<Test, "a" | "b">;
type T = keyof S;
const val: T[] = [];
arr = val; // why it is ok?
```
There, `S` is a type that looks like `{ a: string; b: number }` and T is the union of its keys, which is `"a" | "b"`. An array of `"a"` and `"b"` values are assignable to `string`, so there's no problem there.
A modified version of your `test` function that uses these types would look like thisβ¦
[TS Playground](https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&removeComments=true&target=99&jsx=4&exactOptionalPropertyTypes=true&inlineSourceMap=true&inlineSources=true&isolatedModules=true&noImplicitOverride=true&noErrorTruncation=true#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFACQcAXMllKAOYDchARqSAK4C2d0tBCpdA9rwBsIcELQC+ePEOxwoUUuSoBtALrIAvMlW08MJiARhgvEMkhYAFADc4A0hYDWEAJ68YyAArAEDgDzosABpkACI4EOQAH1C6EIA+AEpVBNxCWSgNZBsBcUkwZwAHFAAxfkz8IgUwChAaekZWdihOJSdnBWc2QRVSfQcQXgB3UTwxHQQTLGRQAqYweza3ZFLeJLVNJQBlTr4BCxCYfhCE4LCQ09iVHXMwCxm5hNogA)
```lang-ts
function test(val: (keyof Pick<Test, "a" | "b">)[]) {
arr = val;
}
```
> Note that `keyof Pick<Test, "a" | "b">` is just `"a" | "b"`.
β¦and attempting to provide an array of values that includes a non-string will produce a compiler diagnostic error:
```lang-ts
type Foo = {
a: string;
b: number;
[key: symbol]: unknown;
};
const input: (keyof Foo)[] = [Symbol("foo"), "a", "b"];
test(input); /* Error
~~~~~
Argument of type '(keyof Foo)[]' is not assignable to parameter of type '("a" | "b")[]'.
Type 'keyof Foo' is not assignable to type '"a" | "b"'.
Type 'symbol' is not assignable to type '"a" | "b"'.(2345) */
``` |
null |
I wrote a PHP function which can be used without Phar.
It also works with long filenames and was tested with big TAR archives. Compatible with PHP 5 to 8.
Usage:
```
<?php
$ret = tar_extract ("filename.tar", "./path-to-extract/");
if (empty ($ret["errText"])) {
print ($ret["fileCnt"]." files extracted.");
print ($ret["log"]);
}
else {
print ("Error: ".$ret["errText"]);
print ($ret["log"]);
}
?>
```
TAR archive functions:
```
<?php
function tar_truncate_name (&$str) {
for ($i=0;$i<strlen ($str);$i++) {
if (0==ord (substr ($str, $i, 1)))
break;
}
$str = substr ($str, 0, $i);
}
function tar_checksum (&$str, $size) {
$checksum = 0;
for ($i=0;$i<$size;$i++) {
$checksum += ord (substr ($str, $i, 1));
}
return $checksum;
}
function tar_read_header ($fh)
{
$header = array (
"name" => 100,
"mode" => 8,
"uid" => 8,
"gid" => 8,
"size" => 12,
"mtime" => 12,
"chksum" => 8,
"linkflag"=> 1,
"linkname"=> 100,
"magic" => 8,
"uname" => 32,
"gname" => 32,
"devmajor"=> 8,
"devminor"=> 8,
"rest" => 167
);
$dataPos = ftell ($fh)+512;
$stat = fstat($fh);
$filesize = $stat['size'];
if ($dataPos>$filesize) {
return -1;
}
$checksum = 0;
foreach ($header as $key => $len) {
$header[$key] = fread ($fh, $len);
$read = strlen ($header[$key]);
if ($read<$len)
return -1;
if ($key=="chksum") {
$empty = " ";
$checksum+=tar_checksum ($empty, 8);
}
else
$checksum+=tar_checksum ($header[$key], $len);
}
tar_truncate_name ($header["chksum"]);
if (empty ($header["chksum"])) {
return false; // Last TAR header
}
// Checksum
if ($header["chksum"]!=sprintf ("%06o", $checksum)) {
return -1;
}
// Parse form octal to decimal
if (sscanf ($header["size"], "%o", $header["size"])!=1)
return false;
if (sscanf ($header["mtime"], "%o", $header["mtime"])!=1)
return false;
// Truncate names
tar_truncate_name ($header["name"]);
tar_truncate_name ($header["linkname"]);
tar_truncate_name ($header["uname"]);
tar_truncate_name ($header["gname"]);
fseek ($fh, $dataPos);
if ($header["linkflag"]=="L" && $header["name"]=="././@LongLink") {
// Read long filename
$longFilename = fread ($fh, $header["size"]);
if (strlen ($longFilename)!=$header["size"])
return -1;
// Skip 512 Byte block
$size=(512-($header["size"] % 512));
fseek ($fh, ftell ($fh)+$size);
// Now comes the real block
$header = tar_read_header ($fh);
if (!is_array ($header)) {
return -1;
}
else {
$header["name"]=trim ($longFilename);
}
}
// Remove relative paths for security
$header["name"] = str_replace (["../", "..\\"], ["./", "./"], $header["name"]);
return $header;
}
function tar_extract ($tarFilename, $dstPath=".", $options=array ()) {
$ret = array (
"fileCnt" => 0,
"dirCnt" => 0,
"size" => 0,
"log" => "",
"errText" => ""
);
$fh = fopen ($tarFilename, "r");
if (!$fh) {
$ret["errText"] = "Cannot open TAR file: ".$tarFilename;
$ret["log"].=$ret["errText"]."\r\n";
return $ret;
}
while (!feof ($fh)) {
$header = tar_read_header ($fh);
if (!is_array ($header)) {
if ($header==-1) {
$ret["errText"] = "TAR header corrupt.";
$ret["log"].=$ret["errText"]."\r\n";
}
break;
}
else
if ($header["linkflag"]==0) {
$ret["log"].=$header["name"].", ".$header["size"]."\r\n";
// Read file
$dstFilename = $dstPath."/".$header["name"];
$fh2 = fopen ($dstFilename, "w+");
if (!$fh2) {
$ret["errText"] = "Cannot create file: ".$dstFilename;
$ret["log"].=$ret["errText"]."\r\n";
break;
}
else {
$size = $header["size"];
$buf = "";
while ($size>0) {
$bufSize = 0xFFFF;
if ($size<$bufSize)
$bufSize=$size;
$buf = fread ($fh, $bufSize);
$read = strlen ($buf);
if ($read<=0)
break;
fwrite ($fh2, $buf);
$size-=$read;
}
fclose ($fh2);
// Set file time and mode
touch ($dstFilename, $header["mtime"], $header["mtime"]);
chmod ($dstFilename, octdec($header["mode"]));
if ($size>0) {
$ret["errText"] = "Filesize incorrect: ".$dstFilename;
$ret["log"].=ret["errText"]."\r\n";
break;
}
}
// Skip 512 Byte block
if (($header["size"] % 512)!=0) {
$rest = 512-($header["size"] % 512);
fseek ($fh, ftell ($fh)+$rest);
}
$ret["fileCnt"]++;
$ret["size"]+=$header["size"];
}
else
if ($header["linkflag"]==5) {
$dstDir = $dstPath."/".$header["name"];
if (!is_dir ($dstDir) && !mkdir ($dstDir)) {
$ret["errText"] = "Cannot create directory: ".$dstDir;
$ret["log"].=$ret["errText"]."\r\n";
break;
}
// Set directory time and mode
touch ($dstDir, $header["mtime"], $header["mtime"]);
// chmod ($dstDir, octdec($header["mode"]));
$ret["dirCnt"]++;
}
else {
// Unknown linkflag
// Ignore header but skip size
if ($header["size"]>0) {
$size = $header["size"];
// Skip 512 Byte block
if ($header["size"]<512)
$size=512;
else
$size+=(512-($header["size"] % 512));
fseek ($fh, ftell ($fh)+$size);
}
}
}
fclose ($fh);
return $ret;
}
?>
``` |
I use Electron.js to build an application that utilizes Selenium WebDriver to automate activities on Chrome. When using the application on platforms like Windows or Mac Intel, it works fine and stable. However, when using it on a Mac M1, it performs very slowly.
Here are the dependencies I have used:
```json
"dependencies": {
"axios": "^1.4.0",
"chromedriver": "^113.0.0",
"date-fns": "^2.30.0",
"dotenv": "^16.1.4",
"electron": "^24.3.0",
"electron-chromedriver": "^24.0.0",
"electron-squirrel-startup": "^1.0.0",
"selenium-webdriver": "^4.9.2"
},
``` |
I created an app that generates keyword searchable PDF files with tesseact, but when the PDF file is created, the pages are randomly reordered by one page every few dozen pages. How can I get the PDF file to be created in the order in which the image files were read?
I used pool.map to match order but its not useless.
```
from multiprocessing import Pool, cpu_count
import pytesseract
import PyPDF2
import io
from datetime import datetime
import os
from PySide6.QtWidgets import QApplication, QFileDialog
import sys
# Tesseract path
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def process_image(args):
index, file_path = args
try:
# image to OCR PDF create
page = pytesseract.image_to_pdf_or_hocr(file_path, extension='pdf', lang='eng+kor')
return (index, file_path, page)
except Exception as e:
return (index, file_path, None)
def create_searchable_pdf_and_doc(files):
pdf_writer = PyPDF2.PdfWriter()
total_files = len(files)
# multi processing
with Pool(processes=cpu_count()) as pool:
# file index and path
tasks = [(i, file) for i, file in enumerate(files)]
# pool.map match order
results = pool.map(process_image, tasks)
# arrange
results.sort(key=lambda x: x[0])
for i, (_, _, page) in enumerate(results):
# processing status
print(f"\rProcessing: {i+1}/{total_files}", end="")
sys.stdout.flush()
if page:
pdf = PyPDF2.PdfReader(io.BytesIO(page))
for pageNum in range(len(pdf.pages)):
pdf_writer.add_page(pdf.pages[pageNum])
print("\nAll files have been processed. Compiling into PDF...")
# file name creation
today_date = datetime.now().strftime("%Y%m%d")
directory_name = os.path.basename(os.path.dirname(files[0]))
final_pdf_name = f"{directory_name}_{today_date}.pdf"
# PDF file save
with open(final_pdf_name, "wb") as f_out:
pdf_writer.write(f_out)
print(f"PDF file created: {final_pdf_name}")
def select_files():
app = QApplication(sys.argv)
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.ExistingFiles)
dialog.setNameFilter("Images (*.png *.xpm *.jpg *.jpeg *.bmp *.gif)")
if dialog.exec():
return dialog.selectedFiles()
return []
if __name__ == "__main__":
selected_files = select_files()
if selected_files:
create_searchable_pdf_and_doc(selected_files)
else:
print("Fie does not selected.")
```
How can I get the PDF file to be created in the order in which the image files were read? |
The project folder you have opened is not the parent folder of "admin.py" and "admin_instance.py" (or the path of "admin.py" would be relative instead of "c: > ..."). So those files are being treated as isolated Python code files.
Select VScode menu "File" -> "Open Folder" and open "C:\...\Python work\importing", and you will see the difference. |
Use case: I want to generate no-passphrase 2048-byte RSA keypairs I can use for service accounts to authenticate to Snowflake. I need to generate them programmatically to make key rotation practical.
Snowflake docs provide [a manual procedure using OpenSSL at this link](https://docs.snowflake.com/en/user-guide/key-pair-auth.
The code below creates keypairs, and they work with snowflake/snowflake connector for python. It is lightly modified from examples in the cryptography documents that create other formats.
Questions:
1) The standard python "cryptography" manual cautions about people like me who don't understand cryptography messing around with hazmat libraries. Do you see anything relevant to security problem with the way I am generating keys? Assuming I can securely get them from point of generation to the place where they are used, is this okay?
2) Would it be safer automate by running openssl in a subprocess, using the Snowflake documented procedures?
```python
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend
key = rsa.generate_private_key(
backend=crypto_default_backend(),
public_exponent=65537,
key_size=2048
)
private_key = key.private_bytes(
crypto_serialization.Encoding.PEM,
crypto_serialization.PrivateFormat.PKCS8,
crypto_serialization.NoEncryption()
)
public_key = key.public_key().public_bytes(
crypto_serialization.Encoding.PEM,
crypto_serialization.PublicFormat.SubjectPublicKeyInfo
)
with open("/tmp/pubkey.pub", "wt") as pub:
pub.write(public_key.decode("utf-8"))
with open("/tmp/privkey.p8", "wt") as priv:
priv.write(private_key.decode("utf-8"))
```
|
Are there poor practices in this use of python cryptography package to generate RSA keypair? |
|snowflake-cloud-data-platform|rsa|encryption-asymmetric|python-cryptography| |
null |
Thank you to user @trojanfoe again, who said
"You are overthinking the issue. To move `A` towards `B` at a given speed you need to do nothing more than `auto dir = normalize(B - A); A += dir * (speed * deltaTime);`"
Below is my code modified to incorporate this much simpler solution (this code already has a deltaTime function elsewhere which fixes the intervals between frame rendering.)
```
void Enemy::attemptMove(sf::Vector2f t_playerPos)
{
sf::Vector2f direction = t_playerPos - enemyLocation; // playerPos-enemyPos (direction to player)
float hyp;
// normalising the vector
hyp = sqrtf(abs(direction.x * direction.x) + abs(direction.y * direction.y));
hyp = abs(1.f / hyp); // inverse of pythagoras theorem hypothenuse
direction.x = hyp * direction.x;
direction.y = hyp * direction.y; // sqrt(x^2 + y^2) should equal 1
move(direction);
}
void Enemy::move(sf::Vector2f t_movement)
{
enemyLocation += t_movement; // update enemy location
enemySprite.setPosition(enemyLocation); // set enemy position to updated location
}
``` |
I am new in ARCore and i create a WebXR application with the help of codelab and it works fine but it placed the rectile towards floor i want this rectile should be on wall.
```html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Building an augmented reality application with the WebXR Device API</title>
<link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
<!-- three.js -->
<script src="https://unpkg.com/three@0.126.0/build/three.js"></script>
<script src="https://unpkg.com/three@0.126.0/examples/js/loaders/GLTFLoader.js"></script>
<link rel="stylesheet" type="text/css" href="app.css" />
<script src="utils.js"></script>
</head>
<body>
<div id="enter-ar-info" class="mdc-card demo-card">
<h2>Augmented Reality with the WebXR Device API</h2>
<p>
This is an experiment using augmented reality features with the WebXR Device API.
Upon entering AR, you will be surrounded by a world of cubes.
Learn more about these features from the <a href="https://codelabs.developers.google.com/codelabs/ar-with-webxr">Building an augmented reality application with the WebXR Device API</a> Code Lab.
</p>
<!-- Starting an immersive WebXR session requires user interaction. Start the WebXR experience with a simple button. -->
<a id="enter-ar" class="mdc-button mdc-button--raised mdc-button--accent">
Start augmented reality
</a>
</div>
<div id="unsupported-info" class="mdc-card demo-card">
<h2>Unsupported Browser</h2>
<p>
Your browser does not support AR features with WebXR. Learn more about these features from the
<a href="https://codelabs.developers.google.com/codelabs/ar-with-webxr">Building an augmented reality application with the WebXR Device API</a> Code Lab.
</p>
</div>
<script src="app.js"></script>
<div id="stabilization"></div>
</body>
</html>
```
```javascript
/*
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Query for WebXR support. If there's no support for the `immersive-ar` mode,
* show an error.
*/
(async function() {
const isArSessionSupported = navigator.xr && navigator.xr.isSessionSupported && await navigator.xr.isSessionSupported("immersive-ar");
if (isArSessionSupported) {
document.getElementById("enter-ar").addEventListener("click", window.app.activateXR)
} else {
onNoXRDevice();
}
})();
/**
* Container class to manage connecting to the WebXR Device API
* and handle rendering on every frame.
*/
class App {
/**
* Run when the Start AR button is pressed.
*/
activateXR = async () => {
try {
// Initialize a WebXR session using "immersive-ar".
this.xrSession = await navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ['hit-test', 'dom-overlay'],
domOverlay: { root: document.body }
});
// Create the canvas that will contain our camera's background and our virtual scene.
this.createXRCanvas();
// With everything set up, start the app.
await this.onSessionStarted();
} catch(e) {
console.log(e);
onNoXRDevice();
}
}
/**
* Add a canvas element and initialize a WebGL context that is compatible with WebXR.
*/
createXRCanvas() {
this.canvas = document.createElement("canvas");
document.body.appendChild(this.canvas);
this.gl = this.canvas.getContext("webgl", {xrCompatible: true});
this.xrSession.updateRenderState({
baseLayer: new XRWebGLLayer(this.xrSession, this.gl)
});
}
/**
* Called when the XRSession has begun. Here we set up our three.js
* renderer, scene, and camera and attach our XRWebGLLayer to the
* XRSession and kick off the render loop.
*/
onSessionStarted = async () => {
// Add the `ar` class to our body, which will hide our 2D components
document.body.classList.add('ar');
// To help with working with 3D on the web, we'll use three.js.
this.setupThreeJs();
// Setup an XRReferenceSpace using the "local" coordinate system.
this.localReferenceSpace = await this.xrSession.requestReferenceSpace('local');
// Create another XRReferenceSpace that has the viewer as the origin.
this.viewerSpace = await this.xrSession.requestReferenceSpace('viewer');
// Perform hit testing using the viewer as origin.
this.hitTestSource = await this.xrSession.requestHitTestSource({ space: this.viewerSpace });
// Start a rendering loop using this.onXRFrame.
this.xrSession.requestAnimationFrame(this.onXRFrame);
this.xrSession.addEventListener("select", this.onSelect);
}
/** Place a sunflower when the screen is tapped. */
onSelect = () => {
if (window.sunflower) {
const clone = window.sunflower.clone();
clone.position.copy(this.reticle.position);
this.scene.add(clone)
const shadowMesh = this.scene.children.find(c => c.name === 'shadowMesh');
shadowMesh.position.y = clone.position.y;
}
}
/**
* Called on the XRSession's requestAnimationFrame.
* Called with the time and XRPresentationFrame.
*/
onXRFrame = (time, frame) => {
// Queue up the next draw request.
this.xrSession.requestAnimationFrame(this.onXRFrame);
// Bind the graphics framebuffer to the baseLayer's framebuffer.
const framebuffer = this.xrSession.renderState.baseLayer.framebuffer
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, framebuffer)
this.renderer.setFramebuffer(framebuffer);
// Retrieve the pose of the device.
// XRFrame.getViewerPose can return null while the session attempts to establish tracking.
const pose = frame.getViewerPose(this.localReferenceSpace);
if (pose) {
// In mobile AR, we only have one view.
const view = pose.views[0];
const viewport = this.xrSession.renderState.baseLayer.getViewport(view);
this.renderer.setSize(viewport.width, viewport.height)
// Use the view's transform matrix and projection matrix to configure the THREE.camera.
this.camera.matrix.fromArray(view.transform.matrix)
this.camera.projectionMatrix.fromArray(view.projectionMatrix);
this.camera.updateMatrixWorld(true);
// Conduct hit test.
const hitTestResults = frame.getHitTestResults(this.hitTestSource);
// If we have results, consider the environment stabilized.
if (!this.stabilized && hitTestResults.length > 0) {
this.stabilized = true;
document.body.classList.add('stabilized');
}
if (hitTestResults.length > 0) {
const hitPose = hitTestResults[0].getPose(this.localReferenceSpace);
// Update the reticle position
this.reticle.visible = true;
this.reticle.position.set(hitPose.transform.position.x, hitPose.transform.position.y, hitPose.transform.position.z)
this.reticle.updateMatrixWorld(true);
}
// Render the scene with THREE.WebGLRenderer.
this.renderer.render(this.scene, this.camera)
}
}
/**
* Initialize three.js specific rendering code, including a WebGLRenderer,
* a demo scene, and a camera for viewing the 3D content.
*/
setupThreeJs() {
// To help with working with 3D on the web, we'll use three.js.
// Set up the WebGLRenderer, which handles rendering to our session's base layer.
this.renderer = new THREE.WebGLRenderer({
alpha: true,
preserveDrawingBuffer: true,
canvas: this.canvas,
context: this.gl
});
this.renderer.autoClear = false;
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// Initialize our demo scene.
this.scene = DemoUtils.createLitScene();
this.reticle = new Reticle();
this.scene.add(this.reticle);
// We'll update the camera matrices directly from API, so
// disable matrix auto updates so three.js doesn't attempt
// to handle the matrices independently.
this.camera = new THREE.PerspectiveCamera();
this.camera.matrixAutoUpdate = false;
}
};
window.app = new App();
```
I want to place rectile towards wall not on floor my example work very well on floor but it is not working towards wall. How to place object on wall? |
null |
I am implementing user authorization using Google using next auth.
The logic is as follows:
1. The user clicks on the login button using Google, after which he is
taken to a page with an account selection.
2. After selecting an account, it is returned back to the page.
3. When the page is rendered, the following useEffect is executed:
```
const { data: session } = useSession();
const dispatch = useDispatch<any>();
useEffect(() => {
console.log(session);
if (session) {
dispatch(
logInWithGoogle({
type: "google",
email: session?.user?.email,
name: session?.user?.name,
socialID: session?.user?.id,
})
);
console.log("qwe");
}
}, [session]);
```
4. *loginWithGoogle* sends a request to the server, and most
importantly, RECEIVES a response.
```
export const logInWithGoogle = createAsyncThunk("user/logInWithGoogle", async (data: loginWithGoogleData) => {
const formData = new FormData();
formData.append("type", `${data.type}`);
formData.append("email", `${data.email}`);
formData.append("name", `${data.name}`);
formData.append("socialID", `${data.socialID}`);
const response = await serviceFetch.post("/auth/social-networks", undefined, formData);
const res = await response.json();
if (res.result && !Object.keys(res.errors).length) {
updateTokenStorage(res.data.token);
console.log(res);
data.router.replace("/profile");
}
return res;
});
```
But the data in the storage itself appears only after the page is reloaded, why is that? The session is available immediately after authorization. |
Data in global storage appears only after the page is reloaded. Redux |
|reactjs|redux|redux-toolkit|redux-thunk| |
I've just installed Wordpress 6.4.3 & MAMP and managed to edit functions.php and saved my changes.
Twenty Twenty-Four: Theme Functions (functions.php)
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
- Moved wordpress to a new folder
- 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."}
|
JavaScript svg scale issue with matter.js |
|javascript|svg|matter.js| |
null |
Coding a two-dimensional, dynamically allocated array of `int` is a non-trivial task. If you use a _double pointer_, there are significant memory allocation details. In particular, you need to check every allocation attempt, and, if any one fails, back out of the ones that didn't fail, without leaking memory. And, finally, to take a term from the C++ lexicon, you need to provide some equivalent of the _Rule of Three_ functions used by a C++ _RAII_ class.
A two-dimensional array of `int` with `n_rows` and `n_cols` should probably be allocated with a single call to `malloc`:
```lang-c
int* data = malloc(n_rows * n_cols * sizeof int);
```
With this approach, you have to write indexing functions that accept both `row` and `col` subscripts.
The program in the OP, however, takes the _double pointer_ route, and allocates an _array of pointers to int_. The elements in such an array are `int*`. Thus, the argument to the `sizeof` operator must be `int*`.
```lang-c
int** data = malloc(n_rows * sizeof (int*)); // step 1.
```
Afterwards, you run a loop to allocate the columns of each row. Conceptually, each row is an array of `int`, with `malloc` returning a pointer to the first element of each row.
```lang-c
for (size_t r = 0; r < n_rows; ++r)
data[r] = malloc(n_cols * sizeof int); // step 2.
```
The program in the OP errs in step 1.
```lang-c
// from the OP:
ret = (int **)malloc(sizeof(int) * len); // should be sizeof(int*)
```
Taking guidance from the [answer by @Eric Postpischil](https://stackoverflow.com/a/78248309/22193627), this can be coded as:
```lang-c
int** ret = malloc(len * sizeof *ret);
```
The program below, however, uses (the equivalent of):
```lang-c
int** ret = malloc(len * sizeof(int*));
```
#### Fixing memory leaks
The program in the OP is careful to check each call to `malloc`, and abort the allocation process if any one of them fails. After a failure, however, it does not call `free` to release the allocations that were successful. Potentially, therefore, it leaks memory. It should keep track of the row where a failure occurs, and call `free` on the preceding rows. It should also call `free` on the original array of pointers.
There is enough detail to warrant refactoring the code to create a separate header with functions to manage a two-dimensional array. This separates the business of array management from the application itself.
Header `tbx.int_array2D.h`, defined below, provides the following functions.
- _Define_ β `struct int_array2D_t` holds a `data` pointer, along with variables for `n_rows` and `n_cols`.
- _Make_ β Function `make_int_array2D` handles allocations, and returns a `struct int_array2D_t` object.
- _Free_ β Function `free_int_array2D` handles deallocations.
- _Clone_ β Function `clone_int_array2D` returns a _deep copy_ of a `struct int_array2D_t` object. It can be used in initialization expressions, but, in general, should not be used for assignments.
- _Swap_ β Function `swap_int_array2D` swaps two `int_array2D_t` objects.
- _Copy assign_ β Function `copy_assign_int_array2D` replaces the existing value of an `int_array2D_t` object with a _deep copy_ of another. It performs allocation and deallocation, as needed.
- _Move assign_ β Function `move_assign_int_array2D` deallocates an existing `int_array2D_t` object, and replaces it with a _shallow copy_ of another. After assignment, it zeros-out the source.
- _Equals_ β Function `equals_int_array2D` performs a _deep comparison_ of two `int_array2D_t` objects, returning `1` when they are equal, and `0`, otherwise.
```lang-c
#pragma once
// tbx.int_array2D.h
#include <stddef.h>
struct int_array2D_t
{
int** data;
size_t n_rows;
size_t n_cols;
};
void free_int_array2D(
struct int_array2D_t* a);
struct int_array2D_t make_int_array2D(
const size_t n_rows,
const size_t n_cols);
struct int_array2D_t clone_int_array2D(
const struct int_array2D_t* a);
void swap_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b);
void copy_assign_int_array2D(
struct int_array2D_t* a,
const struct int_array2D_t* b);
void move_assign_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b);
int equals_int_array2D(
const struct int_array2D_t* a,
const struct int_array2D_t* b);
// end file: tbx.int_array2D.h
```
With these functions, code for the application becomes almost trivial:
```lang-c
// main.c
#include <stddef.h>
#include <stdio.h>
#include "tbx.int_array2D.h"
size_t ft_strlen(char* str)
{
size_t count = 0;
while (*str++)
count++;
return (count);
}
struct int_array2D_t parray(char* str)
{
size_t len = ft_strlen(str);
struct int_array2D_t ret = make_int_array2D(len, 2);
for (size_t r = ret.n_rows; r--;) {
ret.data[r][0] = str[r] - '0';
ret.data[r][1] = (int)(len - 1 - r);
}
return ret;
}
int main()
{
char* str = "1255555555555555";
struct int_array2D_t ret = parray(str);
for (size_t r = 0; r < ret.n_rows; ++r) {
printf("%d %d \n", ret.data[r][0], ret.data[r][1]);
}
free_int_array2D(&ret);
}
// end file: main.c
```
#### tbx.int_array2D.c
Function `free_int_array2D` has been designed so that it can be used for the normal deallocation of an array, such as happens in function `main`, and also so that it can be called from function `make_int_array2D`, when an allocation fails.
Either way, it sets the `data` pointer to `NULL`, and both `n_rows` and `n_cols` to zero. Applications that use header `tbx.int_array2D.h` can check the `data` pointer of objects returned by function `make_int_array2D` and function `clone_int_array2D`. If it is `NULL`, then the allocation failed.
```lang-c
// tbx.int_array2D.c
#include <stddef.h>
#include <stdlib.h>
#include "tbx.int_array2D.h"
//======================================================================
// free_int_array2D
//======================================================================
void free_int_array2D(struct int_array2D_t* a)
{
for (size_t i = a->n_rows; i--;)
free(a->data[i]);
free(a->data);
a->data = NULL;
a->n_rows = 0;
a->n_cols = 0;
}
//======================================================================
// make_int_array2D
//======================================================================
struct int_array2D_t make_int_array2D(
const size_t n_rows,
const size_t n_cols)
{
struct int_array2D_t a = {
malloc(n_rows * sizeof(int*)),
n_rows,
n_cols
};
if (!n_rows || !n_cols)
{
free(a.data);
a.data = NULL;
a.n_rows = 0;
a.n_cols = 0;
}
else if (a.data == NULL) {
a.n_rows = 0;
a.n_cols = 0;
}
else {
for (size_t i = 0u; i < n_rows; ++i) {
a.data[i] = malloc(n_cols * sizeof(int));
if (a.data[i] == NULL) {
a.n_rows = i;
free_int_array2D(&a);
break;
}
}
}
return a;
}
//======================================================================
// clone_int_array2D
//======================================================================
struct int_array2D_t clone_int_array2D(const struct int_array2D_t* a)
{
struct int_array2D_t clone = make_int_array2D(a->n_rows, a->n_cols);
for (size_t r = clone.n_rows; r--;) {
for (size_t c = clone.n_cols; c--;) {
clone.data[r][c] = a->data[r][c];
}
}
return clone;
}
//======================================================================
// swap_int_array2D
//======================================================================
void swap_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b)
{
struct int_array2D_t t = *a;
*a = *b;
*b = t;
}
//======================================================================
// copy_assign_int_array2D
//======================================================================
void copy_assign_int_array2D(
struct int_array2D_t* a,
const struct int_array2D_t* b)
{
if (a->data != b->data) {
if (a->n_rows == b->n_rows && a->n_cols == b->n_cols) {
for (size_t r = a->n_rows; r--;) {
for (size_t c = a->n_cols; c--;) {
a->data[r][c] = b->data[r][c];
}
}
}
else {
free_int_array2D(a);
*a = clone_int_array2D(b);
}
}
}
//======================================================================
// move_assign_int_array2D
//======================================================================
void move_assign_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b)
{
if (a->data != b->data) {
free_int_array2D(a);
*a = *b;
b->data = NULL;
b->n_rows = 0;
b->n_cols = 0;
}
}
//======================================================================
// equals_int_array2D
//======================================================================
int equals_int_array2D(
const struct int_array2D_t* a,
const struct int_array2D_t* b)
{
if (a->n_rows != b->n_rows ||
a->n_cols != b->n_cols) {
return 0;
}
for (size_t r = a->n_rows; r--;) {
for (size_t c = a->n_cols; c--;) {
if (a->data[r][c] != b->data[r][c]) {
return 0;
}
}
}
return 1;
}
// end file: tbx.int_array2D.c
```
|
How can I get 100 EC2 instances metrics in different regions and account in Amazon managed Prometheus in AWS.. i should get all the metrics disk cpu memory in Grafana.please share me the steps it will be helpful
Not yet tried please guide |
Using Amazon managed Prometheus to get EC2 metrics data in Grafana |
|amazon-web-services|amazon-ec2|prometheus|managed| |
null |
Looks like you're trying to create the directories if your user chooses one of 3 text phrases and the directory doesn't already exist, and complain to your user if they choose something other than the 3 text phrases. I would treat each of those cases separately:
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If ($text -in $AcceptableText)
{
If (!(Test-Path $Path\$text))
{
new-item -ItemType directory -path $Path\$text
}
}
Else
{
write-host "invalid input"
}
Or you could test for the existence of the directory first like this:
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (!(Test-Path $Path\$text))
{
If (($text -in $AcceptableText))
{
new-item -ItemType directory -path $Path\$text
}
Else
{
write-host "invalid input"
}
}
Edit
---
Or, if you want to be tricky and avoid the Test-Path (as suggested by @tommymaynard), you can use the following code (and even eliminate the Try|Catch wrappers if you don't want error checking)
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (($text -in $AcceptableText))
{
try { mkdir -path $Path\$text -ErrorAction Stop } #Change to -ErrorAction Ignore if you remove Try|Catch
catch [System.IO.IOException] { } #Do nothing if directory exists
catch { Write-Error $_ }
}
Else
{
write-host "invalid input"
}
Edit
---
Also worth noting that there are many ways to [Use PowerShell to Create Folders](https://devblogs.microsoft.com/scripting/learn-four-ways-to-use-powershell-to-create-folders/).
|
Sometimes, something may go wrong with `npm install` due to network trouble or something. So if you keep on facing the problem repeatedly, it's better to erase `node_modules folder` and re-run `npm install` command. |
Rendering a component via a ternary or switch statement does not have any effect on how React will render them and whether they get unmounted or not in between renders. It seems your issue comes from both statements having different behavior;
```jsx
{cardValue === 'A' ? <ComponentA/> : <ComponentB>}
````
This is basically if "A", render `ComponentA` and in all other cases, render `ComponentB`.
But your switch statement does something different;
```jsx
switch (cardValue) {
case 'A':
return <ComponentA />;
case 'B':
return <ComponentB />;
default:
return null;
}
```
If "A" render `ComponentA` and if "B", render `ComponentB`, and in all other cases render null. Based on this, I am concluding your `cardValue` is not just "A" or "B", but can be another value as well, or possibly temporarily while switching from "A" to "B". To make both statements equal, you could use this for your switch statement:
```jsx
switch (cardValue) {
case 'A':
return <ComponentA />;
default:
return <ComponentB />;
}
``` |
Sounds like you are looking for this API?
https://aps.autodesk.com/en/docs/data/v2/tutorials/publish-model/
https://aps.autodesk.com/en/docs/data/v2/reference/http/PublishModel/
|
i have a Steam Deck and would like to install GLFW on a Steamdeck, so that VSCode can find the Libary, i use Cmake. I used Cmake on another linux machine with no problems. I think its related to the steam deck and steam os.
I a location in with the following files in usr/lib/cmake/glfw3 :
- glfw3Targets.cmake,
- glfw3Targets-noconfig.cmake,
- glfw3ConfigVersion.cmak,
- glfw3Config.cmake
Also there are two header files in /usr/include/GLFW called:
- glfw3.h
- glfw3native.h
Also i have this so's:
- /usr/lib/libglfw.so
- /usr/lib/libglfw.so.3
- /usr/lib/libglfw.so.3.3
In the main.cpp file the #include \<GLFW/glfw3.h\> do not work.
My Cmake file looks now like this:
```
cmake_minimum_required(VERSION 3.12)
project(test)
# Add executable
add_executable(test src/main.cpp)
# Specify the path to GLFW include directory
set(GLFW_INCLUDE_DIR "/usr/include" CACHE PATH "Path to GLFW include directory")
# Specify the path to GLFW library directory
set(GLFW_LIBRARY_DIR "/usr/lib" CACHE PATH "Path to GLFW library directory")
# Add GLFW include directory
target_include_directories(test PRIVATE ${GLFW_INCLUDE_DIR})
# Link GLFW library to your executable
target_link_libraries(test ${GLFW_LIBRARY_DIR}/libglfw.so)
```
Maybe some one with a better understanding of cmake, c and linux can help me.
Thank you in advance.
I tried different combinations of cmake files with find() and so on. Looked into the internet, and used Chat GPT to find a solution.
Reinstalled with
```
sudo pacman -S glfw-x11
```
glfw again on the steam deck.
EDIT:
Here is the full error when i start the building:
```
[main] Building folder: game_engine all
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all --
[build] ninja: error: '/usr/lib/libglfw.so', needed by 'test', missing and no known rule to make it
[proc] The command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all -- exited with code: 1
[driver] Build completed: 00:00:00.029
[build] Build finished with exit code 1
```
EDIT2:
When i safe the CMakeList.txt i get following message in VSCode:
```
[main] Configuring project: game_engine
[proc] Executing command: /usr/bin/cmake --no-warn-unused-cli -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc -DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++ -S/home/deck/Programming/game_engine -B/home/deck/Programming/game_engine/build -G Ninja
[cmake] Not searching for unused variables given on the command line.
[cmake] -- Configuring done (0.0s)
[cmake] -- Generating done (0.0s)
[cmake] -- Build files have been written to: /home/deck/Programming/game_engine/build
```
Permission of usr/lib/libglfw.so:
with following command: ```ls -l libglfw.so```
lrwxrwxrwx 1 root root 12 Jul 23 2022 libglfw.so -> libglfw.so.3
EDIT3:
if i change my ```target_link_libraries(test ${GLFW_LIBRARY_DIR}/libglfw.so)``` to ```target_link_libraries(test $usr/lib/libglfw.so.3.3)```
Permission is set to: -rwxr-xr-x 1 root root 278200 Jul 23 2022 /usr/lib/libglfw.so.3.3
Permission of /usr/include/GLFW/glfw3.h: -rw-r--r-- 1 root root 215860 Jul 23 2022 glfw3.h
i get this error in the build process:
```
[main] Building folder: game_engine
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all --
[build] [1/2 50% :: 0.022] Building CXX object CMakeFiles/test.dir/src/main.cpp.o
[build] FAILED: CMakeFiles/test.dir/src/main.cpp.o
[build] /usr/bin/g++ -g -std=gnu++11 -MD -MT CMakeFiles/test.dir/src/main.cpp.o -MF CMakeFiles/test.dir/src/main.cpp.o.d -o CMakeFiles/test.dir/src/main.cpp.o -c /home/deck/Programming/game_engine/src/main.cpp
[build] /home/deck/Programming/game_engine/src/main.cpp:3:10: fatal error: GLFW/glfw3.h: No such file or directory
[build] 3 | #include <GLFW/glfw3.h>
[build] | ^~~~~~~~~~~~~~
[build] compilation terminated.
[build] ninja: build stopped: subcommand failed.
[proc] The command: /usr/bin/cmake --build /home/deck/Programming/game_engine/build --config Debug --target all -- exited with code: 1
[driver] Build completed: 00:00:00.054
[build] Build finished with exit code 1
``` |
|javascript|html| |
An error was generated by MicroSoft JET database engine, could not delete from specified tables.
How can i fix this in order to run my program?
I installed the 2017 version of MicroSoft Visual Studio C++, but the issue persisted. I am expecting it to run smoothly and be able to project and to be used by a projector. |
Error generated by MicroSoft JET database, engine could not delete from specified tables |
I have a customer app where they request services. On the screen I'm working on, they can choose up to three dates. However, what I'm having trouble with is I'm unable to append the selected dates to the array and then upload it to the Firestore document. How would you go about this? Should I rewrite my `handleDateCreationTapped()` function to add to my array? Thank you!
```
var firstDayAndTimes: String?
var secondDayAndTimes: String?
var thirdDayAndTimes: String?
// MARK: - Selectors
@objc func handleDateCreationTapped() {
let controller = DateCreationController()
controller.jobService = self.jobService
controller.continueCallback = { [weak self] isSelected in
guard let self = self else { return }
if controller.selectedCardViewCount == 1 {
self.dateContainer.isHidden = false
self.dateContainerView.isHidden = true
self.dateLabel.text = controller.viewModel.selectedDate
self.timeOfDayLabel.text = controller.viewModel.selectTimesOfDay.joined(separator: ", ")
self.dateCounterLabel.text = "1/3"
self.dateStack.spacing = 5
} else if controller.selectedCardViewCount == 2 {
self.dateContainer.isHidden = false
self.secondDateContainer.isHidden = false
self.dateContainerView.isHidden = true
self.dateLabel.text = controller.viewModel.selectedDate
self.timeOfDayLabel.text = controller.viewModel.selectTimesOfDay.joined(separator: ", ")
self.secondDateLabel.text = controller.viewModel.selectedSecondDate
self.secondTimeOfDayLabel.text = controller.viewModel.selectSecondTimesOfDay.joined(separator: ", ")
self.dateCounterLabel.text = "2/3"
self.dateStack.spacing = 5
} else if controller.selectedCardViewCount == 3 {
self.dateContainer.isHidden = false
self.secondDateContainer.isHidden = false
self.thirdDateContainer.isHidden = false
self.dateContainerView.isHidden = true
self.dateLabel.text = controller.viewModel.selectedDate
self.timeOfDayLabel.text = controller.viewModel.selectTimesOfDay.joined(separator: ", ")
self.secondDateLabel.text = controller.viewModel.selectedSecondDate
self.secondTimeOfDayLabel.text = controller.viewModel.selectSecondTimesOfDay.joined(separator: ", ")
self.thirdDateLabel.text = controller.viewModel.selectedThirdDate
self.thirdTimeOfDayLabel.text = controller.viewModel.selectThirdTimesOfDay.joined(separator: ", ")
self.dateCounterLabel.text = "3/3"
self.dateStack.spacing = 5
}
firstDayAndTimes = controller.selectedCardViewCount >= 1 ? (controller.viewModel.selectedDate + " | " + controller.viewModel.selectTimesOfDay.joined(separator: ", ")) : nil
secondDayAndTimes = controller.selectedCardViewCount >= 2 ? (controller.viewModel.selectedSecondDate + " | " + controller.viewModel.selectSecondTimesOfDay.joined(separator: ", ")) : nil
thirdDayAndTimes = controller.selectedCardViewCount == 3 ? (controller.viewModel.selectedThirdDate + " | " + controller.viewModel.selectThirdTimesOfDay.joined(separator: ", ")) : nil
self.navigationController?.popViewController(animated: true)
}
navigationController?.pushViewController(controller, animated: true)
}
@objc func handleConfirm() {
guard let customer = self.customer else {
self.simpleAlert(title: "Error", msg: "Can't fetch your account, try again later.")
return
}
if currentLocationButton.isSelected {
if let currentLocation = locationManager.location {
let latitude = currentLocation.coordinate.latitude
let longitude = currentLocation.coordinate.longitude
let geocoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
if let error = error {
print("Reverse geocoding failed with error: \(error.localizedDescription)")
self.handleJobRequestCreation(customer: customer, fullAddress: "Location not available")
} else if let placemark = placemarks?.first {
print("Placemark data: \(placemark)")
let addressValue = self.constructFullAddress(placemark: placemark)
print("Constructed Address: \(addressValue)")
self.handleJobRequestCreation(customer: customer, fullAddress: addressValue)
} else {
self.handleJobRequestCreation(customer: customer, fullAddress: "Address not found")
}
}
}
} else if !addressContainer.isHidden, let street = addressStreetLabel.text, let description = addressDescriptionLabel.text {
let addressValue = street + ", " + description
self.handleJobRequestCreation(customer: customer, fullAddress: addressValue)
}
}
// MARK: - Helper Functions
func handleJobRequestCreation(customer: Customer, fullAddress: String) {
let customerUid = customer.uid
let fullname = customer.fullname
let username = customer.username
let email = customer.email
let profileImageUrl = customer.profileImageUrl
let jobRequestId = UUID().uuidString
var dayAndTimesArray: [String] = []
if let firstDayAndTimes = firstDayAndTimes {
dayAndTimesArray.append(firstDayAndTimes)
}
if !secondDateContainer.isHidden, let secondDayAndTimes = secondDayAndTimes {
dayAndTimesArray.append(secondDayAndTimes)
}
if !thirdDateContainer.isHidden, let thirdDayAndTimes = thirdDayAndTimes {
dayAndTimesArray.append(thirdDayAndTimes)
}
var data: [String: Any] = [
"id": jobRequestId,
"customerUid": customerUid,
"employeeUid": "",
"fullname": fullname,
"username": username,
"email" : email,
"profileImageUrl": profileImageUrl,
"businessName": self.businessName ?? "",
"businessId": self.companyID ?? "",
"accountId": self.accountId ?? "",
"address": fullAddress,
"dayAndTimesArray": dayAndTimesArray,
"timeConstraints": self.timingConstraintTextView.text ?? "",
"jobDescription": self.needsTextView.text ?? ""
]
if let firstDayAndTimes = firstDayAndTimes {
data["firstDayAndTimes"] = firstDayAndTimes
}
if let secondDayAndTimes = secondDayAndTimes {
data["secondDayAndTimes"] = secondDayAndTimes
}
if let thirdDayAndTimes = thirdDayAndTimes {
data["thirdDayAndTimes"] = thirdDayAndTimes
}
if let jobRequestData = JobRequest(id: jobRequestId, dictionary: data) {
CustomerService.uploadCustomerAndJobRequest(jobRequest: jobRequestData) { error in
if let error = error {
self.simpleAlert(title: "Error", msg: "Unable to upload job details: \(error.localizedDescription)")
return
}
let controller = RequestJobConfirmationController()
self.delegate = controller
self.delegate?.passJobRequest(self, didConfirmJobRequest: jobRequestData)
let nav = UINavigationController(rootViewController: controller)
nav.modalTransitionStyle = .crossDissolve
nav.modalPresentationStyle = .overCurrentContext
self.present(nav, animated: true, completion: nil)
}
} else {
self.simpleAlert(title: "Error", msg: "Failed to create job request.")
}
}
```
------------------------------
I tried to add the values to the document by checking the containers isHidden, but that didn't help. |
Saving Dates Into Array for Uploading to a Firestore Document |
|ios|arrays|swift|google-cloud-firestore| |
null |
you were close with your first approach, you just got the logic a little wrong. the substition removes `list` if it is present in the variable link, meaning the condition will `not` be true if the string list is present. therefore:
`If defined link If /i Not "%link:list=%" == "%link%" goto:Playlist`
Would be the correct logic.
To safely expand user input, it is advisable to perform such comparisons with `Setlocal enabledelayedexpansion` active and using: `If defined link If /i Not "!link:list=!" == "!link!" goto:Playlist` |
By default mongoose will buffer commands; this is to manage the possible intermittent disconnections with MongoDB server.
By default, under the event of a disconnection, mongoose will wait for 10 seconds / 10000 milliseconds before throwing an error. This is what happens in your case. Mongoose throws an error after retrying the given insertion command for 10 seconds.
Therefore the main problem is mongoose could not establish server connection in 10 seconds.
This is something to check further. In order to check this connection issue, there needs to be an error handler provided to the connection statement shown below.
let conn = mongoose.connect("mongodb://localhost:27017/todo")
Thanks to @jqueeny, he has given you a code snippet for doing the same. Once you have trapped this error, the error message would help you to know the reason for failing connection.
The hostname - localhost, specified in the connection string has enough potential for this kind of connection issues. You can see the details of a similar case enclosed here. It suggests to replace localhost with IP address.
[Why can I connect to Mongo in node using 127.0.0.1, but not localhost?][1]
Thanks
WeDoTheBest4You
[1]: https://stackoverflow.com/questions/73133094/why-can-i-connect-to-mongo-in-node-using-127-0-0-1-but-not-localhost |
I am having this error when I am installing yfinance. Any solution on that?
kevin@KevindeMacBook-Air test % pip install yfinance --upgrade --no-cache-dir
Collecting yfinance
Downloading yfinance-0.2.37-py2.py3-none-any.whl.metadata (11 kB)
Requirement already satisfied: pandas>=1.3.0 in ./venv/lib/python3.9/site-packages (from yfinance) (1.5.3)
Requirement already satisfied: numpy>=1.16.5 in ./venv/lib/python3.9/site-packages (from yfinance) (1.24.2)
Requirement already satisfied: requests>=2.31 in ./venv/lib/python3.9/site-packages (from yfinance) (2.31.0)
Collecting multitasking>=0.0.7 (from yfinance)
Downloading multitasking-0.0.11-py3-none-any.whl.metadata (5.5 kB)Collecting lxml>=4.9.1 (from yfinance)
Downloading lxml-5.1.1-cp39-cp39-macosx_10_9_x86_64.whl.metadata (3.5 kB)Collecting appdirs>=1.4.4 (from yfinance)
Downloading appdirs-1.4.4-py2.py3-none-any.whl.metadata (9.0 kB)Requirement already satisfied: pytz>=2022.5 in ./venv/lib/python3.9/site-packages (from yfinance) (2022.7.1)Collecting frozendict>=2.3.4 (from yfinance)
Downloading frozendict-2.4.0-cp39-cp39-macosx_10_9_x86_64.whl.metadata (23 kB)Collecting peewee>=3.16.2 (from yfinance)
Downloading peewee-3.17.1.tar.gz (3.0 MB)3.0/3.0 MB 25.5 MB/s eta 0:00:00Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
Getting requirements to build wheel did not run successfully.exit code: 1[32 lines of output]Traceback (most recent call last):File "/Users/kevin/PycharmProjects/test/venv/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
main()
File "/Users/kevin/PycharmProjects/test/venv/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
json_out['return_val'] = hook(**hook_input['kwargs'])File "/Users/kevin/PycharmProjects/test/venv/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
return hook(config_settings)
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel
return self._get_build_requires(config_settings, requirements=['wheel'])
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires
self.run_setup()File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 487, in run_setup
super().run_setup(setup_script=setup_script)
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 311, in run_setup
exec(code, locals())
File "<string>", line 109, in <module>File "<string>", line 86, in _have_sqlite_extension_support
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py", line 600, in compile
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/unixccompiler.py", line 185, in _compile
self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py", line 1041, in spawn
spawn(cmd, dry_run=self.dry_run, **kwargs)
File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/spawn.py", line 57, in spawn
proc = subprocess.Popen(cmd, env=env)File "/usr/local/Cellar/python@3.9/3.9.1_8/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 947, in initself._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/local/Cellar/python@3.9/3.9.1_8/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1739, in _execute_child
env_list.append(k + b'=' + os.fsencode(v))
File "/usr/local/Cellar/python@3.9/3.9.1_8/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 810, in fsencode
filename = fspath(filename) # Does type-checking of filename.TypeError: expected str, bytes or os.PathLike object, not int[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.error: subprocess-exited-with-error
Getting requirements to build wheel did not run successfully.exit code: 1See above for output.
yfinance version - UNABLE TO INSTALL ANY yfinance version
python version: Python 3.9.1
on Mac
I can install other libraries, but not yfinance. |
Problems with the order in which PDF files are created |
|pdf|ocr|tesseract| |
null |
I have a page in Laravel that has a start date, a deadline, and an end date. I want to calculate and display the final date when I enter the number of days (deadline). I have used Laravel Collective for the controls.
start date:
{!! Form::text('StartDate', jdate($task->StartDate)->format('Y-m-d'), ['class'=>'myform-control]) !!}
deadline:
{!! Form::text('Deadline', null, ['class'=>'myform-control','style'=>'width:50px;']) !!}
<script>
$('#Deadline').change(function()
{
const dval =parseInt($('#Deadline').val());
const StartDate=document.getElementById("StartDate").value;
const startdateToEnglish= StartDate.toEnglishDigit();
const startdateToEngArray = startdateToEnglish.split('-').map(Number);
var inputF = document.getElementById("EndDate");
edate = new persianDate(startdateToEngArray).add('days', dval).format('YYYY-MM-DD');
console.log(startdateToEngArray,dval,edate);
inputF.value = edate;
});
</script>
and end date:
{!! Form::text('EndDate', jdate($task->EndDate)->format('Y-m-d'), ['class'=>'myform-control observer-example','style'=>'width:180px;','old'=>'EndDate']) !!}
I have implemented this template for both the store and edit blades. The event manager works in the store blade, but in the edit blade, it adds a month to the date in addition to the day.
That is, if I enter the value 6 in the deadline, the final date will be one month and 6 days.
I am surprised that the conditions are completely similar and I have copied the codes related to the edit blade from the store blade.
The values displayed in the console are exactly the same, except for the end date |
problem with change event in javascript for Calculate the new date with a deadline |
|javascript|laravel| |
|html|css| |
I have a ksqldbcluster with 2 nodes. Sometimes i might receive an alert from grafana(which i monitor the cluster) that some queries are in error state. When i check the show queries i see that a number of queries have 1 PERSISTENT running and 1 ERROR. I restart first the second ksqdb docker instance. Sometimes is fixed sometimes is not. If is not i restart the first ksqldb docker instance and then is fixed. Any ideas?
version: '3'
services:
ksqldb-server:
container_name: ksqldb-server
hostname: ksqldb.xxxxxxx
network_mode: host
image: confluentinc/ksqldb-server:latest
environment:
KSQL_HOST_NAME: ksqldb.xxxxxxxx
KSQL_BOOTSTRAP_SERVERS: xxxxxx:9093
KSQL_SECURITY_PROTOCOL: SSL
KSQL_LISTENERS: http://xxxxxx:8088,https://xxxxxx:8443
KSQL_KSQL_SCHEMA_REGISTRY_URL: http://xxxxxxxx-as.net:8081,http://xxxxxx:8082
KSQL_SSL_CLIENT_KEY_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_CLIENT_KEY_STORE_PASSWORD: xxxxxx
KSQL_SSL_CLIENT_TRUST_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_CLIENT_TRUST_STORE_PASSWORD: xxxxxxx
KSQL_SERVER_ID: id1
KSQL_STREAMS_NUM_STANDBY_REPLICAS: 1 # Corrected property name
KSQL_LOG4J_ROOT_LOGLEVEL: "ERROR"
KSQL_QUERY_PULL_ENABLE_STANDBY_READS: true
KSQL_HEARTBEAT_ENABLE: true
KSQL_QUERY_PULL_THREAD_POOL_SIZE: "30"
KSQL_LAG_REPORTING_ENABLE: true
KSQL_INTERNAL_LISTENER: http://xxxxxxx:8080
KSQL_SSL_TRUSTSTORE_LOCATION: /etc/kafka/secrets/ksqldb.truststore.jks
KSQL_SSL_TRUSTSTORE_PASSWORD: xxxxxx
KSQL_SSL_KEYSTORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_KEYSTORE_PASSWORD: xxxxxxx
KSQL_JMX_OPTS: -Dcom.sun.management.jmxremote -javaagent:/etc/kafka/secrets/jmx_prometheus_javaagent-0.17.2.jar=4000:/etc/kafka/secrets/ksql.yaml
ports:
- 8088:8088
- 4000:4000
- 8443:8443
volumes:
- /ksqldata/data:/var/lib/ksqldb-server/data
- /ksqldata/newssl/:/etc/kafka/secrets/
ksqldb-cli:
image: confluentinc/ksqldb-cli:latest
container_name: ksqldb-cli
entrypoint: /bin/sh
tty: true # Corrected indentation
telegraf:
image: telegraf
restart: always
volumes:
- ./telegraf.conf:/etc/telegraf/telegraf.conf:ro
- /var/run/docker.sock:/var/run/docker.sock
~
When restarting ksqldb instance the issue is resolved. Maybe i am missing something in my parameters or how to fix the error? |
You should only add an epsilon transition from final states back to the start state.
You seem to have transitions from every state back to the start state. |
Termux does not (yet) appear to support recording directly to mp3 format. To get an mp3, you'll need to convert your recording using ffmpeg.
AWR Wide format has good quality for speech recording.
<!-- language: shell -->
# Begin recording
termux-microphone-record -e awr_wide -f filename.amr
# Stop recording
termux-microphone-record -q
# Convert to mp3
ffmpeg -i filename.amr filename.mp3
|
Here:
```
g++.exe -o bin\Release\GraphicsC++.exe obj\Release\main.o -s ..\..\..\..\Windows\SysWOW64\glu32.dll
```
You are trying to statically link a DLL (glu32.dll). You cannot do that, and your "simple code snippet" does not need OpenGL in any event.
Moreover you cannot normally statically link code built using a different incompatible toolchain. If you do need to link the OpenGL Utility library in your code, you should link the *MinGW provided* export library with the command line switch `-lglu32`. That will cause the _appropriate_ Windows provided DLL to be loaded at runtime.
You should not try to link a specific DLL path - and using a relative path is bound to fail at some time, it rather assumes that your project will always be in the same place relative to the DLL.
Linking the OpenGL Utility library on its own with no other OpenGL support probably won't be useful either - but that is a different issue. |
I'm re-doing a multi-page website I made with Dreamweaver over a decade ago for my Stained glass business. It is old code and I am a do it yourself amateur as a web-site maker, but the site pages look good on browsers, links work, text size ok, images and background graphic look good to me. **I'm trying to get one of the pages to center in browser windows** so I can do that with all pages. The site uses absolute position to arrange the photo images of windows and some text boxes. It uses a table for reference links to different gallery and information areas of the site. It uses the built-in Dreamweaver CSS text for style rules.
I followed a Dreamweaver tutorial on centering the page which basically goes like this:
\</head\>
**\<body\>**
**\<div id ="wrapper"\>**
\<. web page information/code/ html stuff\>
**\*\</div\>**
\</body\>
\</html\>
The CSS goes like this
\<style type="text/css"\>
\<!--
**#wrapper{**
**margin: 0 auto;**
**width: 1240px;**
**}**
This code looks pretty standard from my inquiries but it is not making the page center in a browser window; the page still hugs the left side. The Dreamweaver community forum, dominated by Nancy O'Shea refuses to help unless I learn the Bootstrap code, and I am not ready for that, having spent many, many hours cleaning up errors on current code and changing some style issues and adding new pages etc. I don't know what is causing the problem: absolute positioning?, the table?, my background graphic gif? If a helpful person knows why my attempt to center is failing It would mean a lot to me. If it would help I will post the entire block of code for the page.
\<\< |