Julia CUDA: UndefVarError: parameters not defined Posted: 13 Nov 2021 09:18 AM PST I have a program for doing Fourier series and I wanted to switch to CuArrays to make it faster. The code is as follows (extract): #Arrays I want to use coord = CuArray{ComplexF64,1}(complex.(a[:,1],a[:,2])) t=CuArray{Float64,1}(-L:(2L/(N-1)):L) #Array of indexes in the form [0,1,-1,2,-2,...] n=[((-1)^i)div(i,2) for i in 1:grado] #Array of functions I need for calculations base= [x -> exp(π * im * i * x / L) / L for i in n] base[i](1.) #This line is OK base[i](-1:.1:1) #This line is OK base[i].(t) #This line gives error! base[i].(CuArray{Float64,1}(t)) #This line gives error! And the error is: GPU broadcast resulted in non-concrete element type Any. This probably means that the function you are broadcasting contains an error or type instability. If I change it like this base= [(x::Float64) -> (exp(π * im * i * x / L) / L)::ComplexF64 for i in n] the same lines still give error, but the error now is: UndefVarError: parameters not defined Any idea how I could fix this? Thank you in advance! Package information: (@v1.6) pkg> st CUDA Status `C:\Users\marce\.julia\environments\v1.6\Project.toml` [052768ef] CUDA v2.6.2 P.S.: This other function has the same problem: function integra(inizio, fine, arr) N=size(arr,1) h=(fine-inizio)/N integrale=sum(arr) integrale -= (first(arr)+last(arr))/2 integrale *= h end L=2 integra(-L,L,coord) |
Detect if browser supports dark mode Posted: 13 Nov 2021 09:18 AM PST Is there a way detect if browser supports dark mode? I know I can use prefers-color-scheme: dark to detect if dark mode activated or not, but that's not what I'm after. window.matchMedia('(prefers-color-scheme: dark)').matches The reason I need this is I want to present to the visitor a choice of themes (light/dark), but only if the dark mode is available. |
When RemovedCallback called in ObjectCache .net? Posted: 13 Nov 2021 09:18 AM PST The RemmovedCallBack is called randomly. When RemovedCallback is called? After cache expires time? or what time? private static ObjectCache _cache; public static async Task Main() { _cache = new MemoryCache("test"); Console.WriteLine(DateTime.Now.ToLongTimeString()); _cache.Set("key", 15, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.UtcNow.AddSeconds(1), RemovedCallback = RemmovedCallBack }); await DoSomething(); } private static async Task DoSomething() { await Task.Delay(3000); } private static void RemmovedCallBack(CacheEntryRemovedArguments arguments) { Console.WriteLine(arguments.CacheItem.Key + "----" + arguments.RemovedReason); Console.WriteLine(DateTime.Now.ToLongTimeString()); } In the above code sometimes I see this: 8:47:18 PM key----Expired 8:47:20 PM C:\Users\Farhad\source\repos\TestStack\TestStack\bin\Debug\net5.0\TestStack.exe (process 23968) exited with code 0. Press any key to close this window . . . And usually, I see this: 8:40:22 PM C:\Users\Farhad\source\repos\TestStack\TestStack\bin\Debug\net5.0\TestStack.exe (process 23248) exited with code 0. Press any key to close this window . . . |
javascript query: somehow javascript is finding length of an integer Posted: 13 Nov 2021 09:18 AM PST var a=1; var b=10; console.log(a.length == b.length); and it is returning true. Someone explain how it is calculating the length of integers |
ModuleNotFoundError: No module named 'CLIP' Posted: 13 Nov 2021 09:17 AM PST |
How to read one or several strings on its standard input and prints what their nature is Posted: 13 Nov 2021 09:16 AM PST i have to read several strings from imput and print their nature using only grep and builtins following this rule : no character or whitespaces (spaces and tabs): it is empty only letters (a-zA-Z): it is a word a single digit: it is a digit only digits (at least two): it is a number only digits and letters: it is an alphanum anything else, it is too complicated. Plus i have to exit 0 when it is too complicated. However, it is always printing it is empty and it is a word. Do you have any idea how i can fix this issue and resolve the problem ? Thanks for your attention |
how to iterate over matrices files in a directory using matlab and saving specefic index of each matrix in an array? Posted: 13 Nov 2021 09:15 AM PST i have a directory that includes files , where each file is a matrix with the extention .mat i want to iterate over the files and from each matrix extract for example the first index and arrange them in an array i am having a problem opening the files and read from them what i tried : i put all the files in an array myDir = uigetdir; matrics = dir(fullfile(myDir,'*.mat')); now i want to loop over each mat file and open it and extract the first index , but when i try to open a file i get this : fopen(matrics(1)) Error using fopen First input must be a file name or a file identifier what am i doing wrong ? |
JavaScript to Python (Using JS2PY) Posted: 13 Nov 2021 09:15 AM PST I have a seed-calculating thing that uses JavaScript (Functions properly). I'm attempting to convert it into Python (For a more detailed project) using the JS2PY library. My code: import js2py hasCode = js2py.eval_js('function hashCode(s) {let h = 0; for (let i = 0; i < s.length; i++) {h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;} return h;}') getSeed = js2py.eval_js('function getSeed(s) {let x = BigInt(hashCode(s)); if (/^[\-\+0-9]*$/.test(s)) {try {let y = BigInt(s); if (BigInt.asIntN(64, y) !== y) {throw RangeError();} x = y;} catch (err) {}} return { high: x >> 32n, low: BigInt.asIntN(32, x) };}') output = js2py.eval_js('function output() {let seed = -734744700160476640; print("Copy this output - " + seed.high, seed.low);}') output() Should you use this in, say, a HTML file, the JavaScript will produce a "High" and "Low" of the seed input (Here it is -734744700160476640, but I would allow users to input their own seed). The command log explains that there's syntax errors in files that I'm assuming is from the library. You can probably tell I'm a little inexperienced so if it's my own code that's broken, shout it out. I don't know if JS2PY is outdated or if there's better options out there. I couldn't find any myself. |
Statlib installation error (python 2.7) in windows 10 Posted: 13 Nov 2021 09:16 AM PST I have found the outputs as follows: C:\Users\mm>python -m pip install statlib DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Collecting statlib ERROR: ***Could not find a version that satisfies the requirement statlib (from versions: none) ERROR: No matching distribution found for statlib*** WARNING: You are using pip version 19.2.3, however version 20.3.4 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. How to solve the issue and run statlib? |
Converting the value in a text into a dictionary Posted: 13 Nov 2021 09:18 AM PST I have a text file that looks like this. Paul Velma 63.00 Mcgee Kibo 71.00 Underwood Louis 62.75 Clemons Phyllis 57.50 I am trying to make them into a dictionary but I got stuck because I am not sure how to slice them into keys and values. Below is my code. dt_stu=[] infile = open("C:\\Users\kwokw\Downloads\\student_avg.txt",'r') for line in infile: key,value=line.split([0:9]) dt_stu[key]=value print(dt_stu) |
How do I solve this flutter dart run error when i'm fetching the result from firebase? Posted: 13 Nov 2021 09:15 AM PST The code is supposed to display the news on the news tab and get fetch records from firebase and display it on the reports tab. Here is the entire code import 'dart:async'; import 'dart:convert'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:feel_safe/widgets/drawer.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:http/http.dart' as http; class ShowResult extends StatefulWidget { final String _location; ShowResult(this._location); @override _ShowResultState createState() => _ShowResultState(); } class _ShowResultState extends State<ShowResult> { StreamSubscription<QuerySnapshot>? subscription; bool t = true; late List<DocumentSnapshot> eventsData; int _lengthOfEventsData = 0; final CollectionReference collectionReference = FirebaseFirestore.instance.collection('reports'); late String key, query, url, myText; List data = []; late int length; @override void initState() { super.initState(); key = "c0dd7cc7ac9d4795a2899b239ca25dd8"; query = "(+injured OR +killed OR +accident) AND (+${widget._location}) AND (-football OR -cricket) AND ${widget._location}"; url = "https://newsapi.org/v2/everything?q=$query&apiKey=$key"; // print(url); this.getJsonData(); subscription = collectionReference.snapshots().listen((datasnapshot) { FirebaseFirestore.instance .collection('/reports') .where('locality', isEqualTo: widget._location) .get() .then((docs) { setState(() { eventsData = docs.docs; _lengthOfEventsData = docs.docs.length; // print("len $_lengthOfEventsData"); }); }); }); // fetch_firebase(); } _launchURL(url) async { if (await canLaunch(url)) { await launch(url); } else { throw 'Could not launch $url'; } } Future<String> getJsonData() async { var response = await http.get(Uri.parse(url), headers: {"Accept": "application/json"}); // print(response.body); setState(() { var convertDataDataToJson = json.decode(response.body); data = convertDataDataToJson['articles']; // print(data); }); return "Success"; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: t ? Text("NEWS") : Text("REPORTS"), actions: <Widget>[ MaterialButton( child: t ? Text("REPORTS") : Text("NEWS"), color: Colors.white, onPressed: () { setState(() { t = !t; }); }, ) ], ), drawer: CustomDrawer(context), body: t ? ListView.builder( itemCount: data.length, itemBuilder: (BuildContext context, int index) { return Container( padding: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 0.0), child: Center( child: Card( child: Container( padding: EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Container( child: Text( data[index]['Title'], style: TextStyle( fontFamily: 'Montserrat', fontSize: 20.0, fontWeight: FontWeight.w800), ), ), Padding( padding: EdgeInsets.all(5.0), ), InkWell( onTap: () { _launchURL(data[index]['url']); }, child: Text( data[index]['url'], style: TextStyle(color: Colors.blue), ), ) ], ), ), ), ), ); }, ) : ListView.builder( itemCount: _lengthOfEventsData, itemBuilder: (BuildContext context, int index) { return Container( padding: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 0.0), child: Center( child: Card( child: Container( padding: EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Container( child: Text( "title", //eventsData[index].data['Title'], style: TextStyle( fontFamily: 'Montserrat', fontSize: 20.0, fontWeight: FontWeight.w800), ), ), Padding( padding: EdgeInsets.all(5.0), ), Text("Info text" //eventsData[index].data['Information'], //style: TextStyle(fontSize: 14.0), ), Padding( padding: EdgeInsets.all(5.0), ), Text( "Location:", style: TextStyle( fontSize: 11.0, fontWeight: FontWeight.bold), ), Text("loc text" /*eventsData[index].data['location'], style: TextStyle(fontSize: 11.0),*/ ), Padding( padding: EdgeInsets.all(5.0), ), ], ), ), ), ), ); }, ), ); } } The entire console output when i open that: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following assertion was thrown building Builder(dirty): setState() or markNeedsBuild() called during build. This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: Overlay-[LabeledGlobalKey<OverlayState>#b1517] The widget which was currently being built when the offending call was made was: Builder The relevant error-causing widget was: MaterialApp file:///D:/FlutterProjects/test/lib/main.dart:20:16 When the exception was thrown, this was the stack: #0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4217:11) #1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4232:6) #2 State.setState (package:flutter/src/widgets/framework.dart:1108:15) #3 OverlayState.rearrange (package:flutter/src/widgets/overlay.dart:436:5) #4 NavigatorState._flushHistoryUpdates (package:flutter/src/widgets/navigator.dart:4065:16) #5 NavigatorState._pushEntry (package:flutter/src/widgets/navigator.dart:4573:5) #6 NavigatorState.push (package:flutter/src/widgets/navigator.dart:4480:5) #7 _HomePageState.goToResult (package:feel_safe/pages/homepage.dart:27:27) #8 _HomePageState.retButton.<anonymous closure>.<anonymous closure> (package:feel_safe/pages/homepage.dart:49:61) #9 MaterialPageRoute.buildContent (package:flutter/src/material/page.dart:53:55) #10 MaterialRouteTransitionMixin.buildPage (package:flutter/src/material/page.dart:106:27) #11 _ModalScopeState.build.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/routes.dart:843:53) #12 Builder.build (package:flutter/src/widgets/basic.dart:7798:48) #13 StatelessElement.build (package:flutter/src/widgets/framework.dart:4648:28) #14 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15) #15 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #16 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4553:5) #17 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5) ... Normal element mounting (157 frames) #174 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14) #175 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6221:36) #176 Element.updateChild (package:flutter/src/widgets/framework.dart:3363:18) #177 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5654:32) #178 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6243:17) #179 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #180 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:16) #181 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11) #182 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #183 StatefulElement.update (package:flutter/src/widgets/framework.dart:4778:5) #184 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #185 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:16) #186 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #187 ProxyElement.update (package:flutter/src/widgets/framework.dart:4922:5) #188 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #189 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:16) #190 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #191 ProxyElement.update (package:flutter/src/widgets/framework.dart:4922:5) #192 _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:181:11) #193 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #194 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6090:14) #195 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #196 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:16) #197 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11) #198 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #199 StatefulElement.update (package:flutter/src/widgets/framework.dart:4778:5) #200 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #201 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6090:14) #202 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #203 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6090:14) #204 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #205 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:16) #206 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #207 ProxyElement.update (package:flutter/src/widgets/framework.dart:4922:5) #208 Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15) #209 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:16) #210 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11) #211 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5) #212 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2582:33) #213 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:875:21) #214 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:328:5) #215 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15) #216 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9) #217 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:998:5) #221 _invoke (dart:ui/hooks.dart:163:10) #222 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:259:5) #223 _drawFrame (dart:ui/hooks.dart:126:31) (elided 3 frames from dart:async) ════════════════════════════════════════════════════════════════════════════════════════════════════ E/flutter (20750): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 3018 pos 18: '!navigator._debugLocked': is not true. E/flutter (20750): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39) E/flutter (20750): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5) E/flutter (20750): #2 _RouteEntry.handlePush.<anonymous closure> (package:flutter/src/widgets/navigator.dart:3018:18) E/flutter (20750): #3 TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart:407:15) E/flutter (20750): #4 _rootRunUnary (dart:async/zone.dart:1362:47) E/flutter (20750): #5 _CustomZone.runUnary (dart:async/zone.dart:1265:19) E/flutter (20750): <asynchronous suspension> E/flutter (20750): #6 TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart) E/flutter (20750): <asynchronous suspension> E/flutter (20750): E/flutter (20750): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 3018 pos 18: '!navigator._debugLocked': is not true. E/flutter (20750): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39) E/flutter (20750): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5) E/flutter (20750): #2 _RouteEntry.handlePush.<anonymous closure> (package:flutter/src/widgets/navigator.dart:3018:18) E/flutter (20750): #3 TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart:407:15) E/flutter (20750): #4 _rootRunUnary (dart:async/zone.dart:1362:47) E/flutter (20750): #5 _CustomZone.runUnary (dart:async/zone.dart:1265:19) E/flutter (20750): <asynchronous suspension> E/flutter (20750): #6 TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart) E/flutter (20750): <asynchronous suspension> E/flutter (20750): W/DynamiteModule(20750): Local module descriptor class for providerinstaller not found. I/DynamiteModule(20750): Considering local module providerinstaller:0 and remote module providerinstaller:0 W/ProviderInstaller(20750): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0. Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null. The entire project code is available at: https://github.com/NaitikVora/Neighbourhood-Watch-App I needed to migrate the app and change few legacy code to get it running. Any help on this would be great! |
How to align a label above a form widget QT Posted: 13 Nov 2021 09:18 AM PST I'm working with a narrow form with a slider. By default the slider's label is to the left (rtl language.) I want to put the label above the slider. I assume I could create a text widget, add that as a separate row, but I'm not sure if I lose accessibility or other benefits of the QT row. Also, maybe I can make the whole form follow the "label above widget" pattern. Just not sure where that might be. Current layout code: myForm->addRow(tr("My Label:"), m_thicknessSlider); Weirdly, I accidentally did the following, which provides the layout I'm looking for, mostly. But this seems wrong? myForm->addRow(tr("My Label:"), m_thicknessSlider); myForm->addRow(m_thicknessSlider); |
scale balancing JavaScript algorithm [closed] Posted: 13 Nov 2021 09:18 AM PST Have the function ScaleBalancing(strArr) read strArr which will contain two elements, the first being the two positive integer weights on a balance scale (left and right sides) and the second element being a list of available weights as positive integers. Your goal is to determine if you can balance the scale by using the least amount of weights from the list, but using at most only 2 weights. For example: if strArr is ["[5, 9]", "[1, 2, 6, 7]"] then this means there is a balance scale with a weight of 5 on the left side and 9 on the right side. It is in fact possible to balance this scale by adding a 6 to the left side from the list of weights and adding a 2 to the right side. Both scales will now equal 11 and they are perfectly balanced. Your program should return a comma separated string of the weights that were used from the list in ascending order, so for this example your program should return the string 2,6. There will only ever be one unique solution and the list of available weights will not be empty. It is also possible to add two weights to only one side of the scale to balance it. If it is not possible to balance the scale then your program should return the string not possible . function ScaleBalancing(strArr) { const a1 = JSON.parse(strArr[0])[0]; const a2 = JSON.parse(strArr[0])[1]; let weights = JSON.parse(strArr[1]); for (let i = 0; i < weights.length; i++) { if (a1 + weights[i] === a2 || a2 + weights[i] === a1) { if (a1 > a2){ return 'add right side ' + weights[i]; } else{ return 'add left side ' + weights[i]; } } for (let j = i + 1; j < weights.length; j++) { if (a1 + weights[i] + weights[j] === a2 || a2 + weights[i] + weights[j] === a1 || a1 + weights[i] === a2 + weights[j] || a2 + weights[i] === a1 + weights[j]) { if (a1 < a2){ return ' left side add ' + weights[i] + ', right side add ' + weights[j]; } else{ return ' left side add ' + weights[j] + ', right side add ' +weights[i]; } } } } return 'not possible'; } console.log(ScaleBalancing(["[13, 4]", "[1, 2,3, 6]"])); how does this implement get output like this Sample test cases: Input:"[3, 4]", "[1, 2, 7, 7]" Output:"Left: 1 | Right: 0" Input:"[13, 4]", "[1, 2, 3, 6, 14]" Output:"Left: 0 | Right: 3,6" Input: "[5, 5]", "[1, 2, 3]" Output: "Equals" |
How to pass a variable from html to python? Posted: 13 Nov 2021 09:17 AM PST I need to pass id to python. Is it possible? If so how can I do it? Here is what the related code looks like so far: <div class="button"> <button type="button" class="btn2" onclick="decrement()"><</button> <button type="button" class="btn2" onclick="increment()">></button> <form action = "/test.html" method = "get"> <script> var id = 1; function increment() { ++id; return id; } function decrement() { --id; return id; } </script> </form> </div> and here is the related python code: @app.route("/test.html", methods=["GET", "POST"]) def test(): if request.method == "GET": front = db.execute("SELECT student FROM class WHERE id = ?", id) back = db.execute("SELECT grade FROM class WHERE id = ?", id) return render_template("test.html") |
How to separate elements within a navBar css Posted: 13 Nov 2021 09:18 AM PST I'm trying to build a blog web page in a html css tutorial and I can't find a way to make the navBar identical. Here's the Navigation Bar: I don't know how to separate the logo on the left to to the group of icons on the rigth. I tried to use Flex but I can't figure out how to use it properly. Here's my html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My blog</title> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> </head> <body> <header> <img src="C:\Users\elios\OneDrive\Documents\HTML_classes\My_blog_project\logo.png" alt=""> <nav> <ul> <li><a href=""><i class="material-icons">search</i></a></li> <li><a href=""><i class="material-icons">list</i></a></li> <li><a href=""><i class="material-icons">notifications</i></a></li> <li><a href=""><button>Upgrade</button></a></li> <li><a href=""><div id="circle"></div></a></li> </ul> </nav> </header> </body> </html> And here's my CSS: header img{ height: 40px; margin-left: 40px; } header { background-color: white; position: fixed; top: 0; left: 0; right: 0; height: 80px; } body{ background-color: aliceblue; } header * { display: inline; } header li{ justify-content: center; margin: 20px; } header li a { color: black; text-decoration: none; } If you have any advices or suggestions it would be great I'm starting and this is making me struggle a lot. Thnaks in advance guys! |
replace url into anchor tag with using nl2br in laravel blade Posted: 13 Nov 2021 09:17 AM PST hello i have laravel blade and here is the part that have the issue @php $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; @endphp <div class="message"> @php $text = nl2br(e($message)); @endphp @if(preg_match($reg_exUrl, $text, $url)){!! preg_replace($reg_exUrl, '<a href="$0" target="_blank">$0</a> ', $text) !!} @else {!!$text!!} @endif </div> this works good if the link is only in the text but if it got mixed with some words and some break line like this message hello dear buyer the link is working good https://google.com/blabla and some random text it converted to this html code hello dear buyer<br> <br> the link is working good<br> <a href="https://google.com/blabla<br" target="_blank">https://google.com/blabla<br< a=""> /> <br> and some random text<br> <br> how to fix this i want to replace the url into anchor tag and show the break line if the user enters message contains lines also to use the e() function in blade to prevent any html code from running any one help please |
Flutter/Dart Get All Values Of a Key from a JSON Posted: 13 Nov 2021 09:16 AM PST How can i get all values of a second level key in a JSON? I need to get all total values as like 409571117, 410559043, 411028977, 411287235 JSON: {"country":"USA","timeline": [{"total":409571117,"daily":757824,"totalPerHundred":121,"dailyPerMillion":2253,"date":"10/14/21"}, {"total":410559043,"daily":743873,"totalPerHundred":122,"dailyPerMillion":2212,"date":"10/15/21"}, {"total":411028977,"daily":737439,"totalPerHundred":122,"dailyPerMillion":2193,"date":"10/16/21"}, {"total":411287235,"daily":731383,"totalPerHundred":122,"dailyPerMillion":2175,"date":"10/17/21"}]} I can able to get first level values but i don't know how to get second level. final list = [ {'id': 1, 'name': 'flutter', 'title': 'dart'}, {'id': 35, 'name': 'flutter', 'title': 'dart'}, {'id': 93, 'name': 'flutter', 'title': 'dart'}, {'id': 82, 'name': 'flutter', 'title': 'dart'}, {'id': 28, 'name': 'flutter', 'title': 'dart'}, ]; final idList = list.map((e) => e['id']).toList(); // [1, 35, 93, 82, 28] |
Dash app in django-plotly-dash breaking migrate, how to stop it executing in a migrate? Posted: 13 Nov 2021 09:16 AM PST I am using django-plotly-dash so have a Django template that hosts a Dash app. (The Dash app is using raw SQL queries over psycopg2) When I do a django migrate, this dash raw SQL fails because the tables have not yet been created. Thus halting the migrate. aka Catch22. Anyone know if there's a way to stop the Dash apps being executed during a migrate ? Responding to comment from Ian S (thanks)... Here's a reduced version of the query string: queryStr = ''' SELECT veh.number as veh, dh.rcmdh_number as dh, from rcm_rcmveh as veh, rcma_rcmdh as dh, where sige.sig_id = sig.id AND sig.unit_id = veh .id ''' cnx = psycopg2.connect( host=POSTGRES_ADDRESS, database=POSTGRES_DBNAME, user=POSTGRES_USERNAME, password=POSTGRES_PASSWORD) df = pd.read_sql_query(queryStr, cnx) The query doesn't run because rcm_rcmveh doesn't exist yet because the migration is in the process of being run. This is in the top level of the dashapp.py module. So thinking about it, I probably need to put it inside a function in the module so that it isn't run when the module is scanned by Django on startup ? |
Firebase Rest Api reading data from my model classes using interface callback return null Posted: 13 Nov 2021 09:17 AM PST I am trying to run a Get method in java Restful API. I have tried naming my model classes similar to my real-time firebase. I have tried using interface callback, and it has printed to my console but it still return null in my postman, My interface callback class public interface CallBack { void onCallBack(DeviceTest value); } my model class public class DeviceTest implements Serializable { private String LightSwitch; private String DoorSwitch; // empty COnstructor public DeviceTest() { } public DeviceTest(String lightSwitch, String doorSwitch) { this.LightSwitch = lightSwitch; this.DoorSwitch = doorSwitch; } public String getLightSwitch() { return LightSwitch; } public void setLightSwitch(String lightSwitch) { LightSwitch = lightSwitch; } public String getDoorSwitch() { return DoorSwitch; } public void setDoorSwitch(String doorSwitch) { DoorSwitch = doorSwitch; } @Override public String toString() { return "DeviceTest{" + "LightSwitch='" + LightSwitch + '\'' + ", DoorSwitch='" + DoorSwitch + '\'' + '}'; } } The FireBase Connection class and the method I use. public static void handleLight(CallBack callback) { FireBaseService fbs = null; fbs = new FireBaseService(); device = new DeviceTest(); mylist = new ArrayList<Map<String, Object>>(); DatabaseReference ref = fbs.getDb() .getReference("/Devices/Lamp/Ambient"); Map<String, Object> chemainChild = new HashMap<>(); // chemainChild.put("server/user/",array); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { callback.onCallBack(dataSnapshot.getValue(DeviceTest.class)); } @Override public void onCancelled(DatabaseError databaseError) { } }); //mylist.add(device); } The Get method i use to print to postman DeviceTest deviceTest = new DeviceTest(); @GET @Produces(MediaType.APPLICATION_JSON) public DeviceTest getCustomers() { //System.out.println(device.toString()); FireBaseService.handleLight(new CallBack() { @Override public void onCallBack(DeviceTest value) { // this one will print to my console System.out.println("Should work " + value.toString()); // this value does not seem to be added to my deviceTest, likely a asynchronous issue again. deviceTest = new DeviceTest(value.getLightSwitch(),value.getDoorSwitch()); } }); // this is here i get my null value return deviceTest ; } This is what i got in my postman: What i got in my console: My question is how can I print this value DeviceTest{LightSwitch='LIGHT', DoorSwitch='CLOSED'} in my console to my postman? The issue seems to be in my GET Method. |
Legend not showing with barless histogram plot in python Posted: 13 Nov 2021 09:17 AM PST I am trying to plot a kde plot in seaborn using the histplot function, and removing later the bars of the histogram in the following way (see last part of the accepted answer here): fig, ax = plt.subplots() sns.histplot(data, kde=True, binwidth=5, stat="probability", label='data1', kde_kws={'cut': 3}) The reason for using histplot instead of kdeplot is that I need to set a specific binwidth . The problem I have that I cannot print out the legend, meaning that ax.legend(loc='best') does nothing, and I receive the following message: No handles with labels found to put in legend. I have also tried with handles, labels = ax.get_legend_handles_labels() plt.legend(handles, labels, loc='best') but without results. Does anybody have an idea of what is going on here? Thanks in advance! |
Encode Int to Bytes using logical operators Posted: 13 Nov 2021 09:15 AM PST I've been doing some work on logical arithmetic recently. I want to encode unsigned integers (Uint's) and signed integers (Int's) as bytes. Below is a code snippet that currently translates UInts to bytes and vice versa. Unfortunately I got some problems while encoding signed integers with my tactic. Encoding for Integers will be performed using this shift and mask method for both - unsigned and signed integers. for (let i=0; i<n; i++) buffer.push((value >>> (i*8)) & 0xFF); So what is wrong with my readInt -method and how to fix this? const buffer = []; const writeIntN = (value, n) => { for (let i=0; i<n; i++) buffer.push((value >>> (i*8)) & 0xFF); } const readUint = (n, offset) => { let v=0; for (let i=0; i<n; i++) v |= (buffer[offset++] << (i*8)); return v >>> 0; } const readInt = (n, offset) => { return readUint(n, offset) << (8*n) >> (8*n); // error is here } const writeUInt16 = (value) => writeIntN(value, 2); const readUInt16 = (offset) => readUint(2, offset); const writeInt16 = (value) => writeIntN(value, 2); const readInt16 = (offset) => readInt(2, offset); const writeInt8 = (value) => writeIntN(value, 1); const readInt8 = (offset) => readInt(1, offset); writeUInt16(20); writeInt16(-20); writeInt8(-42); console.log(buffer); console.log(readUInt16(0)); console.log(readInt16(2)); console.log(readInt8(4)); // how? Note: I know about the basic operations to decode 8,16-bit signed ints but how to get this inside the for loop in readUint more efficient? Decoding 8-bit signed integers: (buffer[offset++] << 24) >> 24 Decoding 16-bit signed integers: (((buffer[offset++] << 0) | (buffer[offset++] << 8)) << 16) >> 16 |
Getting SSLHandshake Exception in Firebase crashlytics for android 7 and below Posted: 13 Nov 2021 09:16 AM PST I am using firebase Sdk in my android application. My users using android versions 7 or below are experiencing app crash on startup. In firebase crashlytics, im getting Fatal Exception: javax.net.ssl.SSLHandshakeException Caused by java.security.cert.CertificateException java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. all of the reported crashes are the users who are using android 7 or below. It was working fine previously. does anyone know what might be going wrong? Was there an update from firebase for lower android versions? Please note that, the android application is using firebase sdk and not connected to any custom server. I am also using push notifications in my application. |
Store result of the function with argument into variable Posted: 13 Nov 2021 09:15 AM PST I have a function that takes the path to CSV file as an argument and adds a column: def df_change(path): pd.read_csv(path) df55 = pd.read_csv(path) df55['name'] = 'xxx' print(df55) But the result I get is Series: But I need it to be a Dataframe. I tried to store the result for converting by using this method: But it didn't work. I also tried .to_frame() , but I either used it wrong or it can't be applied in my case |
Manage Locale in Android Jetpack Compose Posted: 13 Nov 2021 09:17 AM PST How do I manage the locale with android Jetpack Compose. How do compose find the locale to set in the view. |
Function that returns a query Posted: 13 Nov 2021 09:17 AM PST This is the function : create or replace function searchbyid (depto in departments.department_id%type) return sys_refcursor is result_s sys_refcursor; begin open result_s for SELECT a.employee_id, a.first_name, a.last_name, a.phone_number, a.salary, b.department_id, b.end_date FROM employees a FULL JOIN job_history b ON a.department_id = b.department_id WHERE b.department_id = depto; return result_s; end; I'm getting the output in a single line, is it possible to get as a table? FUNCTION OUTPUT : Yes, I use SQL Developer |
How to delete old git branches before 1 year? Posted: 13 Nov 2021 09:16 AM PST I want to list all 1 year before git branches and then ask user to type YES tto delete all the listed branches. #!/bin/bash if [[ "$data_folder" == "test" ]]; then current_timestamp=$(date +%s) twelve_months_ago=$(( $current_timestamp - 12*30*24*60*60 )) for x in `git branch -r | sed /\*/d`; do branch_timestamp=$(git show -s --format=%at $x) if [[ "$branch_timestamp" -lt "$twelve_months_ago" ]]; then branch_for_removal+=("${x/origin\//}") fi done if [[ "$USERCHOICE" == "YES" ]]; then git push origin --delete ${branch_for_removal[*]} echo "Finish!" else echo "Exit" fi Is this logic correct to list and delete all 1 year before git branches !! |
Count occurrences of specific word after a different, specific word is found Posted: 13 Nov 2021 09:17 AM PST I am rather new to regex and am stuck on the following where I try to use preg_match_all to count the number of hello after world. If I use "world".+(hello) , it counts to the in the last hello; "world".*?(hello) stops in the first hello, both giving one count. blah blah blah hello blah blah blah class="world" blah blah blah hello blah blah hello blah blah blah hello blah blah blah I am expecting 3 as the count because the hello before world should not be counted. |
Android WorkManager setForegroundInfo Posted: 13 Nov 2021 09:18 AM PST I followed the official guide to set up a long-running worker with WorkManager (Kotlin version). Now I need to update the notification with the operation progress. The documentation says: // Calls setForegroundInfo() periodically when it needs to update // the ongoing Notification However I can't find any setForegroundInfo() method. So how do you update the ongoing notification? |
reportviewer hide exporting to word and excel options Posted: 13 Nov 2021 09:17 AM PST i am using visual studio 2012 and I have a rdlc report. I want to hide word and excel in the export option in ssrs ReportViewer. I Have tried couple of things but nothing seems to work! if any body can help i'd be so grateful :) Thanks |
What is the meaning of following driver_options params? Posted: 13 Nov 2021 09:18 AM PST I'm working on some project in my company, and client asked me to change few things in database. Project was not done by us. After few hours of work I saw these config lines: resources.db.adapter = "PDO_MYSQL" resources.db.params.host = "localhost" resources.db.params.dbname = "db" resources.db.params.username = "db-user" resources.db.params.password = "db-password" resources.db.params.charset = "utf8" resources.db.params.driver_options.1006 = true resources.db.params.driver_options.1000 = true Can anyone tell me what exactly these driver options mean? I was googling around for some time and couldn't find any other answer but this: these are driver specific options... |
No comments:
Post a Comment