instruction
stringlengths
0
30k
smtplib send email with set email image
|python|smtp|smtplib|
null
I ran into the exact issue above from the LinkedIn course "**Building Modern Projects with React**". My project has these versions **"webpack": "^5.91.0",<br> "webpack-cli": "^5.1.4",<br> "webpack-dev-server": "^5.0.4"** ## webpack.config.js ``` const path = require('path'); const webpack = require('webpack'); module.exports = { entry: './src/index.js', mode: 'development', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /(node_modules)/, loader: 'babel-loader', options: { presets: ["@babel/env"] } }, { test: /\.css$/, use: ["style-loader", "css-loader"] } ] }, resolve: { extensions: ['*', '.js', '.jsx'] }, output: { path: path.resolve(__dirname, 'dist/'), publicPath: '/dist/', filename: 'bundle.js' }, devServer: { static : { directory : path.join(__dirname, 'public/') }, port: 3000, devMiddleware:{ publicPath: 'https://localhost:3000/dist/', }, hot: 'only', }, plugins: [new webpack.HotModuleReplacementPlugin()], }; ```
I have page.tsx component where I need to get the current pathname, so it's a **client component**. Then I have a **child server component** where I would like to fetch data based on the pathname passed as prop. However, when I try to fetch the data I get these errors: > Uncaught (in promise) Error: Failed to fetch data. at fetchRadio > Access to fetch at 'https://api.example.com' from origin > 'http://localhost:3000' has been blocked by CORS policy: No > 'Access-Control-Allow-Origin' header is present on the requested > resource. If an opaque response serves your needs, set the request's > mode to 'no-cors' to fetch the resource with CORS disabled. The parent component: "use client"; import * as React from "react"; import Radio from "@/components/ui/radio/radio"; import { usePathname } from "next/navigation"; export default function Page() { const pathName = usePathname(); return <Radio pathName={pathName} />; } Child server component: import * as React from "react"; import { fetchRadio } from "@/lib/data"; export default async function Radio({ pathName }: { pathName: string }) { const radio = await fetchRadio(pathName); return ( {/* ... */} ); } Fetch function: export async function fetchRadio(pathName: string){ try { const radios = await fetch("https://api.example.com"); const data = await radios.json(); console.log(pathName); // for now I just want to log the pathname } catch (error) { console.error("Error:", error); throw new Error("Failed to fetch data."); } }
Finally, I found the solution myself. I removed the single quote around the '{request.Data!.UserId}' and it worked fine. _db.Database.SqlQuery<CreateOrderInfo>($"select * from Asset_CreateOrderInfo({request.Data!.UserId},{request.Data!.SymbolId})") It was really a ridiculous problem!!!
{"Voters":[{"Id":22356960,"DisplayName":"pindakazen"}]}
I am creating a simple flight search website in React. I want the user to be able to search a destination (i.e. Boston), and as they are typing it in have location suggestions appear that they can then select. For this purpose I am using an autocomplete API, which returns a maximum of 5 location objects depending on the current search. The problem is that my implementation makes a ton of API calls, which with real users would become expensive quickly. Right now I make a call to the API every time the user inputs a keystroke using the onChange() function in a form input field. Is this the standard for autocomplete APIs, or is there a way to minimize the number of API calls made? I am currently using a button in order to fetch info after the user has inputted their destination, as the autocomplete API calls are too expensive.
How to minimize number of API calls for an autocomplete field in React
|reactjs|
null
I didn't actually receive any answer within nearly 20 hours, and the only solution I found was to reset the window layout. `Window` -&gt; `Reset Window Layout` -&gt; `Yes`. [![enter image description here][1]][1] [![enter image description here][2]][2] You'll notice that things like Solution Explorer or Toolbox will reset their width to their defaults. Floating (windowed) dialogs will also disappear. But more importantly, the Output dialog will now look like the default: [![enter image description here][3]][3] I'd recommend selecting `Window` -&gt; `Save Window Layout` first and then giving the window layout name, so that the window layout is saved in case to revert the window layout again. To revert it, select `Window` - &gt; `Apply Window Layout`, and click on the name of the window layout saved. If someone posts an answer that provides a solution to this problem without resetting window layout or other settings, I will definitely mark it as accepted. [1]: https://i.stack.imgur.com/jp0pU.png [2]: https://i.stack.imgur.com/5ib1i.png [3]: https://i.stack.imgur.com/eoyoW.png
so consider the code below, when I resolve a `promise` the result is in `pending` state in the very first moment( I know after I expand the dropdown I will see the expected result but in here I'm questioning the very first moment), while I reject a promise, it shows the expected result in very first moment. so I wonder why is this happening? code: const test = new Promise((resolve, reject) => { resolve(Promise.resolve(78)) }) console.log(test); //output in console:Promise {<pending>} <!--end-snippet--> const test2 = new Promise((resolve, reject) => { reject(Promise.resolve(78)) }) console.log(test2); //output:promise {<rejected>: Promise}
why when I resolve a promise, the output is in pending state?
|tensorflow|machine-learning|computer-vision|artificial-intelligence|data-analysis|
null
I am trying to build an app that uses Media3 by following this: https://developer.android.com/media/media3/exoplayer/hello-world#kts When I try to add dependencies in my app for its build.gradle.kts Android Studio does not like the syntax given in the above link. Can someone help tell me what I am missing. P.S. I am doing the kts way not the groovy way as it is the recommended way. Currently, when I build default empty activity app from Android Studio, my build.gradle.kts looks like: ``` ..... dependencies { implementation(libs.androidx.core.ktx) implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.activity.compose) implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.ui) implementation(libs.androidx.ui.graphics) implementation(libs.androidx.ui.tooling.preview) implementation(libs.androidx.material3) testImplementation(libs.junit) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) androidTestImplementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.ui.test.junit4) debugImplementation(libs.androidx.ui.tooling) debugImplementation(libs.androidx.ui.test.manifest) } ``` According to android link https://developer.android.com/media/media3/exoplayer/hello-world#kts when I paste: ``` .... implementation("androidx.media3:media3-exoplayer:1.3.0") implementation("androidx.media3:media3-exoplayer-dash:1.3.0") implementation("androidx.media3:media3-ui:1.3.0") .... ``` It gives me following warning: > Use version catalog instead More... (⌘F1) > Inspection info:If your project is using a libs.versions.toml file, you should place all Gradle dependencies in the TOML file. This lint check looks for version declarations outside of the TOML file and suggests moving them (and in the IDE, provides a quickfix to performing the operation automatically) So: 1. What is the correct way to add media3 dependencies for latest Android Studi - Iguana 2. Why my default build.gradle.kts for hello world project dependencies format look so different than the one provided in https://developer.android.com/media/media3/exoplayer/hello-world#kts. Default one like something like implementation(libs.androidx.material3), starts with libs. Please help, I am confused.
Media3 dependencies for build.gradle.kts for Android Studio 2023.2.1 Patch 2
|android-studio|android-media3|
null
Have a usecase where i was trying to parse fixedlength file with huge load with beanio approach in my spark code and was getting timeout or OOM issue . Do we have any non beanio approach to read complex and very large fixedlength file using spark code ? My approach for single record type of flat file was so quick that i was able to process 10GB file within a minute. but this approach does not work with multi record type of flatfile. Existing approach: 1. Create csv file for schema - metadata file ``` col_name,size product_id,2 first_name,10 last_name,10 ``` 2. Read the flatfile using csv as metadat file to load schema of flatfile as below: ``` JavaRDD<String> rdd = session.sparkContext().textFile("/path_to_fixedlength_file", 0).toJavaRDD(); Dataset<Row> metadata = session.read() .option("header", "true") .csv("/path_to_csv_metadata"); List<String> header = metadata.select("col_name").toJavaRDD().map(row -> row.getString(0).trim()).collect(); List<Integer> sizeOfColumn = metadata.select("size").javaRDD().map(row -> Integer.parseInt(row.getString(0).trim())).collect(); List<StructField> fields = new ArrayList<>(); for (String fieldName : header) { fields.add(DataTypes.createStructField(fieldName, DataTypes.StringType, true)); } StructType schema = DataTypes.createStructType(fields); Dataset<Row> df = session.createDataFrame(rdd.map(row -> lsplit(sizeOfColumn, row)), schema); df.show(5) ``` Aoove approach works only with single record type, can anyone suggest any good approach to load multiple record type fixedlength file. In csv metadata we cannot have multiple headers to parse the fixedlength file . Please provide inputs.
How would i use a prefab gameobject clone as a player target for a navmesh agent in unity version 2022.3f
|c#|unity-game-engine|navmesh|
null
From what I can tell, your data are in various cells in the first 3 tables in the document. In that case, you need something like: Sub GetData() 'Note: this code requires a reference to the Word object model. 'See under the VBA Editor's Tools|References. Application.ScreenUpdating = False Dim WkSht As Worksheet, r As Long, c As Long Dim wdApp As New Word.Application, wdDoc As Word.Document, wdRng As Word.Range Dim strFile As String, strFolder As String strFolder = "C:\Users\" & Environ("UserName") & "\Desktop\Macro VBA - Trabalhos Sequenciais\Trabalhos\" Set WkSht = ActiveSheet: r = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row strFile = Dir(strFolder & "\*.doc", vbNormal) While strFile <> "" r = r + 1: c = 1 Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False) WkSht.Cells(r, c).Value = Split(strFile, ".doc")(0) With wdDoc With .Tables(1) Set wdRng = .Cells(1, 1).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) Set wdRng = .Cells(1, 2).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) Set wdRng = .Cells(1, 3).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) End With With .Tables(2) Set wdRng = .Cells(1, 2).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) Set wdRng = .Cells(1, 4).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) Set wdRng = .Cells(2, 2).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) Set wdRng = .Cells(3, 2).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) Set wdRng = .Cells(4, 2).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) End With With .Tables(3) Set wdRng = .Cells(2, 1).Range: c = c + 1 WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0) End With .Close SaveChanges:=False End With strFile = Dir() Wend wdApp.Quit Set wdRng = Nothing: Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing Application.ScreenUpdating = True End Sub
When trying to add existing/New item, getting error message like "Cannot access to disposed object". To resolve that making the method to run asynchronously and it got resolved, but due to that getting some delay in extension after opening the project.In this method first getting "Cannot access to disposed object" error. private void ProjectItemsEvents_AfterAddProjectItems () { } After making it to asynchronous method, getting delay in extension. private async void asynchronous () { await System.Threading.Tasks.Task.Run(() => ProjectItemsEvents_AfterAddProjectItems(); } Need to know, how to remove the delay causing by the asynchronous method
"Visual Studio stopped responding for 12 seconds,uninstalling extension might help" getting this message on installing VSIX and on opening the project
I am building two programs that run independently of each other. I wish to make output of one program (JAVA) as input to another program (Verilog) and vice-versa. I am building a calculator and have to do calculations in Verilog but UI in Java. Both programs run on the same device. Also how to invoke Verilog program when java program UI is invoked by the user??? I right now have no idea except for somehow making a pipe between two programs/read between ports or something or maybe make use of files to store and read data. I don't know how to make named pipes in Verilog so please do tell. Also how shared memory can be achieved between JAVA and VERILOG is another thing.
Communicate/transfer data between two different programs. JAVA & VERILOG
|java|verilog|ipc|serial-communication|iverilog|
null
|python|sql|
null
hope all is well. I am receiving the following error codes in my output. I am using Icarus Verilog, with VSCode as my IDE. Would anyone know how to resolve this? **No top level modules, and no -s option.** This issue has occurred in one other instance before and I was not sure how to proceed. `timescale 1ns / 1ps // Definition of the 8-bit combinational shifter module module combinational_shifter( input [7:0] A, input [3:0] n, input dir, output reg [7:0] Y ); always @(*) begin if (dir == 1'b0) // If dir is 0, shift to the right Y = A >> n; else // Otherwise, shift to the left Y = A << n; end endmodule // Testbench module for the combinational shifter module combinational_shifter_tb; // Inputs to the shifter reg [7:0] A; reg [3:0] n; reg dir; // Output from the shifter wire [7:0] Y; // Instantiate the Unit Under Test (UUT) combinational_shifter uut ( .A(A), .n(n), .dir(dir), .Y(Y) ); initial begin // Initialize Inputs A = 8'b10101010; // Example input to test dir = 0; // Start with right shift n = 0; // Test all possible shifts for (n = 0; n < 16; n = n + 1) begin #10; // Delay to observe changes $display("Right Shift: A = %b, n = %d, Result = %b", A, n, Y); end dir = 1; // Change to left shift for (n = 0; n < 16; n = n + 1) begin #10; // Delay to observe changes $display("Left Shift: A = %b, n = %d, Result = %b", A, n, Y); end end endmodule
Error message coming up when compiling iVerilog Code
|verilog|
null
Here is my solution fun getMemberName(source: Any, member: Any, prefix: String = "") : String { val res = source::class.declaredMemberProperties.firstOrNull { it.getter.call(source) == member }?.name if(res != null) { return prefix + res } source::class.declaredMemberProperties.filter { !it.getter.call(source)!!.javaClass.kotlin.qualifiedName!!.startsWith("kotlin.") }.forEach { val res = getMemberName(it.getter.call(source)!!, member, prefix + it.name + ".") if(res.isNotEmpty()) { return prefix + res } } return "" }
Nextjs fetching data from child component
|next.js|cors|fetch|
I have a basic swift ui view where there is a side menu and main view. Initially the main view is displayed but using a left to right drag gesture the side menu slides into the view and the main view is offset to the right. This simulates a basic settings page. The problem is the drag gesture in the base views gets ignored by the tab view, this is because the tab view itself allows drag gestures to switch tabs. I would like to allow the user to drag to switch tabs, however, if the user is on the left most tab then another left drag gesture should present the settings. Currently when the left most tab is shown, a left->right drag gesture is picked by the tab view and the settings are not shown. If I include a button in the left most tab and preform a left->right drag gesture then the side menu is shown once the drag is release. This is much like twitters main page. How can I get a left->right drag gesture in the left tab to show the side menu with the offset transition. Left->right drag gesture in the middle and right tabs should only switch the tab though. ``` import SwiftUI struct sideMenu: View { var body: some View { ZStack { Color.gray Text("Side Menu") } } } struct MainView: View { @State var selection: Int = 0 var body: some View { TabView(selection: $selection, content: { ZStack { Color.blue Text("tab 0") }.tag(0) ZStack { Color.red Text("tab 1") }.tag(1) ZStack { Color.green Text("tab 2") }.tag(2) }) } } struct FeedBaseView: View { @State var showMenu: Bool = false @State var offset: CGFloat = 0 @State var lastStoredOffset: CGFloat = 0 @GestureState var gestureOffset: CGFloat = 0 var body: some View { let sideBarWidth = widthOrHeight(width: true) - 90 VStack { HStack(spacing: 0) { sideMenu().frame(width: sideBarWidth) VStack(spacing: 0) { MainView() } .blur(radius: showMenu ? 10 : 0) .frame(width: widthOrHeight(width: true)) .overlay( Rectangle() .fill( Color.primary.opacity( (offset / sideBarWidth) / 6.0 ) ) .ignoresSafeArea(.container, edges: .all) .onTapGesture { if showMenu { UIImpactFeedbackGenerator(style: .light).impactOccurred() showMenu = false } } ) } .frame(width: sideBarWidth + widthOrHeight(width: true)) .offset(x: -sideBarWidth / 2) .offset(x: offset) .gesture( DragGesture() .updating($gestureOffset, body: { value, out, _ in out = value.translation.width }) .onChanged({ value in if abs(value.translation.height) > 10 && !showMenu { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } }) .onEnded(onEnd(value:)) ) } .animation(.linear(duration: 0.15), value: offset == 0) .onChange(of: showMenu) { newValue in if showMenu { if offset == 0 { offset = sideBarWidth lastStoredOffset = offset } UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } if !showMenu && offset == sideBarWidth { offset = 0 lastStoredOffset = 0 } } .onChange(of: gestureOffset) { newValue in if showMenu { if newValue < 0 { if gestureOffset != 0 { if gestureOffset + lastStoredOffset < sideBarWidth && (gestureOffset + lastStoredOffset) > 0 { offset = lastStoredOffset + gestureOffset } else { if gestureOffset + lastStoredOffset < 0 { offset = 0 } } } } } else { if gestureOffset != 0 { if gestureOffset + lastStoredOffset < sideBarWidth && (gestureOffset + lastStoredOffset) > 0 { offset = lastStoredOffset + gestureOffset } else { if gestureOffset + lastStoredOffset < 0 { offset = 0 } } } } } } func onEnd(value: DragGesture.Value) { let sideBarWidth = widthOrHeight(width: true) - 90 withAnimation(.spring(duration: 0.15)) { if value.translation.width > 0 { if value.translation.width > sideBarWidth / 2 { offset = sideBarWidth lastStoredOffset = sideBarWidth if !showMenu { UIImpactFeedbackGenerator(style: .medium).impactOccurred() } showMenu = true } else { if value.translation.width > sideBarWidth && showMenu { offset = 0 if showMenu { UIImpactFeedbackGenerator(style: .light).impactOccurred() } UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) showMenu = false } else { if value.velocity.width > 800 { offset = sideBarWidth if !showMenu { UIImpactFeedbackGenerator(style: .medium).impactOccurred() } showMenu = true } else if showMenu == false { offset = 0 } } } } else { if -value.translation.width > sideBarWidth / 2 { offset = 0 if showMenu { UIImpactFeedbackGenerator(style: .light).impactOccurred() } UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) showMenu = false } else { guard showMenu else { return } if -value.velocity.width > 800 { offset = 0 if showMenu { UIImpactFeedbackGenerator(style: .light).impactOccurred() } UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) showMenu = false } else { offset = sideBarWidth if !showMenu { UIImpactFeedbackGenerator(style: .medium).impactOccurred() } showMenu = true } } } } lastStoredOffset = offset } } func widthOrHeight(width: Bool) -> CGFloat { let scenes = UIApplication.shared.connectedScenes let windowScene = scenes.first as? UIWindowScene let window = windowScene?.windows.first if width { return window?.screen.bounds.width ?? 0 } else { return window?.screen.bounds.height ?? 0 } } ```
Swift UI detect Tab View drag gesture
|swift|swiftui|
|javascript|html|screenshot|webcam|
null
I am trying to refresh a screenshot from my webcam in a webpage continously. Not the whole page. This is my current code, which only shows a screenshot without refreshing it: ```html <!DOCTYPE html> <html> <body> <script language="JavaScript"> var myImageElement = document.getElementById('camshot'); myImageElement.src = 'api.jpg?rand=' + Math.random(); setInterval(function() { var myImageElement = document.getElementById('canshot'); myImageElement.src = 'api.jpg?rand=' + Math.random(); }, 10000); </script> </body> <img src="http://192.168.0.168/cgi-bin/api.cgi?cmd=Snap&channel=0&rs=wuuPhkmUCeI9WG7C" id="camshot" > </html> ```
How to refresh a webcam snapshot periodically in a webpage
I have been asked in one of the Top company below question and I was not able to answer. Just replied : I need to update myself on this topic **Question :** **If you create a composite indexing on 3 columns (eid , ename , esal ) ?** - If i mention only eid=10 after where clause will the indexing be called ? select * from emp where eid=10; - If I mention only eid=10 and ename='Raj' will the indexing be called ? select * from emp where eid=10 and ename='Raj'; - If I mention in different order like esal=1000 and eid=10 will the indexing be called ? - If I mention in reverse order like esal = 1000 and ename = 'Raj' and eid = 20 will the indexing be called ? Need a solution for this need with detail table representation with data how it does?
{"Voters":[{"Id":139985,"DisplayName":"Stephen C"},{"Id":681865,"DisplayName":"talonmies"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]}
{"Voters":[{"Id":207421,"DisplayName":"user207421"},{"Id":12002570,"DisplayName":"user12002570"},{"Id":839601,"DisplayName":"gnat"}]}
To resolve the mismatch in deserialization with the dataclasses-avroschema package, I utilize the ```dacite_config``` attribute within the Meta class. By setting ```"strict": True```: ```python @dataclass class CoreMessage(AvroModel): messageBody: typing.Union[ MessageTypeOne, MessageTypeTwo, ] class Meta: dacite_config = { "strict": True, } ``` For further details, check [dacite config][1] [1]: https://github.com/konradhalas/dacite?tab=readme-ov-file#strict-mode
Calculated tables do not work with slicers. Calculated tables are computed at refresh time.
|c#|visual-studio-2019|vsix|
null
{"Voters":[{"Id":874188,"DisplayName":"tripleee"},{"Id":476,"DisplayName":"deceze"}],"SiteSpecificCloseReasonIds":[13]}
I have a blank project with nothing but a code snippet from Bootstraps horizontal gutters page https://getbootstrap.com/docs/5.3/layout/gutters/#horizontal-gutters I dont see any horizontal gaps, why is that? Vertical gutters only work... [image](https://i.stack.imgur.com/1uull.png) <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <title>Dash</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> <div class="container px-4 text-center"> <div class="row gx-5"> <div class="col border"> <div class="p-3">Custom column padding</div> </div> <div class="col border"> <div class="p-3">Custom column padding</div> </div> </div> </div> </body> </html> <!-- end snippet --> https://pastebin.com/raw/UXU2ePk2 https://pastebin.com/raw/cnBsCPvF
Hi I am trying to develop a semi circular interactive progress bar using swift UI but am not able to get the expected output I am trying to achieve something similar to this [![enter image description here][1]][1] Here is my code import SwiftUI struct SemiCircularProgressBar: View { @State var progressValue: Float = 0.0 @State private var degrees: Double = -90 var body: some View { VStack { ZStack { ProgressBar(progress: self.$progressValue) .frame(width: 250.0, height: 250.0) .padding(40.0) ProgressThumb(progress: self.$progressValue) .frame(width: 30, height: 30) .offset(x: self.thumbOffset().x, y: self.thumbOffset().y) .rotationEffect(.degrees(54.5)) .gesture( DragGesture() .onChanged { gesture in let angle = self.angle(for: gesture.location) self.updateProgress(for: angle) } ) } Spacer() } } private func angle(for location: CGPoint) -> Double { let vector = CGVector(dx: location.x, dy: location.y) let angle = atan2(vector.dy, vector.dx) return Double(angle * 180 / .pi) } private func updateProgress(for angle: Double) { let totalAngle: Double = 220 let minAngle: Double = -110 let maxAngle: Double = minAngle + totalAngle var normalizedAngle = min(max(minAngle, angle), maxAngle) if normalizedAngle > 88.8 { normalizedAngle = 88.8 } let progress = Float((normalizedAngle - minAngle) / totalAngle) self.progressValue = progress self.degrees = normalizedAngle } private func thumbOffset() -> CGPoint { let thumbRadius: CGFloat = 125 // half of progress bar diameter let radians = CGFloat(degrees) * .pi / -100 let x = thumbRadius * cos(radians) let y = thumbRadius * sin(radians) return CGPoint(x: x, y: y) } } struct ProgressBar: View { @Binding var progress: Float var body: some View { ZStack { Circle() .trim(from: 0.3, to: 0.9) .stroke(style: StrokeStyle(lineWidth: 12.0, lineCap: .round, lineJoin: .round)) .opacity(0.3) .foregroundColor(Color.gray) .rotationEffect(.degrees(54.5)) Circle() .trim(from: 0.3, to: CGFloat(self.progress)) .stroke(style: StrokeStyle(lineWidth: 12.0, lineCap: .round, lineJoin: .round)) .fill(AngularGradient(gradient: Gradient(stops: [ .init(color: Color(hex: "ED4D4D"), location: 0.39000002), .init(color: Color(hex: "E59148"), location: 0.48000002), .init(color: Color(hex: "EFBF39"), location: 0.5999999), .init(color: Color(hex: "EEED56"), location: 0.7199998), .init(color: Color(hex: "32E1A0"), location: 0.8099997)]), center: .center)) .rotationEffect(.degrees(54.5)) VStack { Text("824").font(Font.system(size: 44)).bold().foregroundColor(Color(hex: "314058")) Text("Great Score!").bold().foregroundColor(Color(hex: "32E1A0")) } } } } struct ProgressThumb: View { @Binding var progress: Float var body: some View { Circle() .fill(Color.blue) .frame(width: 30, height: 30) } } extension Color { init(hex: String) { let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int: UInt64 = 0 Scanner(string: hex).scanHexInt64(&int) let a, r, g, b: UInt64 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (1, 1, 1, 0) } self.init( .sRGB, red: Double(r) / 255, green: Double(g) / 255, blue: Double(b) / 255, opacity: Double(a) / 255 ) } } #Preview { SemiCircularProgressBar() } Using this above code I am able to achieve something like this [![enter image description here][2]][2] The problems which I face here is like the thumb should be smooth and able to drag with in the semi circle. I am expecting a semicircle with a knob to show the progress. Thanks in advance [1]: https://i.stack.imgur.com/Um7Dz.png [2]: https://i.stack.imgur.com/QU7Iv.png
|math|
JQuery: https://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button Pure JS: Event listener version <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> window.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('myForm'); // this is a little overkill form.addEventListener('submit', (e) => { let name1 = form.first_name.value.trim(); let name2 = form.second_name.value.trim(); if (name1 === "" || name2 === "") e.preventDefault(); // stop submission }); form.addEventListener('input', (e) => { let name1 = form.first_name.value.trim(); let name2 = form.second_name.value.trim(); document.getElementById('subbut').disabled = name1 === "" || name2 === ""; }); }); <!-- language: lang-html --> <form method="POST" id="myForm"> <input type="text" id="first_name" name="first_name" /> <input type="text" id="second_name" name "second_name" /> <input id="subbut" type="submit" value="Submit" disabled="disabled" /> </form> <!-- end snippet --> HTML only version <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <form method="POST"> <input type="text" id="first_name" name="first_name" required /> <input type="text" id="second_name" name "second_name" required /> <input name="subbut" type="submit" value="Submit" /> </form> <!-- end snippet -->
Parse multiple record type fixedlength file with beanio gives oom and timeout error for 10GB data file
|java|apache-spark|read.csv|bean-io|
There is a algorithm in github named Mesonet. this could detect deepfake images. Do anyone have an idea in integrating this algorithm with my webUI like this "https://aravindhprabu2005.github.io/Deepfake-Detector/"? This is my UI for the deepfake detection. The github link for mesonet algorithm is "https://github.com/DariusAf/MesoNet". I don't have an idea to integrate the UI with this algorithm. Could anybody give me the steps to integrate it. I need a proper guidance for integrating it.
Integrating Mesonet algorithm with a webUI for deepfake detection model
|machine-learning|deep-learning|artificial-intelligence|deep-fake|
null
Just Add this code to controller: ViewData("SomeRole") = "hidden"/"visible" apply this to your html: <li style="visibility: @ViewBag.SomeRole">@Html.ActionLink("Tenant", "Index", "{controller}", New With {.area = ""}, Nothing)</li>
I think you can use the ContentFile class that handles the binary data into a temporary file so serializer can deal with it till it pass it to the model, the your model will store that actual image with the given name in the media root and database will store the path only and I hope the example that I will write below will help. ```python from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.core.files.base import ContentFile import requests #local imports from .serializers import ImageSerializer class ImageCreateAPIView(APIView): def post(self, request, *args, **kwargs): serializer = ImageSerializer(data=request.data) if serializer.is_valid(): url = serializer.validated_data['url'] response = requests.get(url).content image = ContentFile(response, name=url.split('/')[-1]) serializer.validated_data['image'] = image return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ```
I had the same problem and I solved by adding `withXSRFToken: true` to `axios.create`.
It is well known that ffmpeg command line can be used to remove some streams in mkv or mp4 files, and I have no problem in doing so. ffmpeg -i input.mp4 -map 0 -map -0:a:3 -map -0:a:6 -c copy output.mp4 The only issue I meet sometimes is, the result media files in mkv or mp4 are much much slower to be opened by player. I cannot figure out the real reason and bypass it. Any hint or help on solving this issue? Thanks!
After using ffmpeg to remove some streams in mkv file, it takes much longer to open the media file in potplayer in Windows
|ffmpeg|
Follow the steps to load a thumbnail using coil in Jetpack Compose. 1. Adding requried dependencies def coil_version = '2.6.0' implementation("io.coil-kt:coil-compose:$coil_version") implementation("io.coil-kt:coil-video:$coil_version") 2. Build an image loader and pass it to `AsyncImage` val imageLoader = ImageLoader.Builder(LocalContext.current) .components { add(VideoFrameDecoder.Factory()) } .build() AsyncImage( model = path, // <========== Pass video path here imageLoader = imageLoader, contentDescription = "Video Thumbnail" ) And that's it. It will display video thumbnail.
|javascript|promise|
|macos|vpn|firewall|wireguard|
This is my application.yml of Spring Authorization Server: ``` spring: security: user: name: "victoria" password: "password" oauth2: authorization-server: client: portfolio-client: registration: client-id: "portfolio-client" client-secret: "{noop}secret" client-authentication-methods: - "client_secret_basic" authorization-grant-types: - "authorization_code" scopes: - "openid" - "profile" require-authorization-consent: true redirect-uris: - "https://oauth.pstmn.io/v1/browser-callback" logging: level: root: info org.springframework.security: TRACE server: port: 8091 ``` After you start authorization server, go to http://localhost:8091/.well-known/openid-configuration in browser, you will see openid configuration. You will need "authorization_endpoint" and "token_endpoint" urls for Postman. You need the rest from application.yml to put in Postman, like this: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/JFNSS.jpg Then you should get your token when you click "Get New Access Token" after you type "victoria" and "password" in popped up dialog.
{"Voters":[{"Id":2666289,"DisplayName":"Holt"},{"Id":3929826,"DisplayName":"Klaus D."},{"Id":10008173,"DisplayName":"David Maze"}]}
There has to be a way to remove it? I happens in the code example I provided also. Does anyone on here know what I am referring to? When I tap one of the buttons via mobile, there is a white flash, how do I disable or remove that? That is all I am trying to do in the code. https://jsfiddle.net/xmdq14a2/1/ I am not able to take a screenshot of it because it happens too quickly. To reproduce, tap one of the buttons via a mobile device. Only occurs via mobile not desktop. <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> I am not sure what is causing it to occur. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> (function manageLinks() { const linksButton = [{ buttonClass: "linkButton btn-primary btn", title: "Links" } ]; const buttonContainer = document.querySelector(".buttonContainerB"); linksButton.forEach(function (links) { const button = document.createElement("button"); button.className = links.buttonClass; button.textContent = links.title; button.classList.add("linkButton", "btnC", "btn-primaryC"); button.setAttribute("data-destination", "#lb"); // Added this line buttonContainer.appendChild(button); }); })(); (function manageLinkButtonOpen() { function openModal(target) { const modal = document.querySelector(target); modal.classList.add("active"); } function addLinkToButton() { const modalButton = document.querySelector(".linkButton"); modalButton.addEventListener("click", function (event) { //const target = event.currentTarget.dataset.destination; //openModal(target); openModal(event.currentTarget.dataset.destination); }); } addLinkToButton(); }()); (function manageLinkButtonClose() { function closeModal(modal) { modal.classList.remove("active"); } function addCloseEventToModal() { const closeModals = document.querySelectorAll(".modalB"); closeModals.forEach(function (modal) { modal.addEventListener("click", function (event) { //closeModal(event.target.closest(".modalB")); closeModal(document.querySelector(".modalB")); }); }); } addCloseEventToModal(); }()); <!-- language: lang-css --> body { margin: 0; padding: 0; } body { background: #121212; padding: 0 8px 0; } /*body:has(.outer-container:not(.hide)) { padding-top: 0; }*/ body:has(.modal.active) { overflow: hidden; } body:has(.modalB.active) { overflow: hidden; } .outer-container { display: flex; min-height: 100vh; /*justify-content: center; flex-direction: column;*/ } .buttonContainerB { display: flex; flex-wrap: wrap; justify-content: center; align-content: center; max-width: 569px; gap: 10px; } /*.buttonContainerC { display: flex; flex-wrap: wrap; justify-content: center; align-content: center; max-width: 569px; gap: 10px; } */ .buttonContainerC { display: flex; flex-wrap: wrap; justify-content: center; align-content: space-around; max-width: 569px; gap: 10px; } .buttonContainerC:after{ content:""; flex-basis:183px; } .btn-primaryC { color: #2fdcfe; background-color: #000000; border-color: #2fdcfe; } .btnC { display: inline-block; 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: #000000; border: 1px solid red; box-sizing: border-box; padding: 6px 12px; font-size: 16px; border-radius: 4px; font-family: "Poppins", sans-serif; font-weight: 500; font-style: normal; } .btn-primaryD { color: #2fdcfe; background-color: #000000; border-color: #2fdcfe; } .btnD { display: inline-block; 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: #000000; border: 1px solid #2fdcfe; box-sizing: border-box; padding: 6px 12px; font-size: 16px; border-radius: 4px; font-family: "Poppins", sans-serif; font-weight: 500; font-style: normal; } .linkButtonB { flex-basis: 183px; /* width of each button */ margin: 0; /* spacing between buttons */ cursor: pointer; } .linkButton { flex-basis: 183px; /* width of each button */ margin: 0; /* spacing between buttons */ cursor: pointer; } .containerD.hide { display: none; } .modalB { position: fixed; left: 0; top: 0; right: 0; bottom: 0; display: flex; /*background: rgba(0, 0, 0, 0.4);*/ transition: transform 0.3s ease-out, -webkit-transform 0.3s ease-out; transform: translate(0, -25%); opacity: 0; pointer-events: none; z-index: -99; overflow: auto; border-radius: 50%; } .modalB.active { /* display: flex;*/ opacity: 1; transform: scale(1); z-index: 1000; pointer-events: initial; border-radius: 0; overflow: auto; padding: 8px 8px; } .inner-modalB { position: relative; margin: auto; } .containerC { /*display: flex; flex-wrap: wrap; flex-direction: column;*/ /* added*/ /* min-height: 100%;*/ margin: auto; /* justify-content: center; align-content: center;*/ } .containerC.hide { display: none; } .modal-footer { display: flex; align-items: center; box-sizing: border-box; padding: calc(16px - (8px * 0.5)); background-color: transparent; border-top: 1px solid transparent; border-bottom-right-radius: calc(8px - 1px); border-bottom-left-radius: calc(8px - 1px); } .exitC { transform: translatey(100%); margin: -65px 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; cursor: pointer; } .exitC::before, .exitC::after { content: ""; position: absolute; width: 100%; height: 5px; background: red; transform: rotate(45deg); } .exitC::after { transform: rotate(-45deg); } .closeB { transform: translatey(100%); margin: -65px auto 0; inset: 0 0 0 0; /*margin: auto auto 0;*/ /*margin: 10px auto 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; } .closeB::before, .closeB::after { content: ""; position: absolute; width: 100%; height: 5px; background: red; transform: rotate(45deg); } .closeB::after { transform: rotate(-45deg); } <!-- language: lang-html --> <div class="outer-container "> <div class="containerC "> <div class="modal-contentA"> <div class="buttonContainerB"> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> <button class="linkButtonB btn-primaryC btnC">linkButton</button> </div> <div class="modal-footer"> <button class="exitC exit" type="button" title="Exit" aria-label="Close"></button> </div> </div> <div id="lb" class="modalB"> <div class="inner-modalB"> <div class="buttonContainerC"> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> <a href="#" class="linkButton btn-primaryD btnD" target="_blank">some text </a> </div> <div class="linkButton"></div> <div class="modal-footer"> <button class="closeB exit">&times</button> </div> </div> </div> </div> </div> <!-- end snippet -->
I want to make my code read a sheet of IDs and when someone enters the wrong ID the code removes the unmatched response from the google response sheet. My current code below I am a bit of a newbie at this. I would appreciate any help in this its been driving me crazy for awhile. I am dying to get this to work and read the IDs sheet and remove the unmatched responses from the form responses sheet and keep only the matched responses. I am a teacher and the form is for Seniors only and I want to prevent students who are not seniors from having their responses recorded in the spreadsheet so thats why I am using a sheet called IDs because it contains all the ID numbers of just the seniors. My current code below I am a bit of a newbie at this. I would appreciate any help in this its been driving me crazy for awhile. I am dying to get this to work and read the IDs sheet and remove the unmatched responses from the form responses sheet and keep only the matched responses. I am a teacher and the form is for Seniors only and I want to prevent students who are not seniors from having their responses recorded in the spreadsheet so thats why I am using a sheet called IDs because it contains all the ID numbers of just the seniors. function removeUnmatchedResponses() { try { // Replace 'SPREADSHEET_ID' with the ID of your Google Sheets document var spreadsheet = SpreadsheetApp.openById('1sh5dcQJPRJtbFpe7qVjpo7yIUwi5_mCGKrAnhWm-Hng'); // Get the "IDs" sheet by index (assuming it's the first sheet) var idsSheet = spreadsheet.getSheets()[0]; // Change the index if the "IDs" sheet is not the first one // Check if "IDs" sheet exists if (!idsSheet) { throw new Error("IDs sheet not found."); } // Get the Form Responses sheet var formResponsesSheet = spreadsheet.getSheetByName("Form Responses"); // Check if Form Responses sheet exists if (!formResponsesSheet) { throw new Error("Form Responses sheet not found."); } // Get all the IDs from the "IDs" sheet var idsRange = idsSheet.getRange("A:A"); var idsValues = idsRange.getValues().flat().filter(Boolean); // Assuming IDs are in column A // Get the data range from the Form Responses sheet var formResponsesRange = formResponsesSheet.getDataRange(); var formResponsesValues = formResponsesRange.getValues(); // Separate matched and unmatched responses var matchedResponses = []; var unmatchedResponses = []; for (var i = 0; i < formResponsesValues.length; i++) { var responseId = formResponsesValues[i][0]; // Assuming the ID is in the first column of the Form Responses sheet if (idsValues.includes(responseId)) { matchedResponses.push(formResponsesValues[i]); } else { unmatchedResponses.push(formResponsesValues[i]); } } // Clear existing data in the Form Responses sheet formResponsesRange.clear(); // Write back the matched responses if (matchedResponses.length > 0) { formResponsesSheet.getRange(1, 1, matchedResponses.length, matchedResponses[0].length).setValues(matchedResponses); } // Append the unmatched responses if (unmatchedResponses.length > 0) { formResponsesSheet.getRange(formResponsesSheet.getLastRow() + 1, 1, unmatchedResponses.length, unmatchedResponses[0].length).setValues(unmatchedResponses); } Logger.log("Unmatched responses removed successfully."); } catch (error) { Logger.log("Error: " + error.message); } }
DAX query: trying to count unique entries that match two different criteria
|filter|count|powerbi|dax|
null
I am new in ARCore and i create a WebXR application with the help of codelab and it works fine but it placed the rectile towards floor i want this rectile should be on wall. ``` <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Building an augmented reality application with the WebXR Device API</title> <link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css"> <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script> <!-- three.js --> <script src="https://unpkg.com/three@0.126.0/build/three.js"></script> <script src="https://unpkg.com/three@0.126.0/examples/js/loaders/GLTFLoader.js"></script> <link rel="stylesheet" type="text/css" href="app.css" /> <script src="utils.js"></script> </head> <body> <div id="enter-ar-info" class="mdc-card demo-card"> <h2>Augmented Reality with the WebXR Device API</h2> <p> This is an experiment using augmented reality features with the WebXR Device API. Upon entering AR, you will be surrounded by a world of cubes. Learn more about these features from the <a href="https://codelabs.developers.google.com/codelabs/ar-with-webxr">Building an augmented reality application with the WebXR Device API</a> Code Lab. </p> <!-- Starting an immersive WebXR session requires user interaction. Start the WebXR experience with a simple button. --> <a id="enter-ar" class="mdc-button mdc-button--raised mdc-button--accent"> Start augmented reality </a> </div> <div id="unsupported-info" class="mdc-card demo-card"> <h2>Unsupported Browser</h2> <p> Your browser does not support AR features with WebXR. Learn more about these features from the <a href="https://codelabs.developers.google.com/codelabs/ar-with-webxr">Building an augmented reality application with the WebXR Device API</a> Code Lab. </p> </div> <script src="app.js"></script> <div id="stabilization"></div> </body> </html> ``` ``` /* * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Query for WebXR support. If there's no support for the `immersive-ar` mode, * show an error. */ (async function() { const isArSessionSupported = navigator.xr && navigator.xr.isSessionSupported && await navigator.xr.isSessionSupported("immersive-ar"); if (isArSessionSupported) { document.getElementById("enter-ar").addEventListener("click", window.app.activateXR) } else { onNoXRDevice(); } })(); /** * Container class to manage connecting to the WebXR Device API * and handle rendering on every frame. */ class App { /** * Run when the Start AR button is pressed. */ activateXR = async () => { try { // Initialize a WebXR session using "immersive-ar". this.xrSession = await navigator.xr.requestSession("immersive-ar", { requiredFeatures: ['hit-test', 'dom-overlay'], domOverlay: { root: document.body } }); // Create the canvas that will contain our camera's background and our virtual scene. this.createXRCanvas(); // With everything set up, start the app. await this.onSessionStarted(); } catch(e) { console.log(e); onNoXRDevice(); } } /** * Add a canvas element and initialize a WebGL context that is compatible with WebXR. */ createXRCanvas() { this.canvas = document.createElement("canvas"); document.body.appendChild(this.canvas); this.gl = this.canvas.getContext("webgl", {xrCompatible: true}); this.xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(this.xrSession, this.gl) }); } /** * Called when the XRSession has begun. Here we set up our three.js * renderer, scene, and camera and attach our XRWebGLLayer to the * XRSession and kick off the render loop. */ onSessionStarted = async () => { // Add the `ar` class to our body, which will hide our 2D components document.body.classList.add('ar'); // To help with working with 3D on the web, we'll use three.js. this.setupThreeJs(); // Setup an XRReferenceSpace using the "local" coordinate system. this.localReferenceSpace = await this.xrSession.requestReferenceSpace('local'); // Create another XRReferenceSpace that has the viewer as the origin. this.viewerSpace = await this.xrSession.requestReferenceSpace('viewer'); // Perform hit testing using the viewer as origin. this.hitTestSource = await this.xrSession.requestHitTestSource({ space: this.viewerSpace }); // Start a rendering loop using this.onXRFrame. this.xrSession.requestAnimationFrame(this.onXRFrame); this.xrSession.addEventListener("select", this.onSelect); } /** Place a sunflower when the screen is tapped. */ onSelect = () => { if (window.sunflower) { const clone = window.sunflower.clone(); clone.position.copy(this.reticle.position); this.scene.add(clone) const shadowMesh = this.scene.children.find(c => c.name === 'shadowMesh'); shadowMesh.position.y = clone.position.y; } } /** * Called on the XRSession's requestAnimationFrame. * Called with the time and XRPresentationFrame. */ onXRFrame = (time, frame) => { // Queue up the next draw request. this.xrSession.requestAnimationFrame(this.onXRFrame); // Bind the graphics framebuffer to the baseLayer's framebuffer. const framebuffer = this.xrSession.renderState.baseLayer.framebuffer this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, framebuffer) this.renderer.setFramebuffer(framebuffer); // Retrieve the pose of the device. // XRFrame.getViewerPose can return null while the session attempts to establish tracking. const pose = frame.getViewerPose(this.localReferenceSpace); if (pose) { // In mobile AR, we only have one view. const view = pose.views[0]; const viewport = this.xrSession.renderState.baseLayer.getViewport(view); this.renderer.setSize(viewport.width, viewport.height) // Use the view's transform matrix and projection matrix to configure the THREE.camera. this.camera.matrix.fromArray(view.transform.matrix) this.camera.projectionMatrix.fromArray(view.projectionMatrix); this.camera.updateMatrixWorld(true); // Conduct hit test. const hitTestResults = frame.getHitTestResults(this.hitTestSource); // If we have results, consider the environment stabilized. if (!this.stabilized && hitTestResults.length > 0) { this.stabilized = true; document.body.classList.add('stabilized'); } if (hitTestResults.length > 0) { const hitPose = hitTestResults[0].getPose(this.localReferenceSpace); // Update the reticle position this.reticle.visible = true; this.reticle.position.set(hitPose.transform.position.x, hitPose.transform.position.y, hitPose.transform.position.z) this.reticle.updateMatrixWorld(true); } // Render the scene with THREE.WebGLRenderer. this.renderer.render(this.scene, this.camera) } } /** * Initialize three.js specific rendering code, including a WebGLRenderer, * a demo scene, and a camera for viewing the 3D content. */ setupThreeJs() { // To help with working with 3D on the web, we'll use three.js. // Set up the WebGLRenderer, which handles rendering to our session's base layer. this.renderer = new THREE.WebGLRenderer({ alpha: true, preserveDrawingBuffer: true, canvas: this.canvas, context: this.gl }); this.renderer.autoClear = false; this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Initialize our demo scene. this.scene = DemoUtils.createLitScene(); this.reticle = new Reticle(); this.scene.add(this.reticle); // We'll update the camera matrices directly from API, so // disable matrix auto updates so three.js doesn't attempt // to handle the matrices independently. this.camera = new THREE.PerspectiveCamera(); this.camera.matrixAutoUpdate = false; } }; window.app = new App(); ``` I want to place rectile towards wall not on floor my example work very wall on floor but it is not working towards wall. How to place object on wall?
I want to rotate WebXR Rectile towards walls
|javascript|augmented-reality|arcore|virtual-reality|webxr|
null
I'm on Laravel 10, and created an API using sanctum. In my controller, I want to call the local API to display in a view. The API works fine using postman, but when called in my controller the page doesn't load and times out. Below is my module route in `module/api/routes/api.php` ``` Route::group(['middleware' => ['auth:sanctum', 'api']], function () { Route::get('sample', [ApiController::class, 'sample']); }); ``` here is the HTTP code in my controller ``` use Illuminate\Support\Facades\Http; $response = Http::withHeaders([ "Accept"=> "application/json", "Authorization" => "Bearer " . env('SANCTUM_AUTH') ]) ->get(route('sample').'/', ['type' => '2']); dd($response); ``` and this is the error i'm getting. `cURL error 28: Operation timed out after 30006 milliseconds with 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://127.0.0.1:8000/sample/?type=2` Any idea how to call the API locally?
Call local API from controller
|php|laravel|laravel-10|
> The match updates in the lookup table are differentiated by their schema names, so to get the most recent, I just have to identify the latest schema name and swap it out of the query. You can use a view to solve this problem, but you need some way of altering it whenever new data is entered into the database. I'm assuming that whenever a new schema is created, a new table is also created in that schema, but the table name and it's column names are always the same. Note that this assumption is critical to the solution I'm about to propose - and that solution is to use a DDL trigger listening to the `create_table` event on the database level to alter your view so that it will reference the schema of the newly created table. Another assumption I'm making is that you either already have the initial view, or that you are working with SQL Server 2016 or higher (that allows create or alter syntax). So first, let's create the initial view: CREATE VIEW dbo.TheView AS SELECT NULL As Test GO Then, I've added the DML trigger, which creates and executes a dynamic `alter view` statement based on the schema of the newly created table: CREATE TRIGGER AlterViewWhenSchemaChanges ON DATABASE FOR CREATE_TABLE AS DECLARE @Sql nvarchar(max), @NewTableName sysname, @NewSchemaName sysname; SELECT @NewSchemaName = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]', 'NVARCHAR(255)'), @NewTableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]', 'NVARCHAR(255)'); -- We only want to alter the view when this specific table is created! IF @NewTableName = 'TableName' BEGIN SELECT @Sql = 'ALTER VIEW dbo.TheView AS SELECT Col as test FROM '+ QUOTENAME(@NewSchemaName) +'.'+ QUOTENAME(@NewTableName) +';' EXEC(@Sql) END GO This way, whenever a new table with the specific name (`TableName` in my example) is created, the view gets altered to reference the last `TableName` created (which is obviously created in the newest schema). Testing the script: SELECT * FROM dbo.TheView; GO Results: Test NULL Create a new schema with the table `TableName` CREATE SCHEMA SchemaName CREATE TABLE SchemaName.TableName (Col int); GO -- insert some data INSERT INTO SchemaName.TableName(Col) VALUES (123); -- get the data from the altered view SELECT * FROM dbo.TheView Results: test 123 [You can see a live demo on Rextester.][1] [1]: https://rextester.com/XABK59289
{"OriginalQuestionIds":[24319662],"Voters":[{"Id":4850040,"DisplayName":"Toby Speight"},{"Id":10008173,"DisplayName":"David Maze","BindingReason":{"GoldTagBadge":"docker"}}]}
POSIX signals can allow a user program written in C to catch and handle some types of interrupts and/or exceptions. It's the most standard approach I know about. #include <stdio.h> #include <signal.h> #include <setjmp.h> int a,b,*p; jmp_buf jump_destination; void exception_handler (int sg) { printf ("Error dereferencing pointer\n"); p=&b; /* pointer quick fix. */ longjmp(jump_destination,1); /* long GOTO... */ } void main (void) { int i; signal (SIGSEGV, exception_handler); b=0; p=NULL; setjmp(jump_destination); /* ...to this position */ printf ("Trying to dereference pointer p with value %08.8X... ",p); printf ("After dereferencing pointer, its value is: %d\n", *p); } For hardware interrupts, C has no explicit semantics, mainly because it is not needed. For example, a Linux device driver can install its own interrupt handler for a hardware device. All you need is to call `request_irq()` function with the address of the function that will be in charge of handling the interrupt. For example, this will install an interrupt handler for the RTC chip (assumming it's present and activated in your hardware) ... ... res=request_irq (8, /* which interrupt? */ interrupt_handler, /* address of handler */ IRQF_DISABLED, /* this is not a shared IRQ */ "mydriver", /* to be shown at /proc/interrupts */ NULL); if (res!=0) { printk ("Can't request IRQ 8\n"); } ... ... Your handler is just a regular C function: static irqreturn_t handle_interrupt (int irq, void *dev_id, struct pt_regs *regs) { /* do stuff with your device, like read time or whatever */ ... ... ... return IRQ_HANDLED; /* notify the kernel we have handled this interrupt */ } This is possible (to use a regular C function to handle a hardware interrupt) because the handler itself is called from another kernel function, that has taken care of preserving the current context so the interrupted process won't notice anything. If you are dealing with interrupts in a "naked" computer and you want to keep your C code from deviating from the standard, then you will need to use some assembler to call your function.
null
POSIX signals can allow a user program written in C to catch and handle some types of interrupts and/or exceptions. It's the most standard approach I know about. #include <stdio.h> #include <signal.h> #include <setjmp.h> int a,b,*p; jmp_buf jump_destination; void exception_handler (int sg) { printf ("Error dereferencing pointer\n"); p=&b; /* pointer quick fix. */ longjmp(jump_destination,1); /* long GOTO... */ } void main (void) { int i; signal (SIGSEGV, exception_handler); b=0; p=NULL; setjmp(jump_destination); /* ...to this position */ printf ("Trying to dereference pointer p with value %08.8X... ",p); printf ("After dereferencing pointer, its value is: %d\n", *p); } For hardware interrupts, C has no explicit semantics, mainly because it is not needed. For example, a Linux device driver can install its own interrupt handler for a hardware device. All you need is to call `request_irq()` function with the address of the function that will be in charge of handling the interrupt. For example, this will install an interrupt handler for the RTC chip (assumming it's present and activated in your hardware) ... ... res=request_irq (8, /* which IRQ? */ interrupt_handler, /* address of handler */ IRQF_DISABLED, /* this is not a shared IRQ */ "mydriver", /* to be shown at /proc/interrupts */ NULL); if (res!=0) { printk ("Can't request IRQ 8\n"); } ... ... Your handler is just a regular C function: static irqreturn_t handle_interrupt (int irq, void *dev_id, struct pt_regs *regs) { /* do stuff with your device, like read time or whatever */ ... ... ... return IRQ_HANDLED; /* notify the kernel we have handled this interrupt */ } This is possible (to use a regular C function to handle a hardware interrupt) because the handler itself is called from another kernel function, that has taken care of preserving the current context so the interrupted process won't notice anything. If you are dealing with interrupts in a "naked" computer and you want to keep your C code from deviating from the standard, then you will need to use some assembler to call your function.
I've been looking at the documentation and relevant tutorials on permutation importance and nobody seems to have a clear idea on what they are actually permuting. Just to clarify, would the step by step process be as follows: 1. Split dataset into X_train, X_val and X_test 2. Train data on X_train, using X_val to e.g. find best epoch 3. Run the trained model on X_test, taking note of the metric we are measuring 4. Permuting a feature in X_test, and running the same model on this permuted X_test dataset 5. Take note of the same metric and compare the two 6. Repeat for each variable, without changing the model. Aside Question: Would it be worth running repeats of this permutation process, with X_train,X_val and X_test changing with each repeat. I know the resultant model will be different, but I want to get a broad perspective of how the general model (with fixed hyperparameters) behaves when trained on different datasets, as keeping X_test fixed may skew the perceived importances of certain features.
I have the input table below. I want to create a column called **Desired** where, for each row (as if iterating through each row), the **Desired** value is the sum of **Measurement**s (excluding the Measurement value in the row being evaluated) where **Lower** <= (the Lower value in the row being evaluated) and **Upper** >= (the Upper value in the row being evaluated) and **ID2** = (ID2 in the row being evaluated). Right now, I only have data for **ID2** = 1, but in the future, we will add rows for **ID2** = 2, 3, 4, etc. I made up one row for **ID2** = 2 to have two distinct ID2s. Just to try to explain my thinking, *for each row* in Input, do something like ``` SUM([MEASUREMENT] WHERE [ID2] = (ID2 in current row) AND [LOWER] <= (LOWER value in current row) AND [UPPER] >= (UPPER value in current row)) - (MEASUREMENT in current row) AS [DESIRED] ``` Obviously that's not how it works but maybe it can clarify my thinking. ("Col value" in row being evaluated) is liked SelectedValue(Col) in DAX. (Sorry I have DAX on my mind.) Seems like there should be a loop involved, but I'm hoping there is a non-loop solution. The input table is ordered by [ID1], [ID2], [Value] DESC, [Lower] In Excel, I was able to calculate the desired result like this (in cell G2): ``` =SUMIFS(F:F,B:B,B2,C:C,"<="&C2,E:E,">="&E2)-F2 ``` How can I implement this in SQL? Currently using Microsoft SQL Azure. **Input** | ID1 | ID2 | Lower | Value | Upper | Measurement | | --- | --- | ----- | ----- | ----- | ----------- | | 2 | 1 | 0 | 50 | 50 | 38 | | 2 | 1 | 0 | 25 | 25 | 20 | | 2 | 1 | 25 | 25 | 50 | 62 | | 2 | 1 | 7.5 | 17.5 | 25 | 43 | | 2 | 1 | 0 | 7.5 | 7.5 | 44 | | 2 | 2 | 0 | 7.5 | 7.5 | 44 | **Expected** | ID1 | ID2 | Lower | Value | Upper | Measurement | Desired | | --- | --- | ----- | ----- | ----- | ----------- | ------- | | 2 | 1 | 0 | 50 | 50 | 38 | 0 | | 2 | 1 | 0 | 25 | 25 | 20 | 38 | | 2 | 1 | 25 | 25 | 50 | 62 | 38 | | 2 | 1 | 7.5 | 17.5 | 25 | 43 | 58 | | 2 | 1 | 0 | 7.5 | 7.5 | 44 | 58 | | 2 | 2 | 0 | 7.5 | 7.5 | 44 | 0 |
Auto delete old posts using Snippets for especial category
|wordpress|code-snippets|vscode-snippets|
Good day I receive a file from a third party. The file seems to contain both ANSI and UTF-8 encoded characters (not sure if my terminology is correct). Changing the encoding in Notepad++ yields the following: [![Notepad++ screenshot][1]][1] [1]: https://i.stack.imgur.com/G0hcd.png So when using ANSI encoding, Employee2 is incorrect. And when using UTF-8 encoding, Employee1 is incorrect. Is there a way in C# to set 2 encodings for a file? Whichever encoding I set in C#, one of the two employees is incorrect: string filetext = ""; filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.GetEncoding("ISO-8859-1")); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.GetEncoding("Windows-1252")); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.UTF7); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.Default); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.UTF8); // Employee1 is wrong, Employee2 is correct Has anyone else encountered this and found a solution? Thank you
How to read a file that contains both ANSI en UTF-8 encoded characters
|c#|utf-8|ansi|