instruction
stringlengths
0
30k
I am trying to learn Django and have encountered a problem I can't figure out for the life of me. In this project I have an app called `projects`. In this app I have one model called `Projectinfo` and one called `Buildingtypes`. Every project can have one or more building types. What I am trying to do is to write a view that lists out all the projects with a commaseparated list of related building types. Here's a simplified version of my two models: ``` class Buildingtypes(models.Model): buildingtype = models.CharField(max_length=100) def __str__(self): return self.buildingtype class ProjectInfo(models.Model): project_number = models.CharField(max_length=12, blank=True) project_name = models.CharField(max_length=120) buildingtypes = models.ManyToManyField(Buildingtypes, default=[1]) def __str__(self): return self.project_name ``` I made a view that looks like this: ``` from django.http import HttpResponse from django.template import loader from .models import ProjectInfo def index(request): myProjects = ProjectInfo.objects.all() template = loader.get_template('projects/index.html') context = { 'projects': myProjects, } return HttpResponse(template.render(context, request)) ``` And the template: ``` {% if projects %} {% for x in projects %} {{ x.project_number }} | {{ x.project_name }} | {{ x.buildingtype }} {% endfor %} {% endif %} ``` Which resulted in this: ``` projectnumber | project name | building type ---------------------------------------------------------- 101010 | project 1 | projects.Buildingtypes.None 202020 | project 2 | projects.Buildingtypes.None ``` Since that obviously failed I also tried this: ``` {% if projects %} {% for x in projects %} {{ x.project_number }} | {{ x.project_name }} | {% for y in x.buildingtypes %} {{ y.buildingtype }} {% endfor %} {% endfor %} {% endif %} ``` Which resulted in this: ``` projectnumber | project name | building type ---------------------------------------------------------- 101010 | project 1 | 202020 | project 2 | ``` I made a query in MySQL just to show you what I am looking for. The following query gives me the result I want: ``` SELECT project_number, project_name, GROUP_CONCAT(pb.buildingtype SEPARATOR ', ') AS buildingtypes FROM projects_projectinfo AS pp JOIN projects_projectinfo_buildingtypes AS ppb ON pp.id = ppb.projectinfo_id JOIN projects_buildingtypes AS pb ON ppb.buildingtypes_id = pb.id GROUP BY pp.id; ``` Result: ``` projectnumber | project name | building type -------------------------------------------------------------------------------- 101010 | project 1 | building type 1, building type 3 202020 | project 2 | building type 2, building type 5, building type 6 ``` But how to convert this to a view? I have made various attempts with select_related, prefetch_related, filter and what not, but I can't just can't figure it out.
React Accordion transition ,
|reactjs|
null
as shown in the code posted below, i am using `turf.js` to buffer a geometry in the listener callback of `modifyend` of `Modify` event. i tried to set the buffered feature `asOLFeature` on the map via: `this.#vectorSource.addFeature(asOLFeature)` to assure that the buffered geometry is placed on the map, i converted `asOLFeature.getGeometry()` to geojson format so i can visualize it. the code i used to convert the `OL Geometry` to `GeoJSON` is as follows: var writer = new GeoJSON(); var geoJsonStr = writer.writeGeometry(asOLFeature.getGeometry()); the digitized geometry is shown in image-1 below, and the buffered geometry is shown in image-2 below. Apparently, the digitized geometry in image-1 when gets buffered using `turf`, as shown in image-2, it somehow gets converted into two geometries and displaced. i believe it about coordinate transformation and projection issue, but i do not know how to solve it. **code** this.#modifyEvtNullifierFeature = evt.feature; const modifyEvtNullifierAsGeom = this.#modifyEvtNullifierFeature.getGeometry(); const geojsonFormat = new GeoJSON(); const geosonGeometry = geojsonFormat.writeGeometryObject(modifyEvtNullifierAsGeom, { featureProjection: 'EPSG:3857', dataProjection:'EPSG:4326' }); let geomInMercator = turf.toMercator(geosonGeometry); const buffered = turf.buffer(geomInMercator, 60, {units: 'kilometers'}); let bufferedInWgs84 = turf.toWgs84(buffered); const asOLFeature = geojsonFormat.readFeature(bufferedInWgs84, { dataProjection:'EPSG:4326', featureProjection: 'EPSG:3857' }); this.#modifyEvtNullifierFeature.set(ModifyEvtNullifierFeaturesConstants.CONST_IS_MODIFY_EVT_NULLIFIER_FEATURE.description, true); this.#vectorSource.addFeature(asOLFeature); **image-1** [![enter image description here][1]][1] **image-2** [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/5WSTa.png [2]: https://i.stack.imgur.com/Fn858.png
projection and EPSG mismatch when buffer a geometry
|openlayers|openlayers-3|openlayers-6|
[enter image description here][1]According to the network diagram above, the connection from company A's pc0 to the server system including gmail and facebook is successful, but company B's pc6 and pc7 cannot ping the server system. I tried to give ip from dns but it didn't work. The system works normally, all devices are connected successfully, can send emails from the pc to the server [1]: https://i.stack.imgur.com/pz5eC.png
This is due to `executable_path` is an argument of `webdriver.chrome.service.Service`, see [ducumentation][1] Just use driver = webdriver.Chrome() # or service = webdriver.chrome.service.Service(executable_path='path/to/your/chrome/driver') driver = wbdriver.Chrome(service=service) [1]: https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.chrome.webdriver
{"OriginalQuestionIds":[60640745],"Voters":[{"Id":87698,"DisplayName":"Heinzi","BindingReason":{"GoldTagBadge":"c#"}}]}
I have two middleware in my ASP.NET Core application. One needs to be registered with `ConfigureServcies`, but the other one doesn't. For example: 1. ``` public class RequestMiddleware { private readonly RequestDelegate _next; public RequestMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext httpContext, IWebHostEnvironment env) { try { await _next(httpContext); } catch (Exception ex) { // ... code ... } } } // I use this middleware in startup app.UseMiddleware<RequestMiddleware>(); ``` 2. ``` public class SampleMiddleware : IMiddleware { public Task InvokeAsync(HttpContext context, RequestDelegate next) { // ... code ... } } public void ConfigureServices(IServiceCollection services) { services.AddTransient<AppSampleLogsMiddleware>(); } app.UseMiddleware<AppSampleLogsMiddleware>(); ``` Why does the second one need to be registered, but not the first one? How are they different?
Why do some middleware need to be registered with `ConfigureServices` while others don't?
`foo()` is taking in a primitive `int` *by value*, so it is a *copy* of whatever value you pass in at the call site. There is no reference here. It doesn't matter what `foo()` does internally to the value of `y`, that value does not get reflected back to the caller. Also, there is no such thing as "point at a value". You can have a pointer/reference to a variable, but not point/refer to a value. A variable holds a value. > then `x` becomes 3 because `y=y+2` and `y` was pointing at the value 1 of `x`. > > `foo(a[x])` is called with `a[3]` (which doesnt exists). `x` is decremented to 2. This is incorrect. It is `y`, not `x`, that becomes 3. ```java y = y + 2; ^ ``` `x` is still 0 at this point. So the subsequent call to `foo(a[x])` is using `a[0]` instead, which then decrements `x` to -1 and then sets `x` to 5.
here's an alternative using left join unnest instead of having to write out all the dates. Made a mock table to how the results in the CTE/with function. WITH mock_data AS ( SELECT '2024-03-12' AS date, 'NA' AS region, 999999 AS revenue UNION ALL SELECT '2024-03-12' AS date, 'NA' AS region, 200000 AS revenue UNION ALL SELECT '2024-03-13' AS date, 'NA' AS region, 0 AS revenue) SELECT date, region, SUM(revenue) AS revenue_sum FROM mock_data WHERE CAST(date AS date) IN ( SELECT date FROM ( SELECT date FROM ( SELECT NULL) LEFT JOIN UNNEST (GENERATE_DATE_ARRAY('2024-03-12', '2024-03-25', INTERVAL 1 DAY)) AS date)) GROUP BY date, region
Adding this here for the extra visibility, but if you're using VS Code, the CMake Tools extension has commands to view/edit the variable cache, either using an intermediary UI or directly by opening the cache in a text editor tab so you don't have to go dig into your build folder for it.
Implement FFDShow in .net
|c#|.net|ffdshow|dolby|
I'm trying to have an element project a shadow / blurred edge onto an element behind it, causing the latter to "dissolve", without impacting the background. Hopefully the following images can better illustrate my problem. This is what I was able to get: [Shadow clearly stands out from the background](https://i.stack.imgur.com/s8bjf.png) While this is the result I'm trying to achieve: [Shadow works sort of like a mask on the element behind](https://i.stack.imgur.com/OchMS.png) This is the code I used to make the first image: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> html { height: 500px; background: linear-gradient(#9198E5, #E66465); } #back { position: absolute; top: 100px; left: 100px; width: 200px; height: 200px; background-color: #FFBBBB; } #front { position: absolute; top: 200px; left: 200px; width: 200px; height: 200px; background-color: #BBFFBB; box-shadow: -30px -30px 15px #BF7B9F; } <!-- language: lang-html --> <div id="back"></div> <div id="front"></div> <!-- end snippet -->
null
I currently have an Android application built with Jetpack Compose on the Play Store with [android-maps-compose librairie](https://github.com/googlemaps/android-maps-compose). For several days now, I've been receiving reports of recurring crashes from the Play Store, but I'm unable to reproduce the issue on my end. Here's the StackTrace: ``` Exception java.lang.IllegalStateException: at com.google.maps.android.compose.MarkerState.setMarker$maps_compose_release (Marker.kt:29) at com.google.maps.android.compose.MarkerNode.onAttached (Marker.kt:5) at com.google.maps.android.compose.MapApplier.insertBottomUp (MapApplier.kt:13) at com.google.maps.android.compose.MapApplier.insertBottomUp (MapApplier.kt:13) at androidx.compose.runtime.changelist.Operation$PostInsertNodeFixup.execute (Operation.kt:26) at androidx.compose.runtime.changelist.Operations.executeAndFlushAllPendingOperations (Operations.kt:23) at androidx.compose.runtime.changelist.FixupList.executeAndFlushAllPendingFixups (FixupList.java:36) at androidx.compose.runtime.changelist.Operation$InsertSlotsWithFixups.execute (Operation.kt:36) at androidx.compose.runtime.changelist.Operations.executeAndFlushAllPendingOperations (Operations.kt:23) at androidx.compose.runtime.changelist.ChangeList.executeAndFlushAllPendingChanges (ChangeList.kt:3) at androidx.compose.runtime.CompositionImpl.applyChangesInLocked (Composition.kt:50) at androidx.compose.runtime.CompositionImpl.applyChanges (Composition.kt:6) at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$1.invoke (Recomposer.kt:174) at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$1.invoke (Recomposer.kt:174) at androidx.compose.ui.platform.AndroidUiFrameClock$withFrameNanos$2$callback$1.doFrame (AndroidUiFrameClock.android.kt:7) at androidx.compose.ui.platform.AndroidUiDispatcher.performFrameDispatch (AndroidUiDispatcher.java:48) at androidx.compose.ui.platform.AndroidUiDispatcher.access$performFrameDispatch (AndroidUiDispatcher.java:48) at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.doFrame (AndroidUiDispatcher.android.kt:48) at android.view.Choreographer$CallbackRecord.run (Choreographer.java:1648) at android.view.Choreographer$CallbackRecord.run (Choreographer.java:1659) at android.view.Choreographer.doCallbacks (Choreographer.java:1129) at android.view.Choreographer.doFrame (Choreographer.java:1045) at android.view.Choreographer$FrameDisplayEventReceiver.run (Choreographer.java:1622) at android.os.Handler.handleCallback (Handler.java:958) at android.os.Handler.dispatchMessage (Handler.java:99) at android.os.Looper.loopOnce (Looper.java:230) at android.os.Looper.loop (Looper.java:319) at android.app.ActivityThread.main (ActivityThread.java:8893) at java.lang.reflect.Method.invoke at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:608) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1103) ``` Below is the code for my screen used to display the map (simplified to include only the map part): ```kotlin @Composable fun MyMapsView( cameraPositionState: CameraPositionState, ) { val viewModel: AdaptedMapViewModel = koinViewModel() val darkTheme = appIsInDarkMode() val markerPositionStates = remember { mutableMapOf<Long, MarkerState>() } LaunchedEffect(Unit) { viewModel.init(darkTheme) } LaunchedEffect(viewModel.markers.value) { viewModel.updateMarkerToDisplay() } LaunchedEffect(viewModel.groups.value) { viewModel.updateMarkerToDisplay() } LaunchedEffect(viewModel.sortMode.value) { viewModel.updateMarkerToDisplay() } Box(Modifier.fillMaxSize()) { GoogleMap( modifier = Modifier.fillMaxSize(), cameraPositionState = cameraPositionState, uiSettings = MapUiSettings( myLocationButtonEnabled = false, zoomControlsEnabled = false, mapToolbarEnabled = false ), properties = MapProperties( mapStyleOptions = MapStyleOptions.loadRawResourceStyle( LocalContext.current, viewModel.mapStyle.value.rawResourceId ), mapType = viewModel.mapType.value ) ) { MapMarkersAndCircles(viewModel, markerPositionStates) } } } @Composable private fun MapMarkersAndCircles( viewModel: AdaptedMapViewModel, markerPositionStates: MutableMap<Long, MarkerState> ) { viewModel.markersToDisplay.value.forEach { marker -> if (markerPositionStates.containsKey(marker.id)) { markerPositionStates[marker.id]!!.position = marker.latLng()!! } else { markerPositionStates.putIfAbsent( marker.id, rememberMarkerState( key = "${marker.id}", position = marker.latLng()!! ) ) } MarkerComposable( keys = arrayOf(marker.id), tag = marker.id, state = markerPositionStates[marker.id]!!, anchor = if (marker.emoji.isNotEmpty()) Offset(0.5F, 0.5F) else Offset(0.5F, 1F), visible = viewModel.groups.value.find { it.id == marker.groupId }?.enable ?: true && marker.active, ) { Icon( painter = painterResource(id = R.drawable.ic_marker_fill), contentDescription = null, tint = markerColor(viewModel.mapStyle.value), modifier = Modifier.size(40.dp) ) } marker.circles.sortedByDescending { it.radius() }.forEach { circle -> MapCircle(viewModel, marker, circle) } } } @Composable private fun MapCircle(viewModel: AdaptedMapViewModel, marker: FullDataMarker, circle: FullDataCircle) { return Circle( center = marker.latLng()!!, clickable = true, visible = viewModel.groups.value.find { it.id == marker.groupId }?.enable ?: true && marker.active && circle.active, fillColor = if (viewModel.circleStyle.value == CircleStyle.OUTLINE) Color.Transparent else Color(circle.color).copy(alpha = 0.3f), radius = circle.radius(), ) } fun moveToLocation( coroutineScope: CoroutineScope, cameraPositionState: CameraPositionState, latLng: LatLng ) { coroutineScope.launch { cameraPositionState.animate( update = CameraUpdateFactory.newLatLng(latLng), durationMs = 1000 ) } } ``` And here's the code for the ViewModel (simplified to include only the map, markers, etc.): ```kotlin class AdaptedMapViewModel( private val userPreferencesManager: UserPreferencesManager, private val appDataBaseManager: AppDataBaseManager, ) : ViewModel() { private val _markersToDisplay = mutableStateOf((listOf<FullDataMarker>())) val markersToDisplay: State<List<FullDataMarker>> = _markersToDisplay private val _mapType = mutableStateOf(userPreferencesManager.defaultAppMapType()) val mapType: State<MapType> = _mapType private val _mapStyle = mutableStateOf(MapStyle.STANDARD) val mapStyle: State<MapStyle> = _mapStyle private val _initiated = mutableStateOf(false) val sortMode: State<SortOrder> = userPreferencesManager.sortOrder val circleStyle = userPreferencesManager.circleStyle val markers = appDataBaseManager.markers val groups = appDataBaseManager.markerGroups fun init(darkTheme: Boolean) { if (_initiated.value) return _mapStyle.value = userPreferencesManager.defaultAppMapStyle(darkTheme) updateMarkerToDisplay() _initiated.value = true } fun updateMarkerToDisplay() { _markersToDisplay.value = markers.value .generalOrder(null, groups.value, sortMode.value) .filter { it.active } } } ``` I suspect the issue may arise from the fact that the list of markers to display evolves over time, but I've already tried several approaches, and this one seems to "work best". I added a tag and a key, used a list of MarketState: markerPositionStates to avoid having multiple states per marker (which was previously the case). I'm not sure what else to test at this point.
Android Maps Compose | MarkerState.setMarker IllegalStateException
|android|google-maps|android-jetpack-compose|google-maps-markers|
null
We recently upgraded Allure (2.27.0) and Allure Jenkins plugin (2.31.1) to the latest versions. Now the Allure report is empty and the log file contains: ``` com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "testCaseName" (class io.qameta.allure.model.TestResult), not marked as ignorable (18 known properties: "start", "descriptionHtml", "parameters", "name", "historyId", "statusDetails", "status", "links", "fullName", "uuid", "description", "testCaseId", "stage", "labels", "stop", "steps", "rerunOf", "attachments"\]) ``` The build.gradle is: ``` plugins { id "io.qameta.allure" version "2.11.2" } allure { version = "2.27.0" adapter { allureJavaVersion = "2.27.0" aspectjVersion.set("1.9.22") autoconfigureListeners.set(true) aspectjWeaver.set(true) frameworks { junit5 { // Defaults to allureJavaVersion adapterVersion = "2.26.0" enabled = true } } } report { reportDir.set(project.reporting.baseDirectory.dir("allure-report")) def resultsDir = "project.reporting.baseDirectory.dir("allure-results")" } } ``` Tried upgrading jackson library to the latest version but didn't help.
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "testCaseName" (class io.qameta.allure.model.TestResult)
|allure|
null
The accepted answer is correct git config --global core.autocrlf false For anyone coming here just to learn - one very helpful thing to keep in mind is that modern IDEs can render files with LF or CRLF. So imagine you're a lone windows dev on a team of macOS users. You'll be checking out a codebase that's likely ending in `LF`. The command above ensures that upon checkout, you don't mess up the `LF` characters. In your IDE, for example in JetBrain, you should set the project (or globally) to use LF. 1. CTRL + ALT + S for settings 2. Code Style -> General -> Line Separator [![enter image description here][1]][1] Furthermore, in the bottom righthand IDE toolbar, it will display either LF or CRLF, which indicates the setting of the current file. You can click it to change between styles. [![enter image description here][2]][2] **So in summary** 1. `git config --global core.autocrlf false` to avoid changing line endings on checkout. 2. IDE setting to avoid changing them on subsequent edits or on new file creation. [1]: https://i.stack.imgur.com/zBDAu.png [2]: https://i.stack.imgur.com/hG6sc.png
Rotate an object around another object in javascript
|javascript|
null
Try this: plt.plot(range(1, len(rfecv.cv_results_["mean_test_score"]) + 1), rfecv.cv_results_["mean_test_score"], color='#303F9F', linewidth=3)
It's been 2 years but hope this helps, at least, it worked for me. If you have the country boundaries GeoJSON (Multipolygon Feature). You may use @turf import { featureEach, difference, buffer } from '@turf/turf'; const getInverseFeature = (featureCollection, distance) => { // Create a bounding box for the entire world let invertedPolygon; // Loop through each feature in the FeatureCollection featureEach(featureCollection, (feature) => { // Buffer the feature polygon slightly to ensure it covers the boundaries const bufferedFeature = buffer(feature, 40, { units: 'kilometers' }); //You may use distance instead of 40 km // Convert the buffered feature to a GeoJSON polygon const featurePolygon = bufferedFeature; // If invertedPolygon already exists, subtract the current feature polygon from it if (invertedPolygon) { invertedPolygon = difference(invertedPolygon, featurePolygon); } else { // Otherwise, initialize invertedPolygon with the first feature polygon invertedPolygon = featurePolygon; } }); // Subtract the inverted polygon from the world bounding box const worldPolygon = { type: 'Polygon', coordinates: [ [ [-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90], ], ], }; return difference(worldPolygon, invertedPolygon); }; With the help of function you can get inverse feature and (In React I used the GeoJSON component) <GeoJSON data={outterBounds} pathOptions={{ color: mapChange ? '#163a4a' : '#aad3df', // weight: 2.5, lineCap: 'round', fill: true, fillOpacity: 0.98, }} /> But this is important to know, you shouldn't use the function in Frontend, because it is a very slow function and will freeze the brower. To use the inverse feature you may use one of the following options. 1- Generate Inverse Feature in Backend and return the result from backend to frontend (By the way, the FeatureCollection at function is the Feature Collection of the Country Coastline (Borderlines of the country)) 2- You may use it at frontend just once, console log the Reverse Feature to DevTools console, copy the object and create a country outter bounds constant and import it to the file which you will generate the map and use GeoJSON. 3- Use the second option, add copied object to DB and fetch it from DB (again you will get the data from Backend but this time you do not need to use the above function calculation again and again. Result from the above (I used 2nd option by the way) : [enter image description here][1] [1]: https://i.stack.imgur.com/mvpUF.png
I have data, and for this example it is displayed in two ways. Firstly data is displayed on the server component. The second is data is passed down to a client component, and rendered inside of the client component. If the data changes, and I use either revalidatePath and router.refresh() only the data displayed inside of the server component works. So even though the props change for the client component, the client component is not re-rendered. ```typescript import React from "react"; import AddForm from "./AddForm"; import { Fund, PartnerData, fundCollection } from "@/lib/mongodb"; import ManageTable from "./table"; import { revalidatePath } from "next/cache"; import { WithId } from "mongodb"; export default async function Manage() { var funds; var fund: WithId<Fund>; try { console.log("refetchign"); funds = await (await fundCollection).find({ name: "fund_name" }).toArray(); fund = funds[0]; console.log(fund.partners); } catch (e) { console.log("ERROR", e); } return ( <div> //On revalidatePath or router.refresh(), this updates to correct value {JSON.stringify(fund!.partners)} //This is a client component. Data passed as props. This does not update to the correct value <ManageTable rows={fund!.partners} /> </div> ); } ``` I expect that the fund!.partners be the same inside the server component, and the client component.
This is due to `executable_path` is an argument of `webdriver.chrome.service.Service`, see [ducumentation][1] Just use driver = webdriver.Chrome() # or service = webdriver.chrome.service.Service(executable_path='path/to/your/chrome/driver') driver = webdriver.Chrome(service=service) [1]: https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.chrome.webdriver
I found a simple solution that works reliably. If you assign a unique `GlobalKey` to your `GoogleMap` instance, and update the `GlobalKey` when the app is resumed, then on resume the old (disposed) Maps widget will be replaced with a new one, which is correctly redrawn. You also have to re-create the controller (or at least the `Completer` for the controller), because `Completer` that is typically used with the Maps API is already complete (so it can't be completed a second time): class _CreateEventViewState extends State<_CreateEventView> with WidgetsBindingObserver { // Add late GlobalKey _googleMapWidgetKey; // Add late Completer<GoogleMapController> _mapControllerCompleter; // Add @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); // Add _googleMapWidgetKey = GlobalKey(); // Add _mapControllerCompleter = Completer<GoogleMapController>(); // Add } // Add: @override void didChangeAppLifecycleState(AppLifecycleState state) async { if (state == AppLifecycleState.resumed) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { setState(() { _googleMapWidgetKey = GlobalKey(); _mapControllerCompleter = Completer<GoogleMapController>(); }); } }); } } @override Widget build(BuildContext context) { GoogleMap( key: _googleMapWidgetKey, // Add onMapCreated: _mapControllerCompleter.complete, // Add // ... ), } }
In node_modules file i am getting Angular genric error while using fontawesome in angular12
The problem is following: * One of our VS C++ project files is for v142 build tools and it succesfully buildable with MS Build Tool 2019 on our 'build machine' * but locally (and also on 'build machines' for other customers) I need to build the same VS C++ project with MS Build Tool 2022 (which use v143 build tools) Is it possible to build VS C++ v142 project with newer version is MS Build Tools? So, I want to keep the same VS C++ project file but have it buildable with MS Build Tools 2019 and 2022. Is it possible at all?
Is it possible to build v142 project with v143 build tools?
|c++|msbuild|
I am using com.google.maps.android:maps-compose:4.3.3 to show map with markers. There are not so much of them, so I don't use clustering. I have a mutableStateList of markers which fetches data visible in a current viewport from local Room database. I am using MarkerInfoWindow to show custom composable info window on marker click, also I don't use custom click listener, so it switches to default info window logic. The problem is: I click on a marker, info window is shown, marker is centered, all good, but after marker list refreshes, the info window (very often) jumps to a random marker on a screen however my initially selected marker is still in a list. I tried setting tag and snippet for MarkerInfoWindow assuming it will help with uniquely identifying the marker in a list, but it didn't help. Expected result: once info window is shown, even if the marker list refreshes and the selected marker is still in a list, info window stays where it was initially shown.
browse to https://<yoursitename>.scm.azurewebsites.net/ZipDeployUI
Here's an alternative using left join unnest instead of having to write out all the dates. Made a mock table to how the results in the CTE/with function. WITH mock_data AS ( SELECT '2024-03-12' AS date, 'NA' AS region, 999999 AS revenue UNION ALL SELECT '2024-03-12' AS date, 'NA' AS region, 200000 AS revenue UNION ALL SELECT '2024-03-13' AS date, 'NA' AS region, 0 AS revenue) SELECT date, region, SUM(revenue) AS revenue_sum FROM mock_data WHERE CAST(date AS date) IN ( SELECT date FROM ( SELECT date FROM ( SELECT NULL) LEFT JOIN UNNEST (GENERATE_DATE_ARRAY('2024-03-12', '2024-03-25', INTERVAL 1 DAY)) AS date)) GROUP BY date, region
In my database I have a data set with date (startdatetime) and zone (timezone). Zone is posted into the DB from a different application that uses C# DateObject. Ex. (UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague OR another example (UTC-10:00) Hawaii I need to create a component that can convert date (startdatetime) and zone (timezone) to the users choosing, so I created a dropdown that uses time zones from moment-timezone library. UNFORTUNATELY it doesn't convert (or accurately if it does) the C# DateObject format since it's not in the same format as moment-timezone. So I either have to create a dictionary where for example it converts '(UTC-08:00) Pacific Time (US & Canada)' to 'America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0' or create my own custom dynamic timezone converter. Which I have tried but I keep getting incorrect time. I could be missing something in moment-timezone docs (since I am new to the library) but as of now this is my existing code (before I was informed that the timezone will be on C# Date Object format and not on moment-timezone format). ```` import React, {useState, useEffect} from 'react'; import CloseIcon from '@material-ui/icons/Close'; import { makeStyles } from '@material-ui/core/styles'; import { useSelector, useDispatch } from "react-redux"; import {setRunListData, getRunDataAllGroupedAsync, setIsAllRunListDataShown, setTimeZone} from "../actions/index"; import * as Utils from '../../utils/utils'; import { Select, MenuItem, FormControl } from '@mui/material'; import moment from 'moment-timezone'; import { Typography, IconButton, Button, Dialog, DialogTitle, DialogActions } from '@material-ui/core'; const TimeZone = (props) => { const { handleClose, isOpen } = props; const runlist = useSelector(state => state.runlist); const jwt = useSelector(state => state.jwt); const is_all_run_list_data_shown = useSelector(state => state.is_all_run_list_data_shown); const dispatch = useDispatch(); const [selectedTimeZone, setSelectedTimeZone] = React.useState(localStorage.getItem('time_zone') || 'PST8PDT'); const [originalRunlist, setOriginalRunlist] = useState(runlist); const zones = Utils.zones; useEffect(() => { setOriginalRunlist(is_all_run_list_data_shown); }, [is_all_run_list_data_shown]) const useStyles = makeStyles((theme) => ({ dialogWrapper: { padding: theme.spacing(2), position: 'absolute', top: theme.spacing(2), }, dialogTitle: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', }, closeIcon: { marginLeft: 'auto', }, storagesContainer: { display: 'flex', justifyContent: 'space-evenly', gap: 5, margin: '20px 0px', }, alertContainer: { display: 'flex', alignItems: 'center', marginLeft: '20px 0px', overflow: 'hidden', }, inputContainer: { display: 'flex', alignItems: 'center', justifyContent: 'space-evenly', margin: '15px 0px', //overflow: 'hidden', }, outlineInput: { height: 20, width: 50, marginLeft: 10, marginRight: 10, }, buttonContainer: { display: 'flex', justifyContent: 'space-evenly', overflow: 'hidden', }, defaultButton: { margin: theme.spacing(1), background: 'linear-gradient(113.96deg, #E9F5F5 100%, #D9E7F4 100%)', border: '0.5px solid #CCCCCC', boxSizing: 'border-box', borderRadius: '4px', color: '#189AB4', width: 150, '&:disabled': { background: '#f0f0f0', // Change this to the desired disabled background color color: '#666666', // Change this to the desired disabled text color }, }, button: { margin: theme.spacing(1), background: '-webkit-gradient(linear, left top, right bottom, from(#0075a9), to(#003049))', border: '0.5px solid #CCCCCC', boxSizing: 'border-box', borderRadius: '4px', color: 'white', width: 150, '&:disabled': { background: '#f0f0f0', // Change this to the desired disabled background color color: '#666666', // Change this to the desired disabled text color }, }, formControl: { "& .MuiInputBase-root": { borderWidth: "1px", borderStyle: "solid", minWidth: "120px", width: "280px", justifyContent: "center", cursor: "pointer" // Set cursor to pointer }, "& .MuiSelect-select.MuiSelect-select": { paddingRight: "15px" }, marginLeft: "auto" // Move the FormControl to the right }, })); const classes = useStyles(); const handleChange = (event) => { setSelectedTimeZone(event.target.value); }; const handleDefaultRunlistDate = () => { setSelectedTimeZone('PST8PDT'); dispatch(setTimeZone('PST8PDT')); originalRunlist ? dispatch(getRunDataAllGroupedAsync(undefined, jwt)) : dispatch(getRunDataAllGroupedAsync(100, jwt)); } function toTimeZone(time, zone) { try { var format = 'MM/DD/YYYY HH:mm:ss'; return moment(time, format).tz(zone).format(format); } catch (error) { console.log(error) } } const handleUpdateRunlistDate = () => { let copyRunList = structuredClone(runlist); const updatedRunlist = copyRunList.map(entry => { if(entry.timezone){ const startDatetime = toTimeZone(entry.startdatetime, selectedTimeZone); entry.startdatetime = startDatetime; entry.timezone = selectedTimeZone; } return entry; }); dispatch(setTimeZone(selectedTimeZone)); dispatch(setRunListData(updatedRunlist)); } return ( <> <Dialog disableEnforceFocus onClose={handleClose} aria-labelledby="customized-dialog-title" open={isOpen} fullWidth maxWidth={'sm'} classes={{paper: classes.dialogWrapper}}> <DialogTitle> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <Typography variant="h6">Time Zone Settings</Typography> <IconButton onClick={handleClose}> <CloseIcon /> </IconButton> </div> </DialogTitle> <div className={classes.inputContainer}> <Typography>Time Zone Name:</Typography> <FormControl className={classes.formControl}> <Select labelId="zone-label" id="zone-select" value={selectedTimeZone} onChange={handleChange} > {zones.map((zone, index) => ( <MenuItem key={index} value={zone.split('|')[0]}> {zone.split('|')[0]} </MenuItem> ))} </Select> </FormControl> </div> <div className={classes.buttonContainer}> <DialogActions> <Button autoFocus color="primary" className={classes.defaultButton} onClick={handleDefaultRunlistDate}> Default </Button> <Button autoFocus color="primary" className={classes.button} onClick={handleUpdateRunlistDate}> Apply </Button> </DialogActions> </div> </Dialog> </> ); } export default TimeZone; ```` Any tips?
I'd like to create a custom time zone converter, any pointers?
|javascript|reactjs|datetime|timezone|
{"Voters":[{"Id":3745413,"DisplayName":"Ron Maupin"},{"Id":14853083,"DisplayName":"Tangentially Perpendicular"},{"Id":354577,"DisplayName":"Chris"}],"SiteSpecificCloseReasonIds":[18]}
**I want to fetch data from Amazon's website, list the products, and then navigate to Amazon's site by tapping on the listed items in the application. However, I encountered the following error;** E/flutter (15082): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: Could not launch /sspa/click? E/flutter (15082): #0 \_AmazonScrapingPageState.\_launchURL (package:web_scraping/main.dart:59:7) **And that is my code below ;** ``` import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as dom; import 'package:url_launcher/url_launcher.dart'; class AmazonScrapingPage extends StatefulWidget { @override _AmazonScrapingPageState createState() => _AmazonScrapingPageState(); } class _AmazonScrapingPageState extends State<AmazonScrapingPage> { List<String> productTitles = []; List<String> productPrices = []; List<String> productLinks = []; // Amazon page link Future<void> fetchData() async { final response = await http.get(Uri.parse( 'https://www.amazon.com.tr/s?k=bluetooth+klavye&__mk_tr_TR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&ref=nb_sb_noss')); if (response.statusCode == 200) { setState(() { productTitles.clear(); productPrices.clear(); productLinks.clear(); _parseProductData(response.body); }); } else { throw Exception('Failed to load data'); } } void _parseProductData(String htmlString) { var document = dom.parse(htmlString); var productElements = document.querySelectorAll('.s-result-item'); productElements.forEach((element) { var titleElement = element.querySelector('.a-size-base-plus.a-color-base.a-text-normal'); var priceElement = element.querySelector('.a-price'); var linkElement = element.querySelector('a.a-link-normal'); if (titleElement != null && priceElement != null && linkElement != null) { var title = titleElement.text.trim(); var price = priceElement.text.trim(); var link = linkElement.attributes['href']; productTitles.add(title); productPrices.add(price); productLinks.add(link!); } }); } Future<void> _launchURL(String url) async { if (await canLaunch(url)) { await launch(url); } else { throw 'Could not launch $url'; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Amazon Veri Çekme'), ), body: Center( child: Padding( padding: const EdgeInsets.all(10.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () { fetchData(); }, child: Text('Veriyi Çek'), ), SizedBox(height: 20), Expanded( child: ListView.builder( itemCount: productTitles.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { _launchURL(productLinks[index]); }, child: Container( padding: EdgeInsets.all(10), margin: EdgeInsets.symmetric(vertical: 5), decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.circular(10), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( productTitles[index], style: TextStyle( fontWeight: FontWeight.bold, ), ), SizedBox(height: 5), Text( productPrices[index], style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, ), ), ], ), ), ); }, ), ), ], ), ), ), ); } } void main() { runApp(MaterialApp( home: AmazonScrapingPage(), )); } ``` **The screen displays selected products along with their prices, but when I tap on the products, I can't navigate to the product links. Already tried flutter clean , and closing app then flutter run .**
@Tanaike observed that the API will not allow what i want to achieve. Thanks , i've upvoted you. From my quick research , i've found out it's possible to obtain the same result by AppScripts + webhooks: https://medium.com/@eyalgershon/sending-a-webhook-for-new-or-updated-rows-in-google-sheets-e0c9d6a8cb45 In the AppScript function , one can get any metadata and pass it to the webhook , like current time , coordinates , etc.
The second way of creating middleware is called [Factory-based Middleware](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/extensibility) > `UseMiddleware` extension methods check if a middleware's registered type implements `IMiddleware`. If it does, the `IMiddlewareFactory` instance registered in the container is used to resolve the `IMiddleware` implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container. > > Benefits: > > - Activation per client request (injection of scoped services) Strong > > - typing of middleware So, because of implementing the `IMiddleware`, not only do you need to add this middleware to the request pipeline, but you also need to register it into DI containers. This subtle difference has to do with scope. Factory-based middleware are transient and can receive scoped services via the constructor. See the [Creating conventional and factory-based Middleware for .NET Core](https://codingdistilled.medium.com/creating-conventional-and-factory-based-middleware-for-net-core-a36751187ca3) post to learn more.
I'm writing a landing page to handle redirects from AWS Marketplace, show a signup form, and if the user signs up associate a marketplace customer ID as a custom attribute in Cognito. My app uses the amplify <Authenticator> component to render a sign-up/login form, but it doesn't have an obvious prop where I can either set additional user fields for Cognito or hook into a signup/login event or provide clientContext data to be passed into Cognito's post-confirmation lambda hook. How do I set additional data on the user?
The issue is that you have a string with quotes in it (example: `var str = "<p class="some">Test</p>"`). These `"` need to be escaped. It could be done like this: `var str = "<p class=\"some\">Test</p>"` or you could URL encode the string. JavaScript has functions for encoding and decoding: [encodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) and [decodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI). And you can do something similar in Spring boot: [Guide to Java URL Encoding/Decoding](https://www.baeldung.com/java-url-encoding-decoding). Here is an example on how the JSON object is created in JavaScript (don't mind the `${''}` -- they are there because JavaScript will try to interpret the string as JavaScript): <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> let html_str = `<style>#backgroundImage { border: none; height: 100%; pointer-events: none; position: fixed; top: 0; visibility: hidden; width: 100%; } [show-background-image] #backgroundImage { visibility: visible; } </style> </head> <body> <iframe id="backgroundImage" src=""></iframe> <ntp-app></ntp-app> <scr${''}ipt type="module" src="new_tab_page.js"></scr${''}ipt> <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> <link rel="stylesheet" href="chrome://theme/colors.css?sets=ui,chrome"> <link rel="stylesheet" href="shared_vars.css"> </body> </html>`; let json_obj = {"content": encodeURI(html_str), "title": "test1"}; console.log(json_obj); <!-- end snippet -->
|python|django|django-models|django-views|django-templates|
{"Voters":[{"Id":11107541,"DisplayName":"starball"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":1693192,"DisplayName":"Petr Hejda"}],"SiteSpecificCloseReasonIds":[13]}
df1.assign(higher=df1.High.rolling(3,min_periods=3,center=True).max().eq(df1.High).astype(int)) Date High higher 0 2015-11-11 25.90 0.0 1 2015-11-12 27.12 1.0 2 2015-11-13 26.20 0.0 3 2015-11-16 26.19 0.0 4 2015-11-17 25.51 0.0 5 2015-11-18 26.31 1.0 6 2015-11-19 26.00 0.0 7 2015-11-20 27.01 1.0 8 2015-11-23 25.60 0.0 9 2015-11-24 27.00 1.0 10 2015-11-25 26.49 0.0
I ran into a problem when I decided to make a server for microservices, but I ran into the problem that my microservice cannot register in Eureka, what could be wrong? ``` apiVersion: v1 kind: ConfigMap metadata: name: configmap data: foodcataloguedb_url: jdbc:postgresql://35.228.167.123:5432/foodcataloguedb restaurantdb_url: jdbc:postgresql://35.228.167.123:5432/restaurantdb userdb_url: jdbc:postgresql://35.228.167.123:5432/userdb EUREKA_CLIENT_SERVICEURL_DEFAULTZONE: "http://eureka:8761/eureka/" GATEWAY_APPLICATION_NAME: gateway ``` ``` apiVersion: apps/v1 kind: Deployment metadata: name: gateway labels: app: gateway spec: replicas: 1 selector: matchLabels: app: gateway template: metadata: labels: app: gateway spec: containers: - name: gateway image: kirsing123/gateway:v1.4 imagePullPolicy: Always ports: - containerPort: 8072 env: - name: SPRING_APPLICATION_NAME valueFrom: configMapKeyRef: name: configmap key: GATEWAY_APPLICATION_NAME - name: EUREKA_CLIENT_SERVICEURL_DEFAULTZONE valueFrom: configMapKeyRef: name: configmap key: EUREKA_CLIENT_SERVICEURL_DEFAULTZONE --- apiVersion: v1 kind: Service metadata: name: gateway spec: selector: app: gateway type: LoadBalancer ports: - protocol: TCP port: 8072 targetPort: 8072 ``` [Errors](https://i.stack.imgur.com/dElHe.png) [Eureka Dashboard](https://i.stack.imgur.com/uqnY8.png) I changed dependencies and turned the @EnableDiscoveryClient annotation on and off, to no avail
Here is my interpretation of the [accepted answer], as well as of the [demonstration video][video] linked from [another answer]. Imagine that the graph edges are ropes of given lengths. To get the shortest path distances from the source node to all the other nodes, as well as the shortest paths themselves, it is enough to hold the source node and let the other ones suspend from it vertically on the ropes. This is a physical solution. To get an algorithmic solution, however, the physical laws need to be explicitly tested and enforced. Let now the graph edges be elastically stretchable, with given lengths at rest. Pin the source node fixed and pin all the other nodes strictly vertically under it at a very large distance (to be considered infinite). Thus all the edges from the source node to its neighbors are (infinitely) stretched. (This corresponds to the situation when `d[s] = 0` for the source node `s`, and `d[u]` is infinite for every other node `u`.) Take now any stretched edge and **relax** it by unpinning and re-pinning its lower end, so that the distance between its ends become equal the the edge's "natural" length at rest. This operation may relax some other edges as well, or even make them "loose" (with the physical distance between the ends smaller than the edge's "natural" length). This operation may as well stretch some other edges which were "loose" or "relaxed" before. If `d[u]` denotes the length of the currently known shortest path from the source `s` to the node `u`, then at this moment `u` is pinned at the distance `d[u]` under `s`. In this configuration, an edge `e` from `u` to `v` is *stretched* if and only if its ("natural") length is less than the absolute value `|d[u] - d[v]|` (the physical distance between `u` and `v`), *relaxed* if its length equals `|d[u] - d[v]|`, and *loose* if its length is greater than `|d[u] - d[v]|`. [accepted answer]: https://stackoverflow.com/a/12782683 [another answer]: https://stackoverflow.com/a/71385258 [video]: https://youtu.be/2E7MmKv0Y24?si=v8bqjhSoPnwwRH3H&t=1835
SQLite query not returning expected results despite correct hashing and comparison in Android application"
SQLite query not returning expected results despite correct hashing and comparison in Android application
Just for laffs; this has the benefit of showing both lines where `old` and `mat` bars collide, but complicates things beyond what OP seems to be asking for. ``` r library(ggplot2) library(dplyr) library(tidyr) d <- data.frame(grp=c('a','b','c'), fmlb=c(100,115,125), old=c(20,35,15), mat=c(10,15,5)) d %>% mutate(fmlb = fmlb - old - mat) %>% pivot_longer(-grp) -> d1 ggplot(data = d1, aes(x = grp, y = value, fill = grp, color = name)) + geom_bar(stat = "identity", linewidth = ifelse(d1[["name"]] == "fmlb", 0, 1)) + geom_errorbar(data = d, aes(y=old,ymin=old,ymax=old), colour="black") + scale_color_manual(name = "Legendary", values = c("mat" = "green", "old" = "black"), guide = guide_legend(order = 2), labels = c("Mature", "Old")) + guides(color=guide_legend(override.aes=list(fill=NA))) + ylab("fmlb") ``` ![](https://i.imgur.com/gBL95g2.png)<!-- --> <sup>Created on 2024-03-26 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>
MarkerInfoWindow doesn't hold the clicked marker position after list refresh in Compose Map
|android|kotlin|google-maps|android-jetpack-compose|google-maps-markers|
null
if you want to inherit 2 classes, you can also do it this way class B: def __init__(self, param1='hello from B'): print('start B __init__')`enter code here` self.param1=param1 class C: def __init__(self, param2='hello from C'): print('start C __init__') super().__init__() print('end C __init__') self.param2 = param2 class D(C,B): def __init__(self, param='hello from D'): super().__init__() print('start D __init__') print(self.param1,self.param2) d = D() The super().__init__ in the C_class calls the constructor of B_Class any number of functions can be inserted as long as the inherited class calls the next one class B: def __init__(self, param1='hello from B'): print('start B __init__') self.param1=param1 class C: def __init__(self, param2='hello from C'): print('start C __init__') super().__init__() print('end C __init__') self.param2 = param2 class E: def __init__(self, param3='hello from E'): print('start E __init__') super().__init__() print('end E __init__') self.param3=param3 class D(C,E,B): def __init__(self, param='hello from D'): super().__init__() print('start D __init__') print(self.param1,self.param2) d = D() And if you don't want to pay attention to which class comes first, you can provide all classes with super().__init_() class B: def __init__(self, param1='hello'): print('start B __init__') super().__init__() self.param1=param1 then can you class D(E,C,B): def __init__(self, param='hello from D'): super().__init__() class D(B,C,E): def __init__(self, param='hello from D'): super().__init__() class D(C,B,E): def __init__(self, param='hello from D'): super().__init__()
I am trying to transform a pandas series which has dates in it. I'd like to take the date that is in there and return the following Monday. Here is what I have tried: ``` db['date'] = datetime.date.fromisocalendar(db['date'].dt.year.astype(np.int64),(db['date'].dt.week+1).astype(np.int64),1) ``` But I get the following error: ``` TypeError: 'Series' object cannot be interpreted as an integer ``` Is there a better way to do this?
How to convert pandas series to integer for use in datetime.fromisocalendar
|python|pandas|datetime|series|
# I want to connect to database and do normal login and registration process - details from registration should be stored in data.db and can be retrieved by login for login purpose that is what i want but as i am new to all database and stuff so its kinda hard ![This is Directories for all](https://i.stack.imgur.com/Ahyjt.png) # This is my Registration html - ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Signup</title> <link rel="stylesheet" href="style_signup.css"> </head> <body> <header> <h1 class="logo">Jigoku</h1> <nav class="navigation"> <a href="../index.html">Home</a> <a href="../About/about.html">About</a> <a href="../Download/download.html">Download</a> <a href="" class="active">Signup</a> </nav> </header> <section> <img src="/signup/background.jpg" class="back"> </section> <div class="wrapper"> <div class="form-box"> <h2>Register</h2> <form action="/signup/Register/register.py" method="post"> <div class="input-box"> <span class="icon"><ion-icon name="Person"></ion-icon></span> <input type="text" name="username" required> <label>Username</label> </div> <div class="input-box"> <span class="icon"><ion-icon name="mail"></ion-icon></span> <input type="email" name="email" required> <label>Email</label> </div> <div class="input-box"> <input type="password" name="password" id="password" required> <label for="password">Password</label> <ion-icon name="eye" class="icon" onclick="togglePasswordVisibility()"></ion-icon> </div> <div class="remember-forget"> <label><input type="checkbox" name="agree">Agree to T&Cs</label> <a href="../../About/about.html">T&cs Documentations</a> </div> <button type="submit" class="btn">Register</button> <div class="login-register"> <p>Already have an account?<a href="../index_signup.html" class="register-link">Login</a></p> </div> </form> </div> </div> <div class="wrapper"> <div class="form-box"></div> </div> <script src="script_signup.js"></script> <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script> </body> </html> ``` # This is my login html - ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="style_signup.css"> </head> <body> <header> <h1 class="logo">Jigoku</h1> <nav class="navigation"> <a href="../index.html">Home</a> <a href="../About/about.html">About</a> <a href="../Download/download.html">Download</a> <a href="" class="active">Login</a> </nav> </header> <section> <img src="/signup/background.jpg" class="back"> </section> <div class="wrapper"> <div class="form-box"> <h2>Login</h2> <form action="/signup/login.py" method="post"> <div class="input-box"> <span class="icon"><ion-icon name="mail"></ion-icon></span> <input type="email" name="email" required> <label>Email</label> </div> <div class="input-box"> <input type="password" name="password" id="password" required> <label for="password">Password</label> <ion-icon name="eye" class="icon" onclick="togglePasswordVisibility()"></ion-icon> </div> <div class="remember-forget"> <label><input type="checkbox" name="remember">Remember me</label> <a href="#">Forgot password?</a> </div> <button type="submit" class="btn">Login</button> <div class="login-register"> <p>Don't have an account?<a href="./Register/index_signup.html" class="register-link">Register</a></p> </div> </form> </div> </div> <div class="wrapper"> <div class="form-box"></div> </div> <script src="script_signup.js"></script> <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script> </body> </html> ``` # And here is my register.py file ``` from flask import Flask, render_template, request, jsonify import sqlite3 app = Flask(__name__) @app.route('/signup/Register/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form['username'] email = request.form['email'] password = request.form['password'] conn = sqlite3.connect('../users.db') cursor = conn.cursor() try: cursor.execute('INSERT INTO users (username, email, password) VALUES (?, ?, ?)', (username, email, password)) conn.commit() conn.close() return jsonify({'success': True, 'message': 'Registration successful'}) except sqlite3.IntegrityError: conn.close() return jsonify({'success': False, 'message': 'Username or email already exists'}) else: return render_template('signup/Register/index_signup.html') if __name__ == '__main__': app.run(debug=True) ``` # and login.py file ``` from flask import Flask, request, jsonify, redirect import sqlite3 app = Flask(__name__) @app.route('/login', methods=['POST']) def login(): email = request.form['email'] password = request.form['password'] conn = sqlite3.connect('users.db') cursor = conn.cursor() cursor.execute('SELECT * FROM users WHERE email=? AND password=?', (email, password)) user = cursor.fetchone() conn.close() if user: # Redirect to a success page return redirect('/success') else: # Redirect to a failure page return redirect('/failure') if __name__ == '__main__': app.run(debug=True) ``` I tried running the python files and it give 404 error of file not found after asking GPT it said it was most likely @app.route(/register) where the problem is but i am new to flask and don't know what is this
I have a React JS website being served by an Express JS Backend. My app has an api to fetch data from a database, and then at the end sends the built website. Here is my index.js in my backend: ``` const express = require('express'); const path = require('path'); const cors = require('cors'); require('dotenv').config(); const app = express(); const frontEndPath = path.join(__dirname, '..', 'frontend', 'build') app.use(cors()); app.use(express.json()); app.use(express.static(frontEndPath)); app.get('/api', (req, res) => { res.send('Hello from the API!') }) // Various API Routes From Different Files I Have Omitted app.get('/*', (req, res) => { res.sendFile(path.join(frontEndPath, 'index.html')); }); const PORT = process.env.PORT; app.listen(PORT, () => { console.log('Running on port', PORT); }); ``` One of the pages of the React site has a parameter in its URL, and it works just fine except when I reload that page or try to get to it directly from the URL. At that stage it doesn't show the usual "Could not get /<path-here>", and also doesn't show the page I have for an invalid parameter - it just shows completely blank. I have tried tweaking the /* route and adding a separate route for that page, but haven't had any success. I've probably missed something, but I can't find the answer anywhere.
null
|typescript|next.js|next.js13|react-server-components|
I use shader in phaserjs to change the color of characters and also for rain But the game renders correctly in Google Chrome, but I have a rendering problem in Capacitor, in such a way that the rain is displayed in the form of a ruler. Hardware acceleration
Shader rendering problem in capacitor phaserjs in webgl mode
|webgl|capacitor|phaserjs|
null
<!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, UserId: { allowNull: false, type: Sequelize.INTEGER, references: { model: "Users", key: "id" } }, HeroId: { allowNull: false, type: Sequelize.INTEGER, references: { model: "Heros", key: "id" } }, match: { allowNull: false, type: Sequelize.INTEGER }, status: { allowNull: false, type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); <!-- end snippet -->
I'm traying to launch a Nextflow pipeline, but it throws the following error: ``` ERROR ~ No signature of method: groovyx.gpars.dataflow.DataflowBroadcast.into() is applicable for argument types: (Script_dd34529ec87c0dd2$_runScript_closure3) values: [Script_dd34529ec87c0dd2$_runScript_closure3@39652a30] Possible solutions: any(), find(), bind(java.lang.Object), print(java.io.PrintWriter), find(groovy.lang.Closure), any(groovy.lang.Closure) ``` The error is thrown by this part of the code: ``` Channel .fromFilePairs("$root/**/*.trk", size: -1) { it.parent.name } .into{ tractogram; tractogram_for_check } // [sid, tractogram.trk] ``` I think the problem is that it can't find the file, but it is in the correct folder and has the correct name and extension. How could I solve it? The GitHub source code of [this pipeline](https://github.com/scil-vital/fiesta).
null
So, I managed to get it working finally, for some reason the client certs that were signed by the intermediate ca just didn't work, so I signed them with the root, and added the `ca.pem` to `ssl_ca_certs`. Thanks Maarten for your help, its really appreciated! For those that might be in a similar situation, the following was quite the help too: https://mtls.dev/
|regex|
I'm working on some code for a javascript implemenation of Conway's Game of Life Cellular Automata for a personal project, and I've reached the point of encoding the rules. I am applying the rules to each cell, then storing the new version in a copy of the grid. Then, when I'm finished calculating each cell's next state, I set the first grid's state to the second's one, empty the second grid, and start over. Here's the code I used for the rules: ``` if (Cell(i, j) == 1) { if (Nsum(i, j) == 2 || Nsum(i, j) == 3) ncells[j][i] = 1; else ncells[j][i] = 0; } else { if (Nsum(i, j) == 3) ncells[j][i] = 1; else ncells[j][i] = 0; } ``` Nsum is the function that calculates the neighborhood sum of the current cell. I say ncells[j][i] instead of ncells[i][j] because in a 2d array you adress the row first. I didn't try much, but I can't imagine a solution. Help!
null
**I'm trying to link to GLWF using GCC on Windows.** *I built the code locally on my computer, took the include and lib directories and deleted the rest of the files. Now I'm trying to link them to my code using a batch file and the gcc compiler.* **build.bat:** @echo off SET COMPILER_FLAGS= -I./Dependencies/GLFW/Include -I./Dependencies/GLFW/lib SET LINKER_FLAGS= -lopengl32 -lglfw3 gcc %COMPILER_FLAGS% -o foo.exe core/main.c %LINKER_FLAGS% **main.c:** #include <GLFW/glfw3.h> int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ glClear(GL_COLOR_BUFFER_BIT); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; } **File path:** [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/ORHX1.png **Errors** When including the -lglfw3 flag in *build.bat* I get error: > cannot find -lglfw3 When removing the -lglfw3 flag in *build.bat* I get errors: > undefined reference to `glfwInit' > undefined reference to `glfwCreateWindow' > undefined reference to `glfwTerminate' > undefined reference to `glfwMakeContextCurrent' > undefined reference to `glfwSwapBuffers' > undefined reference to `glfwPollEvents' > undefined reference to `glfwWindowShouldClose' > undefined reference to `glfwWindowShouldClose' > undefined reference to `glfwTerminate' When using -L./Dependencies/GLFW/lib in the linker flag instead of -I > Warning: corrupt .drectve at end of def file (x21) > undefined reference to `__security_cookie' > undefined reference to `_RTC_CheckStackVars' > many other undefined mingw32 references I've looked all over the place and I have run into similar problems, but I really didn't understand the issue wherever I went. The closest I got was a Reddit post about Arch Linux talking about how the linker automatically searches for folders that start with lib to add the .lib files in, and how you could manually set that for shell scripts. I tried that and it didn't work I don't know if it's because it's a bat file because I'm using windows and not a shell file like unix systems, or if it's because the problem is elsewhere.
I'm building a product where we use a board running Android 9. One of the programs I am building has to connect to a specific WiFi device without user interactions. Most of the time it connects with no problem, but sometimes it refuses to connects whatsoever. Here is the code I use: ``` public static boolean connectToWifiNetwork(String networkSSID, String networkPassword) { if (networkSSID == null || networkSSID.equals("")) return false; Log.v(TAG, "connected name: " + getConnectedWifiName()); if(getConnectedWifiName() != null && getConnectedWifiName().equals(networkSSID))return true; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedAuthAlgorithms.clear(); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); conf.priority = 400000; //4000; wifiManager.addNetwork(conf); List<WifiConfiguration> list = wifiManager.getConfiguredNetworks(); for (WifiConfiguration i : list) { if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) { wifiManager.disconnect(); wifiManager.enableNetwork(i.networkId, true); Log.v(TAG, "Trying to connect"); wifiManager.reconnect(); wifiManager.reassociate(); wifiManager.reconnect(); wifiManager.reassociate(); try { Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } if (checkWifiConnection().equals(WifiState.CONNECTED)) return true; return false; ``` It is worth noting that this WiFi device is open (meaning no password). Also, I can connect to that device using my personal phone with no problems. Any ideas how to solve this issue? I tried to change the way I connect to the WiFi device, but that didn't change the outcome.
I am trying to create a *whack-a-mole* type of game in Java but when I run my program the images do not show up. Here is my code so far and I will add the images as well. I am also fairly new to coding so this might be an easy fix. [kuronomi.gif](https://i.stack.imgur.com/43340.gif) [kitty.gif](https://i.stack.imgur.com/NmPys.gif) [This is what I see when I run my program](https://i.stack.imgur.com/OHB5f.png) ```java import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class hellokitty { int screenWidth = 700; int screenHeight = 800; JFrame frame = new JFrame("Catch Hello Kitty!"); JLabel textL = new JLabel(); JPanel textP = new JPanel(); JPanel boardP = new JPanel(); JButton[] board = new JButton[9]; ImageIcon kittyIcon; ImageIcon kuroIcon; JButton currentKittyTile; JButton currentKurTile; Random r = new Random(); Timer setKittyTimer; Timer setKuroTimer; hellokitty(){ //frame.setVisible(true); frame.setSize(screenWidth, screenHeight); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); textL.setFont(new Font("Comic Sans MS", Font.PLAIN, 70)); textL.setHorizontalAlignment(JLabel.CENTER); textL.setText("Score: 0"); textL.setOpaque(true); textP.setLayout(new BorderLayout()); textP.add(textL); frame.add(textP, BorderLayout.NORTH); boardP.setLayout(new GridLayout(3,3)); boardP.setBackground(Color.pink); frame.add(boardP); Image KittyImg = new ImageIcon(getClass().getResource("./kitty.gif")).getImage(); kittyIcon = new ImageIcon(KittyImg.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH)); Image KuronomiImg = new ImageIcon(getClass().getResource("./kuronomi.gif")).getImage(); kuroIcon = new ImageIcon(KuronomiImg.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH)); for (int i = 0; i < 9; i ++){ JButton tile = new JButton(); board[i] = tile; boardP.add(tile); // tile.setIcon(kuroIcon); tile.setFocusable(false); } setKittyTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentKittyTile != null) { currentKittyTile.setIcon(null); currentKittyTile = null; } int num = r.nextInt(9); JButton tile = board[num]; currentKittyTile = tile; currentKittyTile.setIcon(kittyIcon); } }); setKuroTimer = new Timer(1500, new ActionListener() { public void actionPerformed(ActionEvent e){ if (currentKurTile != null){ currentKurTile.setIcon(null); currentKurTile = null; } int num = r.nextInt(9); JButton tile = board[num]; currentKurTile = tile; currentKurTile.setIcon(kuroIcon); } }); setKittyTimer.start(); setKuroTimer.start(); frame.setVisible(true); } } ```
|java|swing|
How do I set custom attributes on a user who signs up via amplify's Authenticator?
|amazon-cognito|aws-amplify|aws-marketplace|
My approach would be 100 - ((100/(highest - lowest)+1))*(triescount)) for example triescount = 3, highest = 20, lowest = 1, 100/20 = 5, 5*3 = 15, 100 - 15 =85 so 85% accuracy This is probably the easiest way of implementing accuracy
So I have a scientific data Excel file validation form in django that works well. It works iteratively. Users can upload files as they accumulate new data that they add to their study. The `DataValidationView` inspects the files each time and presents the user with an error report that lists issues in their data that they must fix. We realized recently that a number of errors (but not all) can be fixed automatically, so I've been working on a way to generate a copy of the file with a number of fixes. So we rebranded the "validation" form page as a "build a submission page". Each time they upload a new set of files, the intention is for them to still get the error report, but also automatically receive a downloaded file with a number of fixes in it. I learned just today that there's no way to both render a template and kick off a download at the same time, which makes sense. However, I had been planning to not let the generated file with fixes hit the disk. Is there a way to present the template with the errors and automatically trigger the download without previously saving the file to disk? This is my `form_valid` method currently (without the triggered download, but I had started to do the file creation before I realized that both downloading and rendering a template wouldn't work): ``` def form_valid(self, form): """ Upon valid file submission, adds validation messages to the context of the validation page. """ # This buffers errors associated with the study data self.validate_study() # This generates a dict representation of the study data with fixes and # removes the errors it fixed self.perform_fixes() # This sets self.results (i.e. the error report) self.format_validation_results_for_template() # HERE IS WHERE I REALIZED MY PROBLEM. I WANTED TO CREATE A STREAM HERE # TO START A DOWNLOAD, BUT REALIZED I CANNOT BOTH PRESENT THE ERROR REPORT # AND START THE DOWNLOAD FOR THE USER return self.render_to_response( self.get_context_data( results=self.results, form=form, submission_url=self.submission_url, ) ) ``` Before I got to that problem, I was compiling some pseudocode to stream the file... This is totally untested: ``` import pandas as pd from django.http import HttpResponse from io import BytesIO def download_fixes(self): excel_file = BytesIO() xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') df_output = {} for sheet in self.fixed_study_data.keys(): df_output[sheet] = pd.DataFrame.from_dict(self.fixed_study_data[sheet]) df_output[sheet].to_excel(xlwriter, sheet) xlwriter.save() xlwriter.close() # important step, rewind the buffer or when it is read() you'll get nothing # but an error message when you try to open your zero length file in Excel excel_file.seek(0) # set the mime type so that the browser knows what to do with the file response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=myfile.xlsx' return response ``` So I'm thinking either I need to: 1. Save the file to disk and then figure out a way to make the results page start its download 2. Somehow send the data embedded in the results template and sent it back via javascript to be turned into a file download stream 3. Save the file somehow in memory and trigger its download from the results template? What's the best way to accomplish this? *UPDATED THOUGHTS*: I recently had done a simple trick with a `tsv` file where I embedded the file content in the resulting template with a download button that used javascript to grab the `innerHTML` of the tags around the data and start a "download". I thought, if I encode the data, I could likely do something similar with the excel file content. I could base64 encode it. I reviewed past study submissions. The largest one was 115kb. That size is likely to grow by an order of magnitude, but for now 115kb is the ceiling. I googled to find a way to embed the data in the template and I got [this][1]: ``` import base64 with open(image_path, "rb") as image_file: image_data = base64.b64encode(image_file.read()).decode('utf-8') ctx["image"] = image_data return render(request, 'index.html', ctx) ``` I recently was playing around with base64 encoding in javascript for some unrelated work, which leads me to believe that embedding is do-able. I could even trigger it automatically. Anyone have any caveats to doing it this way? ## Update I have spent all day trying to implement @Chukwujiobi_Canon's suggestion, but after working through a lot of errors and things I'm inexperienced with, I'm at the point where I am stuck. I don't have any errors, and my server console shows a request that comes in, but the form data doesn't seem to be (correctly) accompanying the `post`. I implemented the django code first and I think it is working correctly. When I submit the form without the javascript, the browser downloads the multipart stream, and it looks as expected: ``` --3d6b6a416f9b5 Content-Type: application/octet-stream Content-Range: bytes 0-9560/9561 PK?N˝Ö€]'[Content_Types].xm... ... --3d6b6a416f9b5 Content-Type: text/html Content-Range: bytes 0-16493/16494 <!--use Bootstrap CSS and JS 5.0.2--> ... </html> --3d6b6a416f9b5-- ``` In the chat, @Chukwujiobi_Canon advised me how to submit the form in javascript and make the resulting multipart stream start a download and open a new tab for the error report/html. I worked with it until I got past all the errors, but I don't know why the form data isn't getting sent and/or processed. Here's the javascript: ``` document.addEventListener("DOMContentLoaded", function(){ validation_form = document.getElementById("submission-validation"); // Take over form submission validation_form.addEventListener("submit", (event) => { event.preventDefault(); submit_validation_form(); }); async function submit_validation_form() { // Put all of the form data into a variable (formdata) const formdata = new URLSearchParams(); for (const pair of new FormData(validation_form)) { formdata.append(pair[0], pair[1]); } try { // Submit the form and get a response (which can only be done inside an async function) alert("Submitting form"); let response; response = await fetch("{% url 'validate' %}", { method: "post", body: formdata, //I commented out the headers based on my googling on the topic... //headers: { //"Content-Type": "multipart/form-data", // "Content-Type": "application/x-www-form-urlencoded", //}, }) alert("Processing result"); let result; result = await response.text(); const parsed = parseMultipartBody(result, "{{ boundary }}"); alert("Starting download and rendering page"); parsed.forEach(part => { if (part["headers"]["content-type"] === "text/html") { const url = URL.createObjectURL( Blob( part["body"], {type: "text/html"} ) ); windows.open(url, "_blank"); } else if (part["headers"]["content-type"] === "application/octet-stream") { const url = URL.createObjectURL( Blob( part["body"], {type: "application/octet-stream"} ) ); window.location = url; } }); } catch (e) { console.error(e); } } function parseMultipartBody (body, boundary) { return body.split(`--${boundary}`).reduce((parts, part) => { if (part && part !== '--') { const [ head, body ] = part.trim().split(/\r\n\r\n/g) parts.push({ body: body, headers: head.split(/\r\n/g).reduce((headers, header) => { const [ key, value ] = header.split(/:\s+/) headers[key.toLowerCase()] = value return headers }, {}) }) } return parts }, []) } }) ``` The alerts all come up, but happen too quick. The file I'm submitting should generate about 20 seconds worth of server console output, but all I get is one line: ``` [30/Mar/2024 18:52:49] "POST /DataRepo/validate HTTP/1.1" 200 19974 ``` [1]: https://nemecek.be/blog/8/django-how-to-send-image-file-as-part-of-response
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 { get; private set; } protected override void OnInitialized() { if(Lifetime != null) { _cts = CancellationTokenSource.CreateLinkedTokenSource(Lifetime.ApplicationStopping); Cancel = _cts.Token; } } public void Dispose() { GC.SuppressFinalize(this); if(_cts != null) { _cts.Cancel(); _cts.Dispose(); _cts = null; } } } ```
|android|react-native|react-navigation|deep-linking|react-native-navigation|
I'm working on a small project where I take content from an Excel Spreadsheet and put it into a word document. I can get the two applications to communicate and put the text in the correct spot, but I cannot change the formatting and I've tried multiple ways. I think I don't understand the Range object, but I'm really not sure. Below is the code. Essentially what I want it the label ("Severity") to be bolded, and then the content, which is coming from the spreadsheet to NOT be bold. Like this: Severity: Moderate I can get it to bold the entire thing or not, but I can't get the code to bold just the label. Appreciate any help someone can provide. Many thanks. Here's the code I have so far: ```vb Sub TestBoldToWordDocument() Dim wdApp As Object Dim wdDoc As Object Dim ExcelRange As Range Dim WordRange As Object Dim TextToPaste As String Dim tblNew As Table Dim intX As Integer Dim intY As Integer Sheets("CleanSheet").Activate ' Create a new Word application Set wdApp = CreateObject("Word.Application") wdApp.Visible = True ' Set to True if you want Word to be visible ' Create a new Word document Set wdDoc = wdApp.Documents.Add Set WordRange = wdDoc.Content With WordRange .InsertAfter "Severity: " .Font.Bold = True End With With WordRange .InsertAfter Sheets("CleanSheet").Cells(2, 2).Value & vbCr .Font.Bold = False End With End Sub ```
Express JS Serve React JS Site With Path Longer Than Just Subdirectory
|reactjs|node.js|express|
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: ``` typedef struct Student{ int q; vector<Course> courses; }; struct Course{ string name; int credit; int point; }; ``` [enter image description here][1] [1]: https://i.stack.imgur.com/wxVYj.png
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: ``` typedef struct Student{ int q; vector<Course> courses; }; struct Course{ string name; int credit; int point; }; ``` [error][1] [1]: https://i.stack.imgur.com/wxVYj.png
Here's a "prettier" version of all this. SpringDoc provides their own static method set to automatically add unresolved schemas to the components (and OpenAPI object respectively), so they can be referenced from other places. ```java import io.swagger.v3.core.util.AnnotationsUtils; @Bean public OpenApiCustomiser errorCustomizer() { return api -> api.getPaths().values().forEach(path -> path.readOperations() .forEach(operation -> addErrorToApi(operation, api.getComponents()))); } private void addErrorToApi(Operation operation, Components components) { MediaType mediaType = new MediaType().schema(AnnotationsUtils.resolveSchemaFromType(Error.class, components, null)); operation.getResponses().addApiResponse("500", new ApiResponse() .description("Unhandled Server Error") .content(APPLICATION_JSON_VALUE, mediaType); } ``` Tested with Java 8 + Spring Boot 2.7.18 + SpringDoc UI 1.8.0, no problems so far. NOTE: `AnnotationsUtils.resolveSchemaFromType()` returns REFERENCED schema, not the original one. That means that it won't have provided examples in fields, etc. To override examples, you need to access `Components` object and extract schema by your schema name (annotated classes' simple name by default): ```java components.getSchemas().get(Error.class.getSimpleName()); ``` EDIT: it also introspects and adds all child schemas, so by calling one `resolveSchemaFromType()` you will have all schemas correctly added and referenced in your API components. Here is an example of my class that I had problem with adding by calling plain `ModelConverters` method: ```java @Schema @Getter @Setter // lombok annotations public class Error { private List<NestedError> nestedErrors; @Schema @Getter @Setter public static class NestedError { private ErrorField; private String reason; } @Schema @Getter @Setter public static class ErrorField { // ... } } ``` When calling `MediaConverters` manually, I had to register child schemas in addition to the `Error` schema.
Here is the original problem: > Now consider a deterministic linear search algorithm, which we refer to as DETERMINISTIC-SEARCH. Specifically, the algorithm searches for in order, considering [1],[2],A[3]...[] until either it finds [] = or it reaches the end of the array. Assume that all possible permutations of the input array are equally likely. > > (e) Suppose that there is exactly one index such that [] = . What is the average-case running time of DETERMINISTIC-SEARCH? What is the worstcase running time of DETERMINISTIC-SEARCH? > > (f) Generalizing your solution to part (e), suppose that there are ≥ 1 indices such that [] = . What is the average-case running time of DETERMINISTICSEARCH? What is the worst-case running time of DETERMINISTIC-SEARCH? > > Your answer should be a function of and . I can find the answer to (f) on the website: > The worst-case running time is −+1. The average-case running time is (+1)/(+1). Let <sub></sub> be an indicator random variable that the <sup>th</sup> element is a match. Then Pr(<sub></sub>) is 1/(+1) Why the Pr(<sub></sub>) is like this? > Let be an indicator random variable that we have found a match after the first −+1 elements (Pr() = 1) > > Thus () = (<sub>1</sub> + <sub>2</sub> + ... + <sub>−</sub> + ) > > &nbsp; &nbsp; &nbsp; = 1 + <sub>=1</sub>∑<sup>−</sup> (<sub></sub>) > > &nbsp; &nbsp; &nbsp; = 1 + ( − ) / ( + 1) > > &nbsp; &nbsp; &nbsp; = ( + 1) / ( + 1) Why they split into <sub>1</sub> , ... , <sub>−</sub> , ?