instruction stringlengths 0 30k ⌀ |
|---|
|reactjs|typescript|next.js|zustand| |
null |
```
public int SetSerialization(ref _CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION pcpcs)
{
// Convert IntPtr to byte[]
if (pcpcs.rgbSerialization == IntPtr.Zero)
{
byte[] serializedData = new byte[pcpcs.cbSerialization];
Marshal.Copy(pcpcs.rgbSerialization, serializedData, 0, (int)pcpcs.cbSerialization);
pcpcs.rgbSerialization = Marshal.AllocCoTaskMem(serializedData.Length);
Marshal.Copy(serializedData, 0, pcpcs.rgbSerialization, serializedData.Length);
}
return HRESULT.S_OK;
}
```
how to retrieve the username from the \_CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION pcpcs.
not sure how to serialize the input credential to retrieve the username from pcpcs. |
How to convert Kivymd file to APk file |
|python|kivymd| |
My script add fields to a pointlayer. This happens while iterating a polygon layer. For each feature I look for the closest point from a dataset. This point gets written to the :
```
## D.4 Write LAWIS snowprofile layer
lawislayer = QgsVectorLayer('Point?crs = epsg:4326', 'lawisprofiles', 'memory')
lawislayer_path = str(outpath_REL + "lawis_layer.shp")
_writer = QgsVectorFileWriter.writeAsVectorFormat(lawislayer,lawislayer_path,'utf-8',driverName='ESRI Shapefile')
REL_LAWIS_profiles = iface.addVectorLayer(lawislayer_path,"REL_LAWIS_profiles", "ogr")
## D.5 LAWIS snowprofile layer write attribute fields
lawisprovider = REL_LAWIS_profiles.dataProvider()
lawisprovider.addAttributes([QgsField("REL_ID", QVariant.String),#QVariant.String
QgsField("ID", QVariant.Int),
QgsField("NAME", QVariant.String),
QgsField("DATE", QVariant.String),
QgsField("ALTIDUDE", QVariant.Int),
QgsField("ASPECT", QVariant.String),
QgsField("SLOPE", QVariant.Int),
QgsField("SD", QVariant.Int),
QgsField("ECTN1", QVariant.Int),
QgsField("ECTN2", QVariant.Int),
QgsField("ECTN3", QVariant.Int),
QgsField("ECTN4", QVariant.Int),
QgsField("COMMENTS", QVariant.String),
QgsField("PDF", QVariant.String)])
REL_LAWIS_profiles.updateFields()
## get layer for data collection
lawis_Pts = QgsProject.instance().mapLayersByName('REL_LAWIS_profiles')[0]
## look for closest point and get data for fields....
```
In a second step features are added and values get assigned to the fields:
```
## GET FIELD ID FROM lawis_pts
rel_id_idx = feat.fields().lookupField('REL_ID') # feat because inside a for loop of anotehr layer
id_idx = lawis_Pts.fields().lookupField('ID')
name_idx = lawis_Pts.fields().lookupField('NAME')
date_idx = lawis_Pts.fields().lookupField('DATE')
l_alti_idx = lawis_Pts.fields().lookupField('ALTIDUDE')
l_aspect_idx = lawis_Pts.fields().lookupField('ASPECT')
l_slo_idx = lawis_Pts.fields().lookupField('SLOPE')
l_sd_idx = lawis_Pts.fields().lookupField('SD')
l_ectn_idx1 = lawis_Pts.fields().lookupField('ECTN1')
l_ectn_idx2 = lawis_Pts.fields().lookupField('ECTN2')
l_ectn_idx3 = lawis_Pts.fields().lookupField('ECTN3')
l_ectn_idx4 = lawis_Pts.fields().lookupField('ECTN4')
com_idx = lawis_Pts.fields().lookupField('COMMENTS')
pdf_idx = lawis_Pts.fields().lookupField('PDF')
## ADD FEATURES TO lawis_Pts.
lawis_Pts.startEditing()
lawisfeat = QgsFeature()
lawisfeat.setGeometry( QgsGeometry.fromPointXY(QgsPointXY(lawisprofile_long,lawisprofile_lat)))
lawisprovider.addFeatures([lawisfeat])
lawis_Pts.commitChanges()
## CHANGE VALUES OF SELECTED FEATURE
lawis_Pts.startEditing()
for lfeat in selection:
lawis_Pts.changeAttributeValue(lfeat.id(), rel_id_idx, REL_LAWIS_ID)
lawis_Pts.changeAttributeValue(lfeat.id(), id_idx, LAWIS_id)
lawis_Pts.changeAttributeValue(lfeat.id(), name_idx, LAWIS_NAME)
lawis_Pts.changeAttributeValue(lfeat.id(), date_idx, LAWIS_DATE)
lawis_Pts.changeAttributeValue(lfeat.id(), l_alti_idx, LAWIS_ALTIDUDE)
lawis_Pts.changeAttributeValue(lfeat.id(), l_aspect_idx, LAWIS_ASPECT)
lawis_Pts.changeAttributeValue(lfeat.id(), l_slo_idx, LAWIS_SLOPE)
lawis_Pts.changeAttributeValue(lfeat.id(), l_sd_idx, LAWIS_SD)
lawis_Pts.changeAttributeValue(lfeat.id(), l_ectn_idx1, LAWIS_ECTN1)
lawis_Pts.changeAttributeValue(lfeat.id(), l_ectn_idx2, LAWIS_ECTN2)
lawis_Pts.changeAttributeValue(lfeat.id(), l_ectn_idx3, LAWIS_ECTN3)
lawis_Pts.changeAttributeValue(lfeat.id(), l_ectn_idx4, LAWIS_ECTN4)
lawis_Pts.changeAttributeValue(lfeat.id(), com_idx, LAWIS_COMMENTS)
lawis_Pts.changeAttributeValue(lfeat.id(), pdf_idx, LAWIS_PDFlink) lawis_Pts.commitChanges()
```
In the table the layer has 14 fields, but if the values are not written to the fields.
I checked values but no issue there. Then i checked if all fields exists and field Nr 12 does (at least for python) not exist. With this:
```
fields = lawis_Pts.fields()
for field in fields:
print(field.name())
```
I checked right after adding the fields if all fields get added. But there are only 13 fields (REL_ID,ID,NAME,DATE,ALTIDUDE,ASPECT,SLOPE,SD,ECTN1,ECTN2,ECTN3,COMMENTS,PDF). So I found out the problem is ECTN4. Also checken the Idx of ECTN4 by
```
print(l_ectn_idx4)
```
which gave me -1, which means it's not existing. If i But If I remove the layer which is added by the script and then add the layer manually and look for the field it is there also using code. I assume there has to be a problem how I add the layer, but I just can't find the reason for this behavior. I'm thankful for any ideas! |
PyQgis: Attribute field does not get added |
|attributes|gis|updating|pyqgis| |
null |
I've used with success this in one of the `CMakeLists.txt` file:
list(APPEND CMAKE_PREFIX_PATH C:\\ThePath) |
You can turn JDBC escape processing off.
Statement statement = connection.createStatement();
statement.setEscapedProcessing(false);
statement.executeQuery("select REGEXP_REPLACE(Title, '([0-9]{4})$') from mytable");
The `statement.setEscapedProcessing(false)` has no effect on a `PreparedStatement`. |
{"Voters":[{"Id":2802040,"DisplayName":"Paulie_D"},{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":1169519,"DisplayName":"Teemu"}]} |
The page contains a list of products and a list of filters.
I get query params from url from which I request a list of products. In addition, FilterList also requests a list of attributes of products in this category to create filters, which should change the query string in the url and, using a button, request a new list of products via an updated searchParams .
In the FilterList component, the "show products" button should add filtering parameters to the url and trigger a request for a new list of products with the selected parameters without reloading the entire page.
The question is how to call a new request with updated searchParams in RTKq using a button from an internal component?
My code
```
const Products: React.FC = (props) => {
const [searchParams, setSearchParams] = useSearchParams();
const queries: any = {};
for (let entry of searchParams.entries()) {
queries[entry[0]] = entry[1];
}
const { data, isLoading, error } = useGetProductsByCatIdQuery(queries);
const categoryId = Number(searchParams?.get('cat_id'));
return (
<AppLayout>
<Box
component="main"
sx={{ width: { sm: `calc(100% - ${drawerWidth}px)` } }}
>
<ProductsList products={data} isLoading={isLoading} />
<FilterList categoryId={categoryId} queries={queries} />
</Box>
</AppLayout>
);
};
```
in addition
the FilterList component should have a form inside with checkboxes for each attribute, and a button when clicked on which, the state of the selected attributes, should transform searchParams and somehow invoke getting a new products list with the selected parameters. Moreover, if the user just opened page via a link with searchParams in the URL, then the FilterList should transform them into the state of the form for checkboxes. I can’t understand or find any example of how I can organize all this. |
I am unable to build a apllication. Here is my docker file
FROM docker.io/node:16-alpine AS builder
WORKDIR /usr/app
COPY ./ /usr/app
RUN npm install
RUN npm run build
Error message
npm ERR! path /usr/app
npm ERR! command failed
npm ERR! signal SIGKILL
npm ERR! command sh -c -- ng build
|
{"OriginalQuestionIds":[20002503],"Voters":[{"Id":494134,"DisplayName":"John Gordon","BindingReason":{"GoldTagBadge":"python"}}]} |
because the `while()` it produce high CPU usage, how I can run async method but wait until CTRL+C pressed before the program exit?
class Program
{
public static bool isRunning = true;
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
// run async method...
Console.WriteLine("-> Press CTRL+C to Exit");
while (isRunning) { } // <- wait but without this
}
static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
isRunning = false;
Console.WriteLine("CancelKeyPress fired, exit...");
}
} |
C# Console app do not exit until CTRL+C pressed without while loop |
|c#|async-await|console-application| |
In Laravel, UUIDs can be automatically generated for models using the `HasUuids` trait. However, for intermediate tables without a model, you would need to manually generate the UUID when creating an entry. One way to do this is using Laravel's built-in `Str::uuid()` method when inserting data into the table.
```php
DB::table('post_user')->insert([
'id' => (string) Str::uuid(),
'title' => $title,
'body' => $body,
'created_at' => now(),
'updated_at' => now(),
]);
``` |
Sure, it's as easy as:
```haskell
if has('gui_running')
imap <M-BS> <C-W>
cnoremap <M-BS> <C-W>
else
imap <Esc><BS> <C-W>
cnoremap <Esc><BS> <C-W>
endif
```
The trick here is to know, given a hypothetical <kbd>foo</kbd> key, that after pressing a <kbd>Alt</kbd>+<kbd>foo</kbd> combination, many terminals will send an Escape code followed by <kbd>foo</kbd>. Apparently there are exceptions — some terminals do send something that vim can recognize as <kbd>Alt</kbd>. But if a `imap <M-BS> <C-W>` mapping doesn't work for you in terminal, then most likely your terminal sends an Esc instead, so the combination `imap <Esc><BS> <C-W>` should work for you.
You can read more about that in vim documentation by evaluating `:help map-alt-keys`
|
I am currently running Fail2Ban version 0.11.2 on my host machine to monitor and manage access to an Nginx service that is operating within a Docker container. The Nginx logs are bind-mounted from the container to a directory on the host machine, and Fail2Ban is configured to observe this bound directory for any malicious activity. In fail2ban.conf, dbfile option is enabled and dbpurgeage value is increased to 1296000 [seconnds] (15 days).
I'm seeking some insights into an issue I've encountered with Fail2Ban on my server. Specifically, I am seeing inconsistencies in the 'Total banned' count reported by Fail2Ban for my `nginx-bad-request` jail. Despite being aware of numerous IP addresses that should have triggered the fail conditions, the 'Total banned' metric is capped at 10.
When running the `fail2ban-client status` command for the `nginx-bad-request` jail, the output is as follows:
```
$ sudo fail2ban-client status nginx-bad-request
Status for the jail: nginx-bad-request
|- Filter
| |- Currently failed: 0
| |- Total failed: 1
| `- File list: /path/to/log/nginx/access.log
`- Actions
|- Currently banned: 10
|- Total banned: 10
`- Banned IP list: [Redacted IP List]
```
Based on my logs and monitoring, I am confident that the actual number of IPs that should be banned exceeds this figure. However, the reported 'Total banned' does not reflect this higher number, instead showing a limit of 10, which corresponds to the number of currently banned IPs. This is happening to other jails as well.
I'm curious to know if there is a configuration setting that I might be overlooking, or if there's a known limitation within Fail2Ban that could be causing this. Is there a way to ensure that the 'Total banned' count accurately reflects all IPs that have been banned over time, rather than just the current snapshot?
Thank you in advance for your assistance and any advice you can provide! |
Windows Credential Provider - How to retrieve the username from _CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION pcpcs |
|c#|rdp| |
null |
I have a workoing multithreaded mandelbrot implementation. It breaks the workload up into between 1 and 64 threads. No mutex's are required. Here is the worker thread...
```
// Worker thread for processing the Mandelbrot algorithm
DWORD WINAPI MandelbrotWorkerThread(LPVOID lpParam)
{
// This is a copy of the structure from the paint procedure.
// The address of this structure is passed with lParam.
typedef struct ThreadProcParameters
{
int StartPixel;
int EndPixel;
int yMaxPixel;
int xMaxPixel;
uint32_t* BitmapData;
double dxMin;
double dxMax;
double dyMin;
double dyMax;
} THREADPROCPARAMETERS, *PTHREADPROCPARAMETERS;
PTHREADPROCPARAMETERS P;
P = (PTHREADPROCPARAMETERS)lpParam;
// Algorithm obtained from https://en.wikipedia.org/wiki/Mandelbrot_set.
double x0, y0, x, y, xtemp;
int iteration;
// Loop for each pixel in the slice.
for (int Pixel = P->StartPixel; Pixel < P->EndPixel; ++Pixel)
{
// Calculate the x and y coordinates of the pixel.
int xPixel = Pixel % P->xMaxPixel;
int yPixel = Pixel / P->xMaxPixel;
// Calculate the real and imaginary coordinates of the point.
x0 = (P->dxMax - P->dxMin) / P->xMaxPixel * xPixel + P->dxMin;
y0 = (P->dyMax - P->dyMin) / P->yMaxPixel * yPixel + P->dyMin;
// Initial values.
x = 0.0;
y = 0.0;
iteration = 0;
// Main Mandelbrot algorithm. Determine the number of iterations
// that it takes each point to escape the distance of 2. The black
// areas of the image represent the points that never escape. This
// algorithm is supposed to be using complex arithmetic, but this
// is a simplified separation of the real and imaginary parts of
// the point's coordinate. This algorithm is described as the
// naive "escape time algorithm" in the WikiPedia article noted.
while (x * x + y * y <= 2.0 * 2.0 && iteration < max_iterations)
{
xtemp = x * x - y * y + x0;
y = 2 * x * y + y0;
x = xtemp;
++iteration;
}
// When we get here, we have a pixel and an iteration count.
// Lookup the color in the spectrum of all colors and set the
// pixel to that color. Note that we are only ever using 1000
// of the 16777215 possible colors. Changing max_iterations uses
// a different pallette, but 1000 seems to be the best choice.
// Note also that this bitmap is shared by all 64 threads, but
// there is no concurrency conflict as each thread is assigned
// a different region of the bitmap. The user has the option of
// using the original RGB or the new and improved Log HSV system.
if (!bUseHSV)
{
// The old RGB system.
P->BitmapData[Pixel] = ReverseRGBBytes
((COLORREF)(-16777215.0 / max_iterations * iteration + 16777215.0));
}
else
{
// The new HSV system.
sRGB rgb;
sHSV hsv;
hsv = mandelbrotHSV(iteration, max_iterations);
rgb = hsv2rgb(hsv);
P->BitmapData[Pixel] =
(((int)(rgb.r * 255))) +
(((int)(rgb.g * 255)) << 8) +
(((int)(rgb.b * 255)) << 16 );
}
}
// End of thread execution. The return value is available
// to the invoking thread, but we don't presently use it.
return 0;
}
```
and here is the thread dispatcher...
```
// Parameters for each thread.
typedef struct ThreadProcParameters
{
int StartPixel;
int EndPixel;
int yMaxPixel;
int xMaxPixel;
uint32_t* BitmapData;
double dxMin;
double dxMax;
double dyMin;
double dyMax;
} THREADPROCPARAMETERS, *PTHREADPROCPARAMETERS;
// Allocate per thread parameter and handle arrays.
PTHREADPROCPARAMETERS* pThreadProcParameters = new PTHREADPROCPARAMETERS[Slices];
HANDLE* phThreadArray = new HANDLE[Slices];
// MaxPixel is the total pixel count among all threads.
int MaxPixel = (rect.bottom - tm.tmHeight) * rect.right;
int StartPixel, EndPixel, Slice;
// Main thread dispatch loop. Walk the start and end pixel indices.
for (StartPixel = 0, EndPixel = PixelStepSize, Slice = 0;
(EndPixel <= MaxPixel) && (Slice < Slices);
StartPixel += PixelStepSize, EndPixel = min(EndPixel + PixelStepSize, MaxPixel), ++Slice)
{
// Allocate the parameter structure for this thread.
pThreadProcParameters[Slice] =
(PTHREADPROCPARAMETERS)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, sizeof(THREADPROCPARAMETERS));
if (pThreadProcParameters[Slice] == NULL) ExitProcess(2);
// Initialize the parameters for this thread.
pThreadProcParameters[Slice]->StartPixel = StartPixel;
pThreadProcParameters[Slice]->EndPixel = EndPixel;
pThreadProcParameters[Slice]->yMaxPixel = rect.bottom - tm.tmHeight; // Leave room for the status bar.
pThreadProcParameters[Slice]->xMaxPixel = rect.right;
pThreadProcParameters[Slice]->BitmapData = BitmapData; // Bitmap is shared among all threads.
pThreadProcParameters[Slice]->dxMin = dxMin;
pThreadProcParameters[Slice]->dxMax = dxMax;
pThreadProcParameters[Slice]->dyMin = dyMin;
pThreadProcParameters[Slice]->dyMax = dyMax;
// Create and launch this thread.
phThreadArray[Slice] = CreateThread
(NULL, 0, MandelbrotWorkerThread, pThreadProcParameters[Slice], 0, NULL);
if (phThreadArray[Slice] == NULL)
{
ErrorHandler((LPTSTR)_T("CreateThread"));
ExitProcess(3);
}
} // End of main thread dispatch loop.
// Wait for all threads to terminate.
WaitForMultipleObjects(Slices, phThreadArray, TRUE, INFINITE);
// Deallocate the thread arrays and structures.
for (Slice = 0; Slice < Slices; ++Slice)
{
CloseHandle(phThreadArray[Slice]);
HeapFree(GetProcessHeap(), 0, pThreadProcParameters[Slice]);
}
delete[] phThreadArray;
delete[] pThreadProcParameters;
// Refresh the image with the bitmap.
SetDIBitsToDevice(hdc, 0, 0, rect.right, rect.bottom - tm.tmHeight,
0, 0, 0, rect.bottom - tm.tmHeight, BitmapData, &dbmi, 0);
```
If you want to see the whole program, perhaps to compile it and see how it does on your machine, please take a look at https://github.com/alexsokolek2/mandelbrot. |
I have patrol running fine when performing the tests on debug:
```
# this comes from a makefile command I wrote:
patrol test --target integration_test/$(test_path) --dart-define="MODE=test" --dart-define="ENV=local" --dart-define="SUPABASE_ADMIN_TEST_PASSWORD=$(SUPABASE_ADMIN_LOCAL_TEST_PASSWORD)" --verbose -d emulator-5554
```
which ends successfully:
```
...
: BUILD SUCCESSFUL in 7s
: 327 actionable tasks: 6 executed, 321 up-to-date
✓ Completed executing apk with entrypoint test_bundle.dart on emulator-5554 (8.1s)
```
But when performing it by adding the `--release` flag, gradle complains:
```
patrol test --target integration_test/$(test_path) --dart-define="MODE=test" --dart-define="ENV=local" --dart-define="SUPABASE_ADMIN_TEST_PASSWORD=$(SUPABASE_ADMIN_LOCAL_TEST_PASSWORD)" --verbose -d emulator-5554
...
FAILURE: Build failed with an exception.
* What went wrong:
Cannot locate tasks that match ':app:assembleReleaseAndroidTest' as task 'assembleReleaseAndroidTest' not found in project ':app'.
* Try:
> Run gradlew tasks to get a list of available tasks.
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Get more help at https://help.gradle.org
```
Here is my `app/build.gradle`
```
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
namespace "net.xxx.xxx.xxx"
compileSdk flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "net.xxx.xxxx.xx"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdkVersion 21
multiDexEnabled true
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "pl.leancode.patrol.PatrolJUnitRunner"
testInstrumentationRunnerArguments clearPackageData: "true"
}
testOptions {
execution "ANDROIDX_TEST_ORCHESTRATOR"
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
flutter {
source '../..'
}
dependencies {
androidTestUtil "androidx.test:orchestrator:1.4.2"
implementation 'com.android.support:multidex:1.0.3'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}
```
and my pubspec:
```
name: xxxx_zzzz
description: xxxx xxxx
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.1.0+01
environment:
sdk: '>=3.1.0 <4.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
supabase_flutter: ^1.7.0
flutter_dotenv: ^5.0.2
table_calendar: ^3.0.0
syncfusion_flutter_pdfviewer: ^22.2.12
flutter_launcher_icons: ^0.13.1
firebase_core: ^2.10.0
firebase_messaging: ^14.4.1
mocktail: ^1.0.0
week_of_year: ^2.0.0
supabase_auth_ui: ^0.2.1
dart_dotenv: ^1.0.1
firebase_crashlytics: ^3.3.5
event_bus: ^2.0.0
url_launcher: ^6.1.14
package_info: ^2.0.2
flutter_local_notifications: ^15.1.1
jwt_decoder: ^2.0.1
pub_semver: ^2.1.4
flutter_markdown: ^0.6.18+2
timezone: ^0.9.2
infinite_scroll_pagination: ^4.0.0
intl: ^0.18.1
dev_dependencies:
patrol: ^3.6.1
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/.local.env
- assets/.test.env
- assets/.prod.env
- assets/.staging.env
flutter_launcher_icons:
android: true
ios: true
image_path_android: "assets/images/logo_android.png"
adaptive_icon_background: "#ffffff"
adaptive_icon_foreground: "assets/images/logo_android.png"
image_path_ios: "assets/images/logo_ios.png"
patrol:
app_name: XXX xxxx
android:
package_name: net.xxx.xxxx
ios:
bundle_id: net.xxx.xxx
```
and some doctor analysis:
```
$ flutter doctor 130
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.19.5, on macOS 14.0 23A344 darwin-arm64, locale en-ES)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 15.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2023.3.6)
[✓] Connected device (4 available)
[✓] Network resources
• No issues found!
```
```
$ patrol doctor 130
Patrol doctor:
Patrol CLI version: 2.7.0
Flutter command: flutter
Flutter 3.19.5 • channel stable
Android:
• Program adb found in /Users/zzz/Library/Android/sdk/platform-tools/adb
• Env var $ANDROID_HOME set to /Users/zzz/Library/Android/sdk
iOS / macOS:
• Program xcodebuild found in /usr/bin/xcodebuild
• Program ideviceinstaller found in /opt/homebrew/bin/ideviceinstaller
``` |
patrol does not run the tests when using --release flag |
|flutter|flutter-patrol| |
{"Voters":[{"Id":14853083,"DisplayName":"Tangentially Perpendicular"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":4902099,"DisplayName":"hcheung"}]} |
I'm pretty new to Blazor myself, but this was one of the first questions that occurred to me and I think I have a better solution.
The `IServiceProvider` automagically knows how to provide the [`IHostApplicationLifetime`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.ihostapplicationlifetime). This exposes a `CancellationToken` representing graceful server shutdown. Inject the application lifetime into your component base and use [`CreateLinkedTokenSource`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.createlinkedtokensource) to create a CTS that you can cancel when the component is disposed:
```C#
public abstract class AsyncComponentBase : ComponentBase, IDisposable
{
[Inject]
private IHostApplicationLifetime? Lifetime { get; set; }
private CancellationTokenSource? _cts;
protected CancellationToken Cancel => _cts?.Token ?? CancellationToken.None;
protected override void OnInitialized()
{
if(Lifetime != null)
{
_cts = CancellationTokenSource.CreateLinkedTokenSource(Lifetime.ApplicationStopping);
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
if(_cts != null)
{
_cts.Cancel();
_cts.Dispose();
_cts = null;
}
}
}
``` |
When I have opened my Unreal Engine project in CLion, it warns me: "Project is not configurated".
[![][1]][1]
I suppose it is why autocompletes does not work.
All toolchains is my IDE seems to be set up properly:
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
Also I have noticed that is some cases the "Project is not configured" message does not appear even is to open the project for the first time ([example][5]).
[1]: https://i.stack.imgur.com/FDjFB.png
[2]: https://i.stack.imgur.com/hhWSY.png
[3]: https://i.stack.imgur.com/NA4BU.png
[4]: https://i.stack.imgur.com/Lkvlx.png
[5]: https://www.youtube.com/watch?v=fetFJUsfY2c&t=379s |
How to solve "Project is not configured" problem when opening the Unreal Engine project in CLion? |
|c++|clion|unreal-engine4| |
I'm programming a simple 'game' that is just a block that can jump around. I placed a wall, but now the character phases through when moving to the right, but the collision works when going to the right.
Every other part of this is fine. the willImpactMovingLeft function works just fine and should be a mirror of willImpactMovingRight, but right doesn't work.
simple working code for this example:
```
<!DOCTYPE html>
<html>
<body>
<div id="cube" class="cube"></div>
<div id="ground1" class="ground1"></div>
<div id="ground2" class="ground2"></div>
<script>
var runSpeed = 5;var CUBE = document.getElementById("cube");var immovables = ["ground1", "ground2"];let Key = {pressed: {},left: "ArrowLeft",right: "ArrowRight",isDown: function (key){return this.pressed[key];},keydown: function (event){this.pressed[event.key] = true;},keyup: function (event){delete this.pressed[event.key];}}
window.addEventListener("keyup", function(event) {Key.keyup(event);});
window.addEventListener("keydown", function(event) {Key.keydown(event);});
setInterval(()=>{
if (Key.isDown(Key.left)){
if(willImpactMovingLeft("cube", immovables)!=false){
cube.style.left = willImpactMovingLeft("cube", immovables)+"px";
}else{
cube.style.left = CUBE.offsetLeft - runSpeed +"px";
}
}
if (Key.isDown(Key.right)){
if(willImpactMovingRight("cube", immovables)!=false){
cube.style.left = willImpactMovingRight("cube", immovables)+"px";
}else{
cube.style.left = CUBE.offsetLeft + runSpeed +"px";
}
}
}, 10);
function willImpactMovingLeft(a, b){
var docA = document.getElementById(a);
var docB = document.getElementById(b[0]);
for(var i=0;i<b.length;i++){
docB = document.getElementById(b[i]);
if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check
if(docA.offsetLeft+docA.offsetWidth>docB.offsetLeft+runSpeed){
if(docA.offsetLeft-runSpeed<docB.offsetLeft+docB.offsetWidth){
return docB.offsetLeft+docB.offsetWidth;
}
}
}
}
return false;
}
function willImpactMovingRight(a, b){
var docA = document.getElementById(a);
var docB = document.getElementById(b[0]);
for(var i=0;i<b.length;i++){
docB = document.getElementById(b[i]);
if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check
if(docA.offsetLeft>docB.offsetWidth+docB.offsetLeft-runSpeed){
if(docA.offsetLeft+docA.offsetWidth+runSpeed<=docB.offsetLeft){
CUBE.textContent = "WIMR";
return docB.offsetLeft-docA.offsetWidth;
}
}
}
}
return false;
}
</script><style>.cube{height:50px;width:50px;background-color:red;position:absolute;top:500px;left:500px;}.ground1{height:10px;width:100%;background-color:black;position:absolute;top:600px;left:0;}.ground2{height:150px;width:10px;background-color:black;position:absolute;top:450px;left:700px;}</style></body></html>```
it looks like a lot, but the only problem is the last if statement. Even when the condition is true, it still skips the return number and returns false. Any idea why?
Edit: simplified the code as much as I could.
P.S. **I CANNOT USE THE CONSOLE, I AM ON A MANAGED COMPUTER** |
You do not see the list of elements because you are not using the naming correctly for the CarModelVariant model list.
By default, the variable that stores this list is **object_list**.
That is, if you want to iterate over the CarModelVariant list, you should use the following construction
```
{% for variant in object_list %}
<li>{{ variant }}</li>
{% endfor %}
```
if you want to use your variable for the list, you must specify the **context_object_name** attribute
```
class CarModelVariantView(ListView):
context_object_name = 'data'
```
**UPD**
Using attributes in classes with capital letters is considered bad form. |
I have written two blocks of R-code. I believe that they should both do exactly the same thing - except that one uses a for-loop approach and one uses the sapply function. However, they produce slightly different results. Does anyone know what is causing the slight differences here? Interestingly, both methods produce the same value for the first elements of the output vectors.
**Method1:**
set.seed(967)
n <- replicate(1000, 200)
ACF2MA <- sapply(n, function(n1) {
acf(arima.sim(n1, model=list(ma=c(0.4))), plot=FALSE)$acf[3]
})
ACF2AR <- sapply(n, function(n1) {
acf(arima.sim(n1, model=list(ar=c(0.45))), plot=FALSE)$acf[3]
})
**Method2:**
ACF2AR1 <- 1:1000
for (i in 1:1000) {
YMA <- arima.sim(n=200, model=list(ma=c(0.4)))
YAR <- arima.sim(n=200, model=list(ar=c(0.45)))
ACF2MA1[i] <- acf(YMA, plot=FALSE)$acf[3]
ACF2AR1[i] <- acf(YAR, plot=FALSE)$acf[3]
}
Many thanks in advance!
I was expecting the exact same results.
|
Another way is to avoid script misusing
I've made a query from the question unscripted and keep its functionality
Mapping
PUT /authors_last_names
{
"mappings": {
"properties": {
"author": {
"type": "text",
"fields": {
"uppercased": {
"analyzer": "uppercase_standard_analyzer",
"type": "text"
},
"lowercased": {
"type": "text",
"analyzer": "edge_ngram_lowercase_standard_analyzer"
}
}
},
"last_name": {
"type": "text",
"fields": {
"uppercased": {
"analyzer": "uppercase_standard_analyzer",
"type": "text"
},
"lowercased": {
"type": "text",
"analyzer": "edge_ngram_lowercase_standard_analyzer"
}
}
}
}
},
"settings": {
"analysis": {
"max_ngram_diff": "6",
"analyzer": {
"lowercase_standard_analyzer": {
"tokenizer": "standard",
"filter": [
"lowercase"
]
},
"edge_ngram_lowercase_standard_analyzer": {
"tokenizer": "standard",
"filter": [
"lowercase",
"edge_ngram_filter"
]
},
"uppercase_standard_analyzer": {
"tokenizer": "standard",
"filter": [
"uppercase"
]
}
},
"filter": {
"edge_ngram_filter": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 5,
"preserve_original": false
}
}
}
}
}
Documents
PUT /authors_last_names/_bulk
{"create":{"_id":1}}
{"author":"joe johnson", "last_name": "johnson"}
{"create":{"_id":2}}
{"author":"jonnas massy"}
{"create":{"_id":3}}
{"last_name": "joachim"}
{"create":{"_id":4}}
{"author": "don dobbs"}
Unscripted Query
GET /authors_last_names/_search?filter_path=hits.hits
{
"query": {
"bool": {
"must_not": [
{
"multi_match": {
"query": "d",
"fields": [
"author.lowercased",
"last_name.lowercased"
],
"analyzer": "lowercase_standard_analyzer"
}
}
]
}
}
}
Response
{
"hits" : {
"hits" : [
{
"_index" : "authors_last_names",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.0,
"_source" : {
"author" : "joe johnson",
"last_name" : "johnson"
}
},
{
"_index" : "authors_last_names",
"_type" : "_doc",
"_id" : "2",
"_score" : 0.0,
"_source" : {
"author" : "jonnas massy"
}
},
{
"_index" : "authors_last_names",
"_type" : "_doc",
"_id" : "3",
"_score" : 0.0,
"_source" : {
"last_name" : "joachim"
}
}
]
}
}
Think like a search engine and not algorithmically
See my answer with [replacing the `scripted_metric` aggregation with the cardinality aggregations][1] as well
[1]: https://stackoverflow.com/questions/78225542/elasticsearch-doc-null-pointer-exception-error-for-scripted-metric-on-date-histo/78239664#78239664 |
|javascript|css|trigonometry| |
i'm currently using JPA buddy in my spring boot application to generate JPA Entities from my sakila database. But when i use this feature JPA buddy alway listed all of database tables and views including system tables and views (here is what on my JPA buddy reverse engineering show https://i.stack.imgur.com/mmAQq.png)
How can i make JPA buddy only list data tables and not system tables.
I expect JPA buddy to only list data tables and not system tables |
I have a socket.io server which listens to sockets:
io.on('connection', (socket) => {
socket.on('myEvent', function(data){
socket.emit('eventReceived', { status: 1 });
});
});
I know that Node.js and Socket.IO is not working in multithreading, so I wonder how to effectively handle multiple clients, sending a myEvent at the same time.
I've read a few things about Clusters. Would it be as easy as just adding the following code infront of my project?
const cluster = require('cluster');
const os = require('os');
const socketIO = require('socket.io');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
//my socket code
}
I've also read a few things about Redis, how would it be useful in such a case? Is it effective on an Raspberry Pi? Would it be possible to create a new thread for each user?
Thanks for any help :) |
I am making a website with the option to change languages. Every time when you refresh the page though, the language you selected returns to the original language.
The code below shows the html and JavaScript code for how this function works:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const langEl = [...document.querySelectorAll(".lang")];
const textEl = document.querySelector(".text");
let chosenLanguage = 'NL';
langEl.forEach((el) => {
el.addEventListener("click", () => {
langEl.map(item => item.classList.contains("active") ? item.classList.remove("active") : false);
el.classList.add("active");
chosenLanguage = el.innerText;
const attr = el.getAttribute("language");
textEl.textContent = data[attr].text;
});
});
var data = {
dutch: {
text: "test test"
},
english: {
text: "test test"
},
spanish: {
text: "prueba prueba"
},
indonesian: {
text: "tes tes"
}
};
<!-- language: lang-css -->
:root {
--secondary-color: #4978ff;
}
.language {
background: #141414;
text-align: center;
padding: 60px 0 50px;
}
.language a {
margin: 0;
text-transform: uppercase;
color: #fff;
text-decoration: none;
padding: 0 15px;
font-weight: bold;
background: #555656;
font-size: 18px;
}
.language a.active {
background: var(--secondary-color);
}
<!-- language: lang-html -->
<p class="text">test test</p>
<div class="language">
<div class="langWrap">
<a href="#" language='dutch' class="lang active">NL</a>
<a href="#" language='english' class="lang">EN</a>
<a href="#" language='spanish' class="lang">ES</a>
<a href="#" language='indonesian' class="lang">ID</a>
</div>
</div>
<!-- end snippet -->
I was wondering if it was possible to store the chose language in the localStorage so that it stays the same after you refresh the page? |
You need to extend the `dayjs` class with the `utc` and `timezone` classes/plugins:
```javascript
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
dayjs.extend(utc);
dayjs.extend(timezone);
```
Refer to docs for more details: https://day.js.org/docs/en/timezone/timezone |
```
from celery import Celery
app = Celery("tasks", broker="pyamqp://guest@localhost//")
@app.task
def add(x: int, y: int) -> int:
return x + y
```
> tasks.py:6: error: Untyped decorator makes function "add" untyped [misc]
Why? |
Untyped decorator makes function "add" untyped [misc] (celery & mypy) |
|python|celery|mypy| |
I would like for screen readers (Narrator, JAWS, NVDA) to read aloud the text of certain labels on my XAML-based windows, so that the sight-impaired user can know the context of the window that they have in the foreground.
I would rather not make these controls a tab stop, since most people will not be using a screen reader, and would not expect the tab control to stop there.
I have been unable to find anything that works so far, and I am thinking I may need to resort to setting the `AutomationProperties.Name` of the top-level window itself to the text I want read aloud.
Any tips/tricks/pointers in the right direction would be much appreciated. |
WinRT + WinUI3 accessibility: How can I get the screen reader to read controls that are not tab stops (e.g. static labels)? |
|accessibility|winrt-xaml| |
null |
null |
null |
null |
null |
You're redefining the "cities" column in your `mutate()` call instead of creating a new "region" column.
Try:
```
df1 <- df %>%
mutate(region = fct_collapse(
cities,
"1" = c("1", "2", "3", "4","5","8"),
"2" = c("10", "24"),
"3" = c("6", "7", "15", "16"),
"4" = c("20", "21", "22", "28", "29"),
"5" = c("9", "17", "18", "19"),
"6" = c("25", "26", "27", "30", "34"),
"7" = c("11", "12", "13", "14"),
"8" = c("23", "31", "32", "33")
))
```
|
I have a regular ASP.NET app, which uses routes and etc. I also want to add WebSockets with database connections to the app, and have come to the conclusion middleware is the best way to do this, but I can not get it to work with the database. This is currently my `WebSocketMiddleware` class:
```
public class WebSocketMiddleware
{
private readonly RequestDelegate next;
private readonly DatabaseService databaseService;
public WebSocketMiddleware(RequestDelegate next, DatabaseService databaseService)
{
this.next = next;
this.databaseService = databaseService;
}
public async Task Invoke(HttpContext context)
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await HandleWebSocketConnection(context, webSocket);
} else
{
Console.WriteLine("Not ws");
await next(context);
}
}
```
and this is the Program:
```
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DatabaseContext>(options =>
options.UseNpgsql("address"));
builder.Services.AddScoped<DatabaseService>();
builder.Services.AddScoped<WebSocketMiddleware>();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowLocalhost",
builder =>
{
builder.WithOrigins("https://localhost:3000")
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
var app = builder.Build();
app.UseCors("AllowLocalhost");
app.UseWebSockets();
app.UseMiddleware<WebSocketMiddleware>();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
```
This is the DatabaseService I am attempting to inject:
```
public class DatabaseService
{
private readonly DatabaseContext databaseContext;
public DatabaseService(DatabaseContext databaseContext)
{
this.databaseContext = databaseContext;
}
// methods //
}
```
I have tried removing and adding WebSocketMiddleware as `AddScoped`, but both fails from their own reasons. If I remove the DatabaseService from the middleware, it works as expected.
Errors:
When adding scoped: 'Unable to resolve service for type Http.RequestDelegate while attempting to activate WebSocketMiddleware'
When removing scoped: 'Cannot resolve scoped service DatabaseService from root provider'
If I remove RequestDelegate from the middleware, I get this error:
'A suitable constructor for type WebSocketMiddleware could not be located'
|
I found a solution for this problem via a custom Inflector. The regular `Rails::Autoloader::Inflector#camelize` ignores its second argument, but incorporating the absolute filepath into the camelization enables me to use both `Gem1::Api` and `Gem2::API`.
```
# config/initializers/autoloaders.rb
class PathnameSuffixInflector
def initialize
@overrides = {}
@max_overrides_depth = 0
end
def camelize(basename, abspath)
return @overrides[basename] || basename.camelize if @max_overrides_depth <= 1
filenames = Pathname.new(abspath).each_filename.to_a[0..-2] + [basename]
@max_overrides_depth.downto(1).each do |suffix_size|
suffix = filenames.last(suffix_size)
return @overrides[suffix] if @overrides.key?(suffix)
end
return basename.camelize
end
def inflect(overrides)
@overrides.merge!(overrides.transform_keys { Pathname.new(_1).each_filename.to_a })
@max_overrides_depth = @overrides.keys.map(&:length).max || 0
end
end
Rails.application.autoloaders.each do |autoloader|
autoloader.inflector = PathnameSuffixInflector.new
autoloader.inflector.inflect("gem2/api" => "API")
end
``` |
|c#|entity-framework-core| |
The `__str__` method should return a string representation of the object. In your case, it returns a tuple, which is incorrect. You need to format the output as a string:
class Card:
def __init__(self, color, number):
self.color = color
self.number = number
def __str__(self):
return f'{self.color} {self.number}'
def __repr__(self):
return f'Card(color={self.color}, number={self.number})'
def main() -> None:
red_cards = [Card('red', i) for i in range(1, 10)]
blue_cards = [Card('blue', i) for i in range(1, 10)]
cards_in_deck = red_cards + blue_cards
for card in cards_in_deck:
print(card) # Uses __str__ method
print(cards_in_deck) # Uses __repr__ method
if __name__ == '__main__':
main()
**Output:**
red 1
red 2
red 3
red 4
red 5
red 6
red 7
red 8
red 9
blue 1
blue 2
blue 3
blue 4
blue 5
blue 6
blue 7
blue 8
blue 9
[Card(color=red, number=1), Card(color=red, number=2), Card(color=red, number=3), Card(color=red, number=4), Card(color=red, number=5), Card(color=red, number=6), Card(color=red, number=7), Card(color=red, number=8), Card(color=red, number=9), Card(color=blue, number=1), Card(color=blue, number=2), Card(color=blue, number=3), Card(color=blue, number=4), Card(color=blue, number=5), Card(color=blue, number=6), Card(color=blue, number=7), Card(color=blue, number=8), Card(color=blue, number=9)] |
Suppose the calculation time of a process is 200 cpu cycles. Meanwhile, the I/O operation is in progress for another process through dma, and after 100 cpu cycles, the end of the I/O operation is notified to the system by an interrupt. If we assume that the execution time of isr is 10 cpu cycles, how much system time do the mentioned operations occupy?
I am not sure of my answer but this is my solution.
The total execution time of the process is equal to the sum of cpu time = 200,I/O time = 100 and ISR time = 10. So the process takes 310 cycles. |
I'm trying to create a bot to automatically invest on Brazilian Certificate of Deposits (CD). These are offered by a specific stock broker but they don't last even 4 seconds. The code below refers to the automatic steps after manually typing login, password and token. When I run the program, when I type the login, before entering the password the website blocks my access. How can I tackle this issue?
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# Investment page URL
investments_url = "https://experiencia.xpi.com.br/renda-fixa/#/emissao-bancaria"
# WebDriver configuration (you need to have ChromeDriver or another driver installed)
driver = webdriver.Chrome()
# Open the browser and manually login if necessary
input("Please login and press Enter to continue...")
# Function to perform the investment process
def perform_investment():
# Navigate to the investments page
driver.get(investments_url)
# Wait for the investments page to load
time.sleep(2)
# Find all available investments in the table
investments_table = driver.find_element_by_css_selector(".sc-bkEOxz.jStPvy.soma-table-body.hydrated")
rows = investments_table.find_elements_by_xpath(".//tr")
# Check each investment
for row in rows:
# Extract investment information
asset = row.find_element_by_xpath(".//td[1]").text
issuer = row.find_element_by_xpath(".//td[2]").text
profitability = float(row.find_element_by_xpath(".//td[3]").text.replace('%', '').replace(',', '.'))
# Check if the investment meets the specified criteria
if "SICREDI" in asset.upper() and profitability > 12.50:
print(f"Investment found: {asset}, Issuer: {issuer}, Profitability: {profitability}%")
# Click the "Invest" button on the table row where the investment was identified
invest_button = row.find_element_by_xpath(".//button[contains(text(),'Investir')]")
invest_button.click()
# Wait for the next page to load
time.sleep(2)
# Fill in the desired quantity (in this example, we fill in with 2)
quantity_input = driver.find_element_by_xpath("//input[@id='input_quantidade']")
quantity_input.send_keys("2")
# Click on "Advance step"
next_button = driver.find_element_by_xpath("//button[contains(text(),'Avançar etapa')]")
next_button.click()
# Click 6 times on the button with the numeral "0" (for electronic signature)
for _ in range(6):
button_0 = driver.find_element_by_xpath("//button[contains(text(),'0')]")
button_0.click()
time.sleep(0.1) # Small interval to ensure clicks are processed
# Click on "Advance step" to finalize the investment
final_next_button = driver.find_element_by_xpath("//button[contains(text(),'Avançar etapa')]")
final_next_button.click()
print("Investment successfully made!")
# No need to continue checking investments after making one
return
# Perform the investment process
perform_investment()
# Close the browser
driver.quit()
```
I was expecting to get to the webpage "https://experiencia.xpi.com.br/renda-fixa/#/emissao-bancaria" and get the investment done as soon as an investment from the bank SICREDI appears, automatically choosing a quantity of 2 and typyng my electronic signature. |
Storing selected language in localStorage |
|javascript|html|jquery|css| |
hey i want to start programming an Arduino esp32 board with micropython so i installed pymakr extension on vscod but then when i wanted to create a project i see this error:
> Error running command pymakr.createProjectPrompt: command 'pymakr.createProjectPrompt' not found. This is likely caused by the extension that contributes pymakr.createProjectPrompt.
[error](https://i.stack.imgur.com/urx6Y.png)
i uninstall and install the extension again but it heppened again i also tried opening a workspace and it didnt help either.
id be thankfull if you tell me whats wrong and how can i solve it. |
trouble with creating a project for Pymakr in vscode |
|visual-studio-code|vscode-extensions|esp32|micropython|arduino-esp32| |
null |
I have created a new project with IntelliJ IDEA Ultimate version 2024.1. This version supports the new Java 22 (openjdk-22) version. But when I reload my Gradle project, it shows this error:
```´
Unsupported Gradle JVM.
Your build is currently configured to use Java 22 and Gradle 8.7.
Possible solutions:
- Use Java 21 as Gradle JVM: Open Gradle settings
- Upgrade to Gradle 8.5 and re-sync
```
AND THIS:
```
FAILURE: Build failed with an exception.
* What went wrong:
BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 66
> Unsupported class file major version 66
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
CONFIGURE FAILED in 69ms
```
Under "project structure" I have selected the installed Java 22 SDK. Also, all Modules are of the SDK Default Language Level.
These are my Gradle properties:
```
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```
and this is my build.kts:
```
plugins {
id("java")
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_22
targetCompatibility = JavaVersion.VERSION_22
}
dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
}
tasks.test {
useJUnitPlatform()
}
``` |
Gradle cannot find installed JDK 22 in IntelliJ |
null |
I'm trying to make a bot with Discord.py and i cant use discord-slash, i tried to install the pip, i will add pics (https://i.stack.imgur.com/6ygwM.png)(https://i.stack.imgur.com/6sBMO.png)(https://i.stack.imgur.com/ci4WB.png)
dont ask about the bot name, it was a discord bot for a Minecraft server originally...
i added the pip install pics up there and the import... |
null |
Within the function `sumAtBis`
int sumAtBis(tree a, int n, int i){
if(i==n){
if(isEmpty(a))
return 0;
else
return root(a);
}
return sumAtBis(left(a),n,i+1)+sumAtBis(right(a),n,i+1);
}
there is no check whether `left( a )` or `right( a )` are null pointers. So the function can invoke undefined behavior.
Actually the function `sumAtBis` is redundant. It is enough to define the function `sumAt` as for example
long long int sumAt( tree a, size_t n )
{
if ( isEmpty( a ) )
{
return 0;
}
else
{
return n == 0 ?
root( a ) :
sumAt( left( a ), n - 1 ) + sumAt( right( a ), n - 1 );
}
}
And correspondingly the call of `printf` will look like
printf( "%lld\n", sumAt( v, n ) );
^^^^
Also using the typedef name `tree`
typedef node * tree;
is not a good idea because you can not define the type `const node *` by means of this typedef name because `const tree` is equivalent to `node * const` instead of the required type `const node *` and this type should be used in the parameter declaration of the function because the function does not change nodes of the tree.
|
What's wrong with this HSQLDB syntax:
```
REGEXP_REPLACE(Title, '([0-9]{4})$')
```
The regular expression is intended to remove 4 digits in parentheses at the end of a string. Thanks for taking a look.
I tried various escaping with no success. Apparently the curly braces are being intercepted by JDBC as an escape sequence of its own. |
JDBC escape processing and HSQLDB regular expression syntax |
Have you added names on the urls on your project?
urlpatterns = [
path('', views.home, name="home"),
path('room/<str:pk>/', views.room, name="room")
]
Please, ensure that your URLs project on the route room have a reference name. Check this documentation https://docs.djangoproject.com/en/5.0/topics/http/urls/#examples
|
I am using node.js and I have a task that runs every second like so:
let queue = ["Sample Data 1", "Sample Data 2"]
const job = schedule.scheduleJob('*/1 * * * * *', function () {
console.log("Checking the queue...")
if (queue.length > 0) {
wss.broadcast(JSON.stringify({
data: queue[0]
}));
setTimeout(() => {
queue.shift();
}, queue[0].duration);
}
});
I am wondering how I can make it so that the timeout must finish before the next queue check. Could I use a de-bounce, or is there a better way? |
How can I schedule a task every second but wait with setTimeout() before continuing to the next task? |
|javascript|node.js|schedule| |
The transposition table uses keys from the position of player 0 and player 1 from bitboards and includes the player turn at the end, I did that to guarantee unique keys for all states. But this seems to be slow because of fmt.Sprintf.
I have two functions where I store and retrieve, and in each of them I build the key and do a check or store.
type TTFlag int64
const (
Exact TTFlag = 0
UpperBound TTFlag = 1
LowerBound TTFlag = 2
)
type TTEntry struct {
BestScore float64
BestMove int
Flag TTFlag
Depth int
IsValid bool
}
type Solver struct {
NodeVisitCounter int
TTMapHitCounter int
TTMap map[string]TTEntry
}
func NewSolver() *Solver {
return &Solver{
NodeVisitCounter: 0,
TTMapHitCounter: 0,
TTMap: make(map[string]TTEntry),
}
}
func (s *Solver) StoreEntry(p *Position, entry TTEntry) {
key := fmt.Sprintf("%d:%d:%d", p.Bitboard[0], p.Bitboard[1], p.PlayerTurn)
s.TTMap[key] = entry
}
func (s *Solver) RetrieveEntry(p *Position) TTEntry {
key := fmt.Sprintf("%d:%d:%d", p.Bitboard[0], p.Bitboard[1], p.PlayerTurn)
if entry, exists := s.TTMap[key]; exists {
s.TTMapHitCounter++
return entry
}
return TTEntry{}
}
What can I do to optimize this further? How can I make better keys without the use of fmt.Sprintf and string concatenation? |
Wavesurfer v6.6.4 invalid progress bar |
|javascript|wavesurfer.js| |
null |
So i'm having a quite simple problem which doesnt seem to be trivial to solve. I found LibVLCSharp for controlling my videos from my c# program, which is exactly what i wanted. But i find the documentation to be quite complicated or non-existant.
I want to accomplish playing up to 4 different videos on 4 installed Monitors on one windows machine. I had a working example for 2 monitors right here:
string[] vlcParameter1 = new string[]
{
@"--video-x=-1024",
@"--video-y=1",
@"--video-on-top",
@"--fullscreen",
@"--no-one-instance"
};
string[] vlcParameter2 = new string[]
{
@"--video-x=1",
@"--video-y=1",
@"--video-on-top",
@"--fullscreen",
@"--no-one-instance"
};
using var libvlc1 = new LibVLC(enableDebugLogs: true, vlcParameter1);
using var libvlc2 = new LibVLC(enableDebugLogs: true, vlcParameter2);
using var media1 = new Media(libvlc1, new Uri(@"C:\sample.mp4"));
using var media2 = new Media(libvlc1, new Uri(@"C:\sample.mp4"));
using var mediaplayer1 = new MediaPlayer(media1);
using var mediaplayer2 = new MediaPlayer(media2);
mediaplayer1.Fullscreen = false;
mediaplayer2.Fullscreen = false;
mediaplayer1.Play();
mediaplayer2.Play();
Thats pretty simple but the FAQ from the libvlcsharp github page says to NEVER instanciate more than _one_ LibVLC object. Which i'm doing there. Its working fine but i dont know about the problems.
To avoid this, i tried to use the `Media.AddOption` like this:
media1.AddOption(":video-x=-1024");
media1.AddOption(":video-y=1");
But that didnt work either.
Is there another simple way to display multiple videos on multiple screens?
|
playing multiple videos with libvlcsharp on multiple monitors |
|c#|video|vlc|libvlcsharp| |
Can the background remain consistent with the buttons as their number reduces from three to two to one?
I want the background to resize to fit the new width when three columns become two and then one, now it just stays fixed with three columns.
I want the background to stay with the buttons.
When the buttons go from 3 to 2 to 1, I want the background to stay attached to the buttons.
I want the background to stay behind the buttons.
Code: https://jsfiddle.net/42Lowjt7/4/
From 3
[Image](https://i.stack.imgur.com/Xs8Gn.png)
To 2
[Image](https://i.stack.imgur.com/2yPQb.png)
To 1
[Image][1]
I tried using media queries, but I am not sure if that would work in the code.
```
.buttonContainerA {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
max-width: 476px;
gap: 10px;
background: linear-gradient(45deg,
transparent,
transparent 7px,
rgb(113, 121, 126) 7px,
rgb(113, 121, 126) 7.5px,
transparent 7.5px,
transparent 10px),
linear-gradient(-45deg,
transparent,
transparent 7px,
rgb(113, 121, 126) 7px,
rgb(113, 121, 126) 7.5px,
transparent 7.5px,
transparent 10px);
background-size: 10px 10px;
}
```
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
html,
body {
margin: 0;
padding: 0;
}
body {
background: #121212;
padding: 0 8px 0;
}
.outer-container {
display: flex;
min-height: 100vh;
/*justify-content: center;
flex-direction: column;*/
}
.containerB {
/*display: flex;
justify-content: center;
align-content: center;
padding: 8px 8px;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
overflow: auto;*/
/* Enable scroll if needed */
/*display: flex;
min-height: 100vh;
justify-content: center;
flex-direction: column;
margin-top: auto;*/
margin: auto;
}
.modal-contentA {
/*display: flex;
flex-wrap: wrap;
flex-direction: column;*/
/* added*/
/*min-height: 100%;*/
margin: auto;
/*justify-content: center;
align-content: center;*/
}
.buttonContainerA {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
max-width: 476px;
gap: 10px;
/*background: red;*/
background: linear-gradient(45deg,
transparent,
transparent 7px,
rgb(113, 121, 126) 7px,
rgb(113, 121, 126) 7.5px,
transparent 7.5px,
transparent 10px),
linear-gradient(-45deg,
transparent,
transparent 7px,
rgb(113, 121, 126) 7px,
rgb(113, 121, 126) 7.5px,
transparent 7.5px,
transparent 10px);
background-size: 10px 10px;
}
.playButtonA {
flex-basis: 152px;
/* width of each button */
margin: 0;
/* spacing between buttons */
cursor: pointer;
}
.btn-primaryA {
color: #fff;
background-color: #0d6efd;
border-color: #0d6efd;
}
.btnA {
display: inline-block;
font-weight: 400;
line-height: 1.5;
text-align: center;
text-decoration: none;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
background-color: #0d6efd;
border: 1px solid transparent;
box-sizing: border-box;
padding: 6px 12px;
font-size: 16px;
border-radius: 4px;
transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
font-family: "Poppins", sans-serif;
font-weight: 500;
font-style: normal;
}
.btnq {
-webkit-appearance: none;
appearance: none;
height: 80px;
width: 80px;
padding: 0;
color: inherit;
border: none;
font: inherit;
cursor: pointer;
outline: inherit;
margin: auto;
}
.btnA:hover {
background-color: #0056b3;
color: #ffffff;
}
.btnA:focus {
color: #fff;
background-color: #0b5ed7;
border-color: #0a58ca;
/*box-shadow: 0 0 0 2px rgb(255 0 0 / 100%)*/
}
.exitB {
position: relative;
margin: 10px auto 0;
inset: 0 0 0 0;
width: 47px;
height: 47px;
background: black;
border-radius: 50%;
border: 5px solid red;
display: flex;
align-items: center;
justify-content: center;
/*margin: auto;*/
cursor: pointer;
}
.exitB::before,
.exitB::after {
content: "";
position: absolute;
width: 100%;
height: 5px;
background: red;
transform: rotate(45deg);
}
.exitB::after {
transform: rotate(-45deg);
}
<!-- language: lang-html -->
<div class="outer-container ">
<div class="containerB">
<div class="modal-contentA">
<div class="buttonContainerA">
<button data-destination="#ba" class="playButtonA btn-primaryA btnA">Listening</button>
<button data-destination="#bb" class="playButtonA btn-primaryA btnA">Live Performance</button>
<button data-destination="#bc" class="playButtonA btn-primaryA btnA">On Loop</button>
<button data-destination="#bd" class="playButtonA btn-primaryA btnA">Audio Visual</button>
<button data-destination="#be" class="playButtonA btn-primaryA btnA">Lyric Video</button>
<button data-destination="#bf" class="playButtonA btn-primaryA btnA">Music Video</button>
<button data-destination="#bg" class="playButtonA btn-primaryA btnA">From The Vault</button>
<button data-destination="#bh" class="playButtonA btn-primaryA btnA">Mystery Box</button>
<button data-destination="#bi" class="playButtonA btn-primaryA btnA">Cover</button>
<button data-destination="#bj" class="playButtonA btn-primaryA btnA">Remix</button>
<button data-destination="#bk" class="playButtonA btn-primaryA btnA">Instrumental</button>
<button data-destination="#bl" class="playButtonA btn-primaryA btnA">Extended Mix</button>
<button data-destination="#bm" class="playButtonA btn-primaryA btnA">Duet</button>
<button data-destination="#bn" class="playButtonA btn-primaryA btnA">Acoustic</button>
<button data-destination="#bo" class="playButtonA btn-primaryA btnA">Rework</button>
</div>
<button class="exitB exit" type="button" title="Exit" aria-label="Close"></button>
</div>
</div>
</div>
<!-- end snippet -->
[1]: https://i.stack.imgur.com/ZBra1.png |
You can curate the input to json_normalise yourself by using a list comprehension like this:
```pd.json_normalize([v['Conversion'] for k, v in input['data'].items()])``` |
I want to have ticker like non stop animation without any gap from right to left in my app i could not get such animation after trying too much, kindly anyone guide me what is the problem in my code
I tried to get ticker like non stop animation but could not get such animation
```
const windowWidth = Dimensions.get("window").width;
const animatedValue = useRef(new Animated.Value(0)).current;
useEffect(() => {
if (activeViewIndex === 1) {
const animation = Animated.loop(
Animated.timing(animatedValue, {
toValue: 2,
duration: animationDuration,
easing: Easing.linear,
useNativeDriver: true,
})
);
animation.start();
} else {
animatedValue.stopAnimation();
animatedValue.setValue(0);
}
}, [activeViewIndex, animatedValue]);
<Animated.View
style={[
styles.animationContainer,
{
transform: [
{
translateX: animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [windowWidth, -windowWidth],
}),
},
],
},
]}
>
{images.map((image) => (
<ImageContainer source={image} />
))}
</Animated.View>
``` |
|operating-system|cpu|interrupt|dma| |
{"OriginalQuestionIds":[12933964],"Voters":[{"Id":550094,"DisplayName":"Thierry Lathuille","BindingReason":{"GoldTagBadge":"python"}}]} |
You set variables in `base.less` and include `main.less`...
Also, if you are using `vite`, and want the `less` varables to be awailables in all components, set this in `vite.config.ts`:
```
// https://vitejs.dev/config/
export default defineConfig({
css: {
preprocessorOptions: {
less: {
additionalData: '@import "@/assets/less/variables.less";',
},
},
},
})
``` |
```
login.components.ts:
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from "@angular/forms";
import {AuthService} from "../../service/auth.service";
import {TokenStorageService} from "../../service/token-storage.service";
import {Router, RouterLink} from "@angular/router";
import {NotificationService} from "../../service/notification.service";
import {error} from "@angular/compiler-cli/src/transformers/util";
import {MatFormField, MatLabel} from "@angular/material/form-field";
import {MatInput} from "@angular/material/input";
import {MatButton} from "@angular/material/button";
@Component({
selector: 'app-login',
standalone: true,
imports: [
ReactiveFormsModule,
MatFormField,
MatLabel,
MatInput,
MatButton,
RouterLink
],
templateUrl: './login.component.html',
styleUrl: './login.component.css'
})
export class LoginComponent implements OnInit{
constructor(
public loginForm: FormGroup,
private authService: AuthService,
private tokenStorage: TokenStorageService,
private notificationService: NotificationService,
private router: Router,
private fb: FormBuilder
)
{
if(this.tokenStorage.getUser()) {
this.router.navigate(['main'])
}
}
ngOnInit(): void {
this.loginForm = this.createLoginForm();
}
createLoginForm(): FormGroup{
return this.fb.group({
username: ['', Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
}
)
}
submit(): void {
this.authService.login({
username: this.loginForm.value.username,
password: this.loginForm.value.password
}).subscribe(data => {
console.log(data);
this.tokenStorage.saveToken(data.token);
this.tokenStorage.saveUser(data.user);
this.notificationService.showSnackBar("Successfully logged in")
this.router.navigate(['/']);
window.location.reload();
}, error => {
console.log(error);
this.notificationService.showSnackBar(error.message);
})
}
}
app.component.ts:
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {MaterialModule} from "./material-module";
import {HttpClientModule} from "@angular/common/http";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {authInterceptorProviders} from "./helper/auth-interceptor.service";
import {authErrorInterceptorProvider} from "./helper/error-interceptor.service";
@Component({
selector: 'app-root',
standalone: true,
imports: [MaterialModule, HttpClientModule, FormsModule, ReactiveFormsModule, RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
providers: [
authInterceptorProviders, authErrorInterceptorProvider
]
})
export class AppComponent {
title = 'instazooFrontend';
}
app.routers.ts:
import { Routes } from '@angular/router';
import {LoginComponent} from "./auth/login/login.component";
import {RegisterComponent} from "./auth/register/register.component";
export const routes: Routes = [
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
];
<div class="login-page">
<form [formGroup]="loginForm">
<div class="justify-content-center">
<mat-form-field appearance="outline">
<mat-label>Email Address</mat-label>
<input formControlName="username">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Password</mat-label>
<input matInput formControlPassword="Password">
</mat-form-field>
</div>
<div id="controls" class="row">
<button style="width: 20%" [disabled] = "loginForm.invalid" (click)="submit()" mat-flat-button color="primary">
Login
</button>
<a routerLink="/register">Register</a>
</div>
</form>
</div>
```
............................................................................................................................................................................................................
When I navigate to 'http://localhost:4200/login' expected to see the form, but I'm immediately redirected to "http://localhost:4200" |
When I navigate to the URL'http://localhost:4200/', it redirects me back |
|angular|angular-material|angular-ui-router| |
null |
I made a client-server side app using React.js and Expres.js.
I also used a local database made on mysql workbench.
I want to deploy my app to app-engine on google cloud, for this purpose I exported my db and now it is on the cloud.
The problem arises when I want ot deploy the app. The client sode shows, but whenever I try to do any function the app crashes and I get an error CONNECTION REFUSED.
So far I have tried:
- using the app engine template from the documentation
- using keys
- using solutions from gemini, copilot and chatgpt
This is my app.yaml
```
runtime: nodejs18
env: standard
instance_class: F2
handlers:
# Catch all handler to index.html
- url: /.*
script: auto
secure: always
redirect_http_response_code: 301
automatic_scaling:
target_cpu_utilization: 0.65
min_instances: 1
max_instances: 10
env_variables:
INSTANCE_CONNECTION_NAME: "hidden"
DB_PRIVATE_IP: ,
INSTANCE_HOST: "hidden"
DB_PORT: "3306"
DB_USER: "root"
DB_PASS: "************"
DB_NAME: "social_media"
vpc_access_connector:
name: projects/hidden
```
```
// import userRoutes from "./routes/users.js";
// import postRoutes from "./routes/posts.js";
// import likeRoutes from "./routes/likes.js";
// import commentRoutes from "./routes/comments.js";
// import relationshipRoutes from "./routes/relationships.js";
// import authRoutes from "./routes/auth.js";
// import cookieParser from "cookie-parser";
// import cors from "cors";
// import multer from "multer";
// import Express from "express";
// const app = Express();
// //middlewares
// app.use((req, res, next) => {
// res.header("Access-Control-Allow-Credentials", true);
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
// res.header("Access-Control-Allow-Headers", "Content-Type");
// next();
// });
// app.use(Express.json());
// app.use(
// cors({
// origin: "http://localhost:3000",
// })
// );
// app.use(cookieParser());
// const storage = multer.diskStorage({
// destination: function (req, file, cb) {
// cb(null, "../client/public/upload");
// },
// filename: function (req, file, cb) {
// cb(null, Date.now() + file.originalname);
// },
// });
// const upload = multer({ storage: storage });
// app.post("/api/upload", upload.single("file"), (req, res) => {
// const file = req.file;
// console.log("Received file:", file);
// res.status(200).json(file.filename);
// });
// app.use("/api/users", userRoutes);
// app.use("/api/posts", postRoutes);
// app.use("/api/likes", likeRoutes);
// app.use("/api/comments", commentRoutes);
// app.use("/api/relationships", relationshipRoutes);
// app.use("/api/auth", authRoutes);
// app.listen(8800, () => {
// console.log("API working!!");
// });
// /*const {Sequelize} = require('sequelize');
// // Create a new Sequelize instance.
// const sequelize = new Sequelize('social_media', 'root', 'password', {
// host: '/cloudsql/third-current-418819:us-central1:systems3db',
// dialect: 'mysql',
// });
// // Test the connection to the database.
// sequelize
// .authenticate()
// .then(() => {
// console.log('Connection to the database has been established successfully.');
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
// */
import userRoutes from "./routes/users.js";
import postRoutes from "./routes/posts.js";
import likeRoutes from "./routes/likes.js";
import commentRoutes from "./routes/comments.js";
import relationshipRoutes from "./routes/relationships.js";
import authRoutes from "./routes/auth.js";
import cookieParser from "cookie-parser";
import cors from "cors";
import multer from "multer";
import Express from "express";
import mysql from "mysql2/promise";
const app = Express();
// Get the environment variables
const {
INSTANCE_HOST,
DB_PORT,
DB_USER,
DB_PASS,
DB_NAME,
INSTANCE_CONNECTION_NAME,
} = process.env;
// Create a connection pool
const pool = mysql.createPool({
host: INSTANCE_HOST,
user: DB_USER,
database: DB_NAME,
password: DB_PASS,
port: DB_PORT,
socketPath: /cloudsql/${INSTANCE_CONNECTION_NAME},
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
// Now you can use the pool to query your database
app.post("/users", async (req, res) => {
try {
const [rows, fields] = await pool.execute("SELECT * FROM users");
res.json(rows);
} catch (err) {
res.status(500).json(err);
}
});
// etc.
//middlewares
app.use((req, res, next) => {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
app.use(Express.json());
app.use(
cors({
origin: "http://localhost:3000",
})
);
app.use(cookieParser());
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "../public/upload");
},
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname);
},
});
const upload = multer({ storage: storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
const file = req.file;
console.log("Received file:", file);
res.status(200).json(file.filename);
});
app.use("/api/users", userRoutes);
app.use("/api/posts", postRoutes);
app.use("/api/likes", likeRoutes);
app.use("/api/comments", commentRoutes);
app.use("/api/relationships", relationshipRoutes);
app.use("/api/auth", authRoutes);
const PORT = process.env.PORT || 8800;
app.listen(PORT, () => {
console.log(API working P:${PORT}!!);
});
```
|
Interest is supposed to be Percentages. Your formula expressed it as a decimal value.
Change the line below to:
// Convert annual interest rate percentage to decimal and then into monthly interest rate.
double monthlyInterestRate = (annualInterestRate / 100) / 12.0; |
I'm struggling to get the correct keyboard to show and be able to insert numbers and the decimal symbol but I'm faced with a strange situation.
This is what i got with Android Studio using Java code:
[![enter image description here][1]][1]
Here the xml code to show this keypad:
<EditText
android:id="@+id/editTextNumberDecimal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="1dp" />
So in this case everything works fine, i can digit numbers and dot to separate decimals.
Using Visual Studio with Syncfusion the keypad change like this:
[![enter image description here][2]][2]
The Keypad Show the negative sign and the dot.
I can insert in the negative sign doing double tap as the first char but not the dot.
The dot is never get showed on the textbox.
here is the xml code to call the numeric keypad:
<control:BorderlessEntry
x:Name="StretchRatioLenEntry"
Placeholder="(Es. 3,3)"
Keyboard= "Numeric"
Style="{StaticResource BorderlessEntryStyle}"
Text="{Binding StretchRatioLen.Value}" PlaceholderColor="#7B7B7B">
<Entry.Behaviors>
<behaviour:NumberEntryBehavior IsValid="{Binding StretchRatioLen.IsValid}" />
</Entry.Behaviors>
</control:BorderlessEntry>
So do you have any suggestion?
Thanks for your help.
[1]: https://i.stack.imgur.com/oxV0Y.png
[2]: https://i.stack.imgur.com/7wDQ1.png |
C# Visual Studio Android App Showing a wrong not working Keypad on Entry text |
|c#|xamarin|syncfusion| |