How to block ads from apps Posted: 07 May 2022 05:15 AM PDT I am a new Android application programmer. I want to know if there is a way to block ads on other applications. How do I access that? What do I use in my application to do this... Sorry if the language is not clear |
Rendering problem in React when localstorage changes Posted: 07 May 2022 05:14 AM PDT I have a memory game where you can choose how many cards do you want to play with. When you start it from the home page it works good and the game renders the correct number of cards. The problem is I have a header with "Deck size" select and a "New Game" button in the Game Component. When you choose an another size and click onto the "New Game" button the app doesn't render the new cards. If I try it with the window.location.reload() function the app reloads and push me back onto the home page. The game loads the number of cards from the localstorage. App.js: <div className="App"> <MemoryRouter> <Routes> <Route path="/"> <Route exact path="/" element={<Home />} /> <Route exact path="/:numberOfCards" element={<Game />} /> </Route> </Routes> </MemoryRouter> </div> Game.js const restartGame = () => { localStorage.setItem("state", null); navigate(`/${deckSize}`); window.location.reload(); }; Game.js const loadState = () => { const local = JSON.parse(localStorage.getItem("state")); if (local && local.deck) { setDeck(local.deck); } if (local && local.activeCards) { setActiveCards(local.activeCards); } if (local && local.pairs) { setPairs(local.pairs); } if (local && local.moves) { setMoves(local.moves); } }; //shuffle the cards if the user haven't saved state const deal = () => { const local = JSON.parse(localStorage.getItem("state")); if (local === null) { setDeck((deck) => [...deck] .slice(0, numberOfCards * 2) .sort((a, b) => Math.random() - 0.5) ); } else { setDeck((deck) => [...deck].slice(0, numberOfCards * 2)); } }; useEffect(() => { loadState(); deal(); }, []); GameHeader.js const startGame = () => { localStorage.setItem("state", null); localStorage.setItem("deckSize", deckSize); window.location.reload(); }; |
How to create an enum with raw values in swift? Posted: 07 May 2022 05:14 AM PDT I am trying to build a structured case switch for various errors that can come back from api. Error output in the console: AuthError: Username is required to signIn Recovery suggestion: Make sure that a valid username is passed during sigIn I have created an enum within a class named AuthenticationManager enum AuthErrors: String { case invalidCode case noUser case unknown case phoneMissing = "AuthError: Username is required to signIn" } And a switch to case .failure(let failureResult): let authError = AuthenticationManager.AuthErrors(rawValue: "\(failureResult)") ?? .unknown switch authError { case .invalidCode: currentStep = .signInRequired continuation.resume(returning: currentStep) case .unknown: currentStep = .signInRequired continuation.resume(throwing: failureResult) break case .noUser: currentStep = .signUpRequired continuation.resume(returning: currentStep) case .phoneMissing: print("missing") } |
How can I create a URL like http://example.org/index.php/xy Posted: 07 May 2022 05:14 AM PDT I've seen on Wordpress-Sites URLs like this: ```http://example.com/index.php/site/postXY``` My Question is: How can I create a URL like this in Apache2/PHP? I hope, anyone can help me. |
How to boot into the Graphics mode for installing Ubuntu Desktop on QEMU Posted: 07 May 2022 05:14 AM PDT I copied the qemu-system-aarch64 command from the following link: https://askubuntu.com/questions/281763/is-there-any-prebuilt-qemu-ubuntu-image32bit-online/1081171#1081171 The following command will boot into the UEFI Shell : qemu-system-aarch64 \ -M virt \ -cpu cortex-a57 \ -device rtl8139,netdev=net0 \ -m 4096 \ -netdev user,id=net0 \ -nographic \ -smp 4 \ -drive "if=none,file=${img},id=hd0" \ -device virtio-blk-device,drive=hd0 \ -drive "file=${user_data},format=raw" \ -pflash flash0.img \ -pflash flash1.img \ ; Output: UEFI Interactive Shell v2.2 EDK II UEFI v2.70 (EDK II, 0x00010000) Mapping table ... Press ESC in 1 seconds to skip startup.nsh or any other key to continue. Shell> Remove the option "-nographic \ " and then run it again, it will boot into the QEMU console: qemu-system-aarch64 \ -M virt \ -cpu cortex-a57 \ -device rtl8139,netdev=net0 \ -m 4096 \ -netdev user,id=net0 \ -smp 4 \ -drive "if=none,file=${img},id=hd0" \ -device virtio-blk-device,drive=hd0 \ -drive "file=${user_data},format=raw" \ -pflash flash0.img \ -pflash flash1.img \ ; Output: QEMU 4.2.1 monitor -type 'help' for more information (qemu) I want to install and run ubuntu desktop on QEMU, the "-nographic " option is only suitable for "ubuntu server ". How to install ubuntu desktop without "-nographic " on the (qemu) console? |
Google API Calendar OAUTH2 The remote server returned an error: (404) Not Found Posted: 07 May 2022 05:13 AM PDT async void GetEvent(string access_token) { String serviceURL = "https://www.googleapis.com/calendar/v3/calendars/{email}/events"; String url = string.Format(serviceURL + "&key={0}&scope={1}", clientSecret, "https://www.googleapis.com/auth/calendar.events.readonly"); // sends the request HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(url); userinfoRequest.Method = "GET"; userinfoRequest.Headers.Add(string.Format("Authorization: Bearer {0}", access_token)); userinfoRequest.ContentType = "application/json"; userinfoRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; userinfoRequest.UseDefaultCredentials = true; userinfoRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; // gets the response WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync(); using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream())) { // reads response body string userinfoResponseText = await userinfoResponseReader.ReadToEndAsync(); output(userinfoResponseText); } } |
While want to see specific query items form DB getting this error : No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate] Posted: 07 May 2022 05:13 AM PDT Access to XMLHttpRequest at 'https://url.herokuapp.com/product?email=emailaddress' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Also getting Axios error. |
Removing first row from a 2d array. (producer-consumer queue) c++ Posted: 07 May 2022 05:13 AM PDT My task is to create an array queue in C++ with producer and consumer . In the code below I have created the queue and the producer class . But now I have trouble creating the producer part. In the producer class , I should get the first row from the queue[][] , sort it, and then remove or pop it from the queue[][] . The problem I am facing is that I don't know how to remove the first row from the queue[][] . Is there any way to do that, without converting my queue to vector ? As the task should be implemented using arrays . Code #include <iostream> #include <mutex> #include <condition_variable> #include <thread> #include <chrono> #include <string> #include <random> #include <vector> #include <array> #include <time.h> using namespace std; using namespace std::chrono; #define SIZE 3 int queue[SIZE][SIZE]; int rows = sizeof queue / sizeof queue[0]; int front = -1; int rear = -1; condition_variable cv; mutex mtx; class queueClass{ public: queueClass(){} void enqueue(int passedArray[]){ lock_guard<mutex> lck(mtx); if (rear != SIZE-1){ if(front == -1 && rear == -1){ rear++; front++; for(int j=0; j<rows; j++){ queue[rear][j] = passedArray[j]; } }else{ rear++; for(int j=0; j<rows; j++){ queue[rear][j] = passedArray[j]; } //queue[rear] = value; } } else{ cout << "Queue is full!" << endl; } cv.notify_one(); } void dequeue(){ if(front != -1 && rear != -1 && front <= rear){ front++; }else{ cout << "Queue is empty!" << endl; } } /*int peek(){ if(front != -1 && rear != -1 && front <= rear){ return queue[front]; }else{ cout << "Queue is empty!" << endl; return -1; } }*/ void display(){ if(front != -1 && rear != -1 && front <= rear){ for(int i=front; i<=rear; i++){ for(int j=front; j<=rear; j++){ cout << queue[i][j] << "\t"; } cout << "\n"; } }else{ lock_guard<mutex> lck(mtx); cout << "Queue is empty!" << endl; } } }; class Producer{ public: queueClass m ; //Producer(){} void Producer1(int n_of_arr){ int a1[3]; while(n_of_arr!=0){ for(int i=0; i<n_of_arr; i++){ a1[i] = rand()%100; } m.enqueue(a1); n_of_arr--; } } }; class Consumer{ public: void Consumer1(){ queueClass q; // My problem is here } }; int main(){ srand((unsigned int)time(NULL)); queueClass m; Producer p; Consumer c; thread CF(&Producer::Producer1, p, 3); CF.join(); m.display(); //m.enqueue(10); cout<<"dequeue\n"; c.Consumer1(); m.display(); cin.get(); } |
Reverse Proxy to HTTP server via IIS with SSL Posted: 07 May 2022 05:13 AM PDT web.config <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="ReverseProxyApi" stopProcessing="true"> <match url="api/(.*)" /> <action type="Rewrite" url="http://localhost:3000/{R:1}" /> </rule> <rule name="ReverseProxyClient" enabled="true" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{CACHE_URL}" pattern="^(.+)://" /> </conditions> <action type="Rewrite" url="{C:1}://localhost:3001/{R:1}" /> <serverVariables> <set name="HTTP_SEC_WEBSOCKET_EXTENSIONS" value="" /> </serverVariables> </rule> </rules> </rewrite> </system.webServer> </configuration> I have successfully created a reverse proxy from http://localhost:9999 to my http://localhost:3000 (NestJS api server) and http://localhost:3001 (NextJS client server) using the above config in rewrite url. My problem is that I am geting an error when I tried to bind https://localhost:8888 to the same site. I made sure that the https url is in the site bindings. I also have a self signed ssl certificate with it. This is the error I am getting: As you can see here https://localhost:8888 is in the site bindings This is self signed certificate that I am using I have no idea what is wrong in my setup. I have tried to restart both the website and the whole IIS server but I am getting the same error. |
how to add type hint for function return something I don't Know Posted: 07 May 2022 05:13 AM PDT How Can I add type hint for conn.cursor() def connect(self,dbname:str,user:str,password:str): """Create Connection to the Postgre database using Json File have the required data in it 1.dbname 2.user 2.password (if there was) return Curser Object or 0 if Can't """ try: conn = psycopg2.connect(dbname=dbname, user=user, password=password,cursor_factory=RealDictCursor) return conn.cursor() except: return 0 ``` |
Last number of iterator in python Posted: 07 May 2022 05:13 AM PDT How to edit the iterator giving also the last number in the sequence, please? I mean in general, not for such an easy sequence. Using < instead of == is not an option. class P(): def __init__(self, n0): self.n = n0 def __iter__(self): return self def __next__(self): if self.n < 1: raise StopIteration num = self.n self.n = self.n - 1 return num nmax = 10 PP = P(nmax) PPP = [] for j in PP: PPP.append(j) print(PPP) Current output: [10, 9, 8, 7, 6, 5, 4, 3, 2] Desired output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] |
want t print the max integer ot of four but extra 1 is added to the result Posted: 07 May 2022 05:13 AM PDT include <stdio.h> int max_of_four(int,int,int,int); int main() { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four(a, b, c, d); printf("%d", ans); } int max_of_four(int a,int b,int c,int d){ if (a>b && a>c && a>d) { return printf("%d",a); } if (b>a && b>c && b>d) { return printf("%d",b); } if (c>a && c>b && c>d) { return printf("%d",c); } if ( d>a && d>b && d>c) { return printf("%d",d); } return 0; } |
Next/Image on Next.js Not Showing Posted: 07 May 2022 05:14 AM PDT I am using next.js 11.1.0 , my images are not showing saying (image below). I tried upgrading to next.js 12 but the problem still persist. I also tried using img tag and it works fine, just next/image not working. It seems not to work on live site production. My images are stored locally. Anyone encountered this? <Image src="images/Uploads/Activities/StoryTelling/3_2022-05-07203A383A38.jpeg" width={500} height={500} /> |
How to print following empty up side down pattern Posted: 07 May 2022 05:14 AM PDT I am trying to print this following pattern , But not able to frame logic My code : for i in range(1,row+1): if i == 1: print(row * '* ') elif i<row: print( '* ' + ((row - 3) * 2) * ' ' + '*') row = row - 1 else: print('*') Expected output : * * * * * * * * * * * * * * * * * * * * * But my code gives me abnormal output : * * * * * * * * * * * * * * * * * * |
How to put buttons on two ends of screen in flutter Posted: 07 May 2022 05:14 AM PDT I want the buttons on flutter to be either side of screen i.e one on the bottom right and one on the bottom left. I want the minus button on the left side of screen : I have searched online but I can't find any help, I have tried to use align but it just gives something messy. My code for the flutter is(some changes in demo app and using Align): void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.red, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } void _decrementCounter(){ setState(() { -_counter --; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: Row( mainAxisAlignment: MainAxisAlignment.end, children : [ Align( alignment: Alignment.bottomLeft, child : FloatingActionButton( onPressed: _decrementCounter, tooltip: 'decrement', child: const Icon(Icons.remove), heroTag: null, )), FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), heroTag: null, ) , ]), // This trailing comma makes auto-formatting nicer for build methods. ); } } How can I achieve this? |
How to cascade two useEffects in React? Posted: 07 May 2022 05:13 AM PDT I want to submit data to the server. The server replies with successful insertion in the database. Then I want to see the updated data on the database. Because I have two useEffects, those work concurrently and I get the old data back. Not after the new data inserted. How can I wait for the first data to be successfully inserted to the database and then fetch the updated data from the server? I have used setTimeOut(). It does not delay the execution of the second useEffect to fetch the updated data. |
Firestore setDoc() method somehow generates a unique identifier when doc says it won't Posted: 07 May 2022 05:14 AM PDT Google documentation states that When you use set() to create a document, you must specify an ID However, I just learned that I CAN call setDoc without specifying the ID like this, and it will still generate a unique identifier. await setDoc(doc(collctionRef), { createdAt: new Date(), updatedAt: new Date(), }); Question - Is the Firebase documentation outdated? or is there something I missed?
- If this is true,
addDoc seems useless now. Or is there another use for it? |
In a DTD, can an attribute be in only one of two declared elements? Posted: 07 May 2022 05:14 AM PDT I have to write a DTD valid for this XML document: <orders> <order> <_id ord_date="2020-03-01" status="A">1.0</_id> <cust_id>Ant O. Knee</cust_id> <items> <element> <price>2.5</price> <qty>5.0</qty> <sku>oranges</sku> </element> <element> <price>2.5</price> <qty>5.0</qty> <sku>apples</sku> </element> </items> <price>25.0</price> </order> <order> <_id>3.0</_id> <cust_id ord_date="2020-03-08" status="A">Busby Bee</cust_id> <items> <element> <price>2.5</price> <qty>10.0</qty> <sku>oranges</sku> </element> <element> <price>2.5</price> <qty>10.0</qty> <sku>pears</sku> </element> <element> <price>0.0</price> <qty>1.0</qty> <sku>gift</sku> </element> <element> <price>0.0</price> <qty>1.0</qty> <sku>gift</sku> </element> </items> <price>50.0</price> </order> </orders> As you can see, I have to declare the attribute ord_date and status inside _id or cust_id but it has to be in only one of those two. I have tried to declare it like this, but this DTD allows to be in both, in one of them or in none of them. <!ELEMENT orders(order)+> <!ELEMENT order(_id, cust_id, items, price)> <!ELEMENT _id> <!ELEMENT cust_id (#PCDATA)> <!ELEMENT items (element)+> <!ELEMENT element (price, qty, sku)> <!ELEMENT price> <!ELEMENT qty> <!ELEMENT sku (#PCDATA)> <!ATTLIST _id ord_date CDATA #IMPLIED> <!ATTLIST cust_id ord_date CDATA #IMPLIED> How can I declare this DTD correctly? |
Filtering data into a list with sections Posted: 07 May 2022 05:13 AM PDT I have data sorted by priority. I'm trying to display that data in a list as: priority 1 item with that priority item with that priority priority 2 item with that priority item with that priority So I thought using a list with sections to display the priority, and then list under each item that has that priority. struct PriorityView: View { @EnvironmentObject private var taskdata: DataModel @State var byPriotity: Int var body: some View { List { VStack(alignment: .leading, spacing: 12) { // priority 3 is display all items in the list if byPriotity == 3 { ForEach(taskdata.filteredTasks(byPriority: byPriotity), id: \.id) { task in Section(header: Text(getTitle(byPriority: task.priority)).font(.headline)) { Text(task.title) } } } } } } } This just creates a list with a section that displays the priority, and then the title of the item. Which is not what I wanted to output. I started reading about section and some articles (this, this, and this) provide some good advise, but I'm stuck trying to figure out how to iterate and find all items with a specific priority, create a header, and then list all those item's titles. Maybe I should add a second forEach filtering all of the items with that particular priority? Or save the initial filtering in a variable and then filter that? I don't know. I tried with ForEach(taskdata.filteredTasks(byPriority: 3)) { task in Section(header: Text(getTitle(byPriority: task.priority)).font(.headline)) { ForEach(task.priority.filter {$0.contains(byPriotity) || byPriotity.isEmpty}) { Text(task.title) } } } But I can't filter them like that. Int doesn't have filter Then I tried ForEach(task.priority.isEqual(to: byPriotity)) And again, issues with an int not having isEqual . And I'm going in circles here... Here's the code I'm trying: struct Task: Codable, Hashable, Identifiable { var id = UUID() var title: String var priority = 2 } extension Array: RawRepresentable where Element: Codable { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode([Element].self, from: data) else { return nil } self = result } public var rawValue: String { guard let data = try? JSONEncoder().encode(self), // comment all this out let result = String(data: data, encoding: .utf8) else { return "[]" } return result } } final class DataModel: ObservableObject { @AppStorage("tasksp") public var tasks: [Task] = [] init() { self.tasks = self.tasks.sorted(by: { $0.priority < $1.priority }) } func sortList() { self.tasks = self.tasks.sorted(by: { $0.priority < $1.priority }) } func filteredTasks(byPriority priority: Int) -> [Task] { tasks.filter { priority == 3 || $0.priority == priority } } } struct PriorityView: View { @EnvironmentObject private var taskdata: DataModel @State var byPriotity: Int var body: some View { List { VStack(alignment: .leading, spacing: 12) { // priority 3 is display all items in the list // I'm going to add another view so the user can // can select what to display eventually if byPriotity == 3 { ForEach(taskdata.filteredTasks(byPriority: byPriotity), id: \.id) { task in Section(header: Text(getTitle(byPriority: task.priority)).font(.headline)) { Text(task.title) } } } } } } func getTitle(byPriority:Int) -> String { switch byPriority { case 0: return "Important" case 1: return "Tomorrow" default: return "Someday" } } } EDIT: Trying with the code that vadian suggested. I really don't know what I'm doing, but tried, and this is the result: Changed the struct name to: struct SectionOrdered : Identifiable { var id: String { priority } let priority: String let tasks: [Task] } The code I tried is: List { VStack(alignment: .leading, spacing: 12) { if byPriority == 3 { ForEach(taskdata.sections) { task in Section(header: task.priority) { Text(task.title) } } } } } vadian suggested to filter all in the class, but I have no clue how to use that. I tried, but I'm making a worse mess here. I wonder if this is possible at all. |
How to avoid rebuilding widgets when using Stream Builder with Firestore? Posted: 07 May 2022 05:14 AM PDT I built an E-commerce app using Firebase/Firestore and I am using Stream Builder or Future Builder and facing high Firestore reads. When I press on Hot-Reload all Stream Builders in the app rebuild (I am using the print method to track the rebuilding). The hot-reload rebuilds the previous screen widget (Includes Stream Builder or Flutter Builder), after Navigator.push. I need to reduce Firestore high reads and avoid many rebuilds. Can someone help me to fix it? Example: class _SliderView extends StatefulWidget { const _SliderView({ required this.slidersItems, Key? key, }) : super(key: key); final Future<List<SliderModel>> slidersItems; @override State<_SliderView> createState() => _SliderViewState(); } class _SliderViewState extends State<_SliderView> { final CarouselController _carouselController = CarouselController(); int currentIndex = 0; int nextPage = 0; late int offersLength; @override void initState() { super.initState(); } @override void dispose() { _carouselController.stopAutoPlay(); super.dispose(); } @override Widget build(BuildContext context) { return FutureBuilder<List<SliderModel>>( future: widget.slidersItems, builder: (context, snapshot) { print("## Home - Slider Viewer ##"); if (snapshot.data != null) { return SizedBox( width: double.infinity, child: Stack( children: [ NotificationListener<OverscrollIndicatorNotification>( onNotification: (scroll) { scroll.disallowIndicator(); return false; }, child: CarouselSlider.builder( carouselController: _carouselController, options: CarouselOptions( viewportFraction: 1.0, height: ScreenSize.screenHeight, autoPlay: snapshot.data!.length > 1 ? true : false, onPageChanged: (val, reason) { setState(() { currentIndex = val; }); }, ), itemCount: snapshot.data!.length, itemBuilder: (context, index, eall) { // ProductModel productModel = // ProductModel.fromJson(fetched.data()); // SliderModel sliderModel = SliderModel.fromMap(fetched.data()); // sliderModel.itemPriceWithDiscount == 0.0 // ? sliderModel.prodPrice.toString() // : sliderModel.itemPriceWithDiscount.toString(); return GestureDetector( onTap: () { // Navigator.pushNamed( // context, // Routes.productDetails, // arguments: productModel, // ); }, child: SizedBox( width: ScreenSize.screenWidth!, child: snapshot.data![index].itemImageUrl == null || snapshot.data![index].itemImageUrl!.isEmpty ? const Center( child: CustomLogo(size: 133), ) : CachedNetworkImage( width: double.maxFinite, imageUrl: snapshot.data![index].itemImageUrl .toString(), fit: BoxFit.cover, placeholder: (context, url) { return const CustomProgressIndicator(); }, errorWidget: (context, url, error) { return const Center( child: CustomLogo(), ); }, ), ), ); }, ), ), Positioned( bottom: 10, child: BuildIndicators( itemIndex: snapshot.data!.length, currentIndex: currentIndex, ), ), ], ), ); } else { return const CustomProgressIndicator(); } }, ); } } |
How to access nested array Posted: 07 May 2022 05:14 AM PDT I am trying to access recipeIngredient in this array. I have tried this: <cfloop from="1" to="#ArrayLen(contents)#" index="i"> <cfoutput> #i.recipeIngredient#<br> </cfoutput> </cfloop> I am getting an error "You have attempted to dereference a scalar variable of type class coldfusion.runtime.Array as a structure with members." |
Why is my collections.sort leading to different outputs in 2 arraylists with the same data Posted: 07 May 2022 05:13 AM PDT I am having some trouble sorting 2 arraylists of mine which have the exact same data, one is received through my API and the other is parsed through ingame text fields, for some reason they are sorted differently even though they are the exact same. public ArrayList<String> names = new ArrayList<>(); AbowAPI api = new AbowAPI(); @Override public void onStart() throws InterruptedException { try { names = api.getTargets(); Collections.sort(names); } catch (IOException e) { log(e.getStackTrace()); } } @Override public int onLoop() throws InterruptedException { if(tabs.getOpen() != Tab.FRIENDS) { tabs.open(Tab.FRIENDS); } else { ArrayList<String> friendList = getFriendNames(); Collections.sort(friendList); log(friendList); } This here is the resulting output [INFO][Bot #1][05/06 07:59:51 em]: [abc, abow42069, adam, bad, bl ack, blood, blue, bye, dead, dog, google, her, him, john wick, light, lol, mad, red] [INFO][Bot #1][05/06 07:59:51 em]: [abc, abow42069, adam, bad, blood, blue, bl ack, bye, dog, google, her, him, john wick, light, lol, mad, red] As I try comparing the 2 arraylists they are not also not equal, I need them to be sorted the same way so they match but I'm having troubles with it, any help to why they are sorting in different ways? This is my API call to get the targets, maybe this is what is causing the weird bug? enter code here URL url = new URL("http://127.0.0.1:5000/snipes"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; ArrayList<String> content = new ArrayList<>(); while ((inputLine = in.readLine()) != null) { content.add(inputLine); } in.close(); return content; |
why sites are not displayed correctly on heroku Posted: 07 May 2022 05:15 AM PDT I'm new to Java development. I made an application that checks the functionality of sites. When you start the Spring application, all sites work and display correctly. I deployed the application to Heroku and the sites no longer display correctly. Most likely the problem is due to Heroku, but how to fix it? Controller public class DetektController { private final SiteService siteService; private final GetAllService getAllService; public DetektController(SiteService siteService, GetAllService getAllService) { this.siteService = siteService; this.getAllService = getAllService; } private String getStatus(boolean result) { if (result) { return " OK"; } else { return "FAIL"; } } @GetMapping("/all") String getAll(Model model) { List<CheckResult> checkResults = getAllService.getUriAndStatus(); List<CheckResultDto> checkResultDtos = new ArrayList<>(); for (CheckResult checkResult : checkResults) { checkResultDtos.add(new CheckResultDto(checkResult.getUri(), getStatus(checkResult.isStatus()))); } model.addAttribute("sites", checkResultDtos); return "all"; } @GetMapping("/add") String addSite() { return "add.html"; } @PostMapping("/add") String addNewSite(@ModelAttribute AddNewSiteRequestDto request) { Site site = new Site(null, request.getSite()); siteService.save(site); return "redirect:/all"; } @GetMapping("/deleteAll") String deleteAllSite() { siteService.deleteAllSite(); return "redirect:/all"; } @GetMapping("/deleteByUri") String deleteByUri(@RequestParam String uri) { siteService.deleteByUri(uri); return "redirect:/all"; } Service public class SiteService { private final SiteRepositoryDao siteRepository; public Site save(Site site) { return siteRepository.save(site); } public Iterable<Site> getAll() { return siteRepository.findAll(); } public void deleteAllSite() { siteRepository.deleteAll(); } public void deleteByUri(String uri) { siteRepository.deleteByUri(uri); } @Service public class GetAllService { private final InetAddressCheckerService inetAddressCheckerService; private final SiteService siteService; private final int timeout; private final SiteConditionRepositoryDao siteConditionRepositoryDao; public GetAllService( InetAddressCheckerService inetAddressCheckerService, SiteService siteService, @Value("${url-checker.timeout}") int timeout, SiteConditionRepositoryDao siteConditionRepositoryDao ) { this.inetAddressCheckerService = inetAddressCheckerService; this.siteService = siteService; this.timeout = timeout; this.siteConditionRepositoryDao = siteConditionRepositoryDao; } public List<CheckResult> getUriAndStatus() { Iterable<Site> sites = siteService.getAll(); List<CheckResult> checkResults = new ArrayList<>(); List<SiteCondition> siteConditions = new ArrayList<>(); for (Site site : sites) { boolean result = inetAddressCheckerService.checkUriAddress(URI.create(site.getUri()), timeout); CheckResult checkResult = new CheckResult(site.getUri(), result); SiteCondition siteCondition = new SiteCondition(null, site.getUri(), result, LocalDateTime.now()); siteConditions.add(siteCondition); checkResults.add(checkResult); } siteConditionRepositoryDao.saveAll(siteConditions); return checkResults; } @Service public class InetAddressCheckerService { public boolean checkUriAddress(URI address, int timeOut) { boolean result; try { result = InetAddress.getByName(address.getHost()).isReachable(timeOut); return result; } catch (IOException e) { } return false; } } веб отображение <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="css/style1.css" rel="stylesheet"> </head> <body> <h1> Результат проверки работоспособности сайтов </h1> <h4> <form action="/deleteAll" method="get" onsubmit="return checkDeleteAll()"> <input type="submit" value=" Delete ALL"> </form> <script> function checkDeleteAll(){ return window.confirm("Точно удалить все записи?") } </script> </h4> <table> <tr> <th>Uri</th> <th>Status</th> <th>Operation</th> </tr> <th:block th:each="site : ${sites}"> <tr> <td th:text="${site.uri}"></td> <td th:text="${site.status}"></td> <td> <form th:action="@{deleteByUri}" method="get"> <input type="hidden" name="uri" th:value="${site.uri}"/> <input type="submit" value="Delete" class="btn btn-danger"/> </form> </td> </tr> </th:block> </table> </body> </html> enter image description here enter image description here |
Recursive data structure unmarshalling gives error "cannot parse invalid wire-format data" in Go Lang Protobuf Posted: 07 May 2022 05:15 AM PDT OS and protobuf version go1.18.1 linux/amd64, github.com/golang/protobuf v1.5.2 Introduction I am trying to use recursive proto definitions. .proto file message AsyncConsensus { int32 sender = 1; int32 receiver = 2; string unique_id = 3; // to specify the fall back block id to which the vote asyn is for int32 type = 4; // 1-propose, 2-vote, 3-timeout, 4-propose-async, 5-vote-async, 6-timeout-internal, 7-consensus-external-request, 8-consensus-external-response, 9-fallback-complete string note = 5; int32 v = 6 ; // view number int32 r = 7;// round number message Block { string id = 1; int32 v = 2 ; // view number int32 r = 3;// round number Block parent = 4; repeated int32 commands = 5; int32 level = 6; // for the fallback mode } Block blockHigh = 8; Block blockNew = 9; Block blockCommit = 10; } The following is how I Marshal and Un-Marshal func (t *AsyncConsensus) Marshal(wire io.Writer) error { data, err := proto.Marshal(t) if err != nil { return err } lengthWritten := len(data) var b [8]byte bs := b[:8] binary.LittleEndian.PutUint64(bs, uint64(lengthWritten)) _, err = wire.Write(bs) if err != nil { return err } _, err = wire.Write(data) if err != nil { return err } return nil } func (t *AsyncConsensus) Unmarshal(wire io.Reader) error { var b [8]byte bs := b[:8] _, err := io.ReadFull(wire, bs) if err != nil { return err } numBytes := binary.LittleEndian.Uint64(bs) data := make([]byte, numBytes) length, err := io.ReadFull(wire, data) if err != nil { return err } err = proto.Unmarshal(data[:length], t) if err != nil { return err } return nil } func (t *AsyncConsensus) New() Serializable { return new(AsyncConsensus) } My expected outcome When marshaled and sent to the same process via TCP, it should correctly unmarshal and produce correct data structures. Resulting error error "cannot parse invalid wire-format data" Additional information I tried with non-recursive .proto definitions, and never had this issue before. |
How to test system that requires Time resource? Posted: 07 May 2022 05:13 AM PDT I want to write tests for system that moves entities and detects collisions, system uses Res<Time> to ensure that entities move with constant speed. I was trying to write test following this example, but it doesn't use Time. My test creates world and inserts two entities and tries to run my system. let mut world = World::default(); /* here insert entities into world */ let mut update_stage = SystemStage::parallel(); update_stage.add_system(move_system); It doesn't insert Time resource so unsurprisingly running it ends with panicked at 'Resource requested by io_project::move_system::move_system does not exist: bevy_core::time::time::Time' World has method insert_resource() but I wasn't able to figure out if I can use it to insert Time resource. I was also wondering if it would be possible to use some kind of ''fake'' time, meaning that instead of checking how much time really passed I would call something like time.pass_seconds(1.) . This would be useful to simulate very high or low framerate and create more consistent results. I am using bevy 0.6.1 |
How do text-editors recognize if the user wanted to type a number or the ascii value associated with it? Posted: 07 May 2022 05:14 AM PDT According to my current understanding:- - All binary values are treated as equal by the system, and it is the task of the software (or the app) to interpret a binary value as text or image, etc. based on the context in which the app expects the data to be.
- When a key is pressed by the user, an event is fired by the system and any running application handles the event and gets the value of the key pressed.
Now, take for example the user presses the tab key. Binary Value of the horizontal tab (if I'm not wrong) - 00001001 When this binary value is converted into its decimal equivalent, we get "9" as the value. Now my doubt[s] are:- - How does the text editor recognize whether the value "9" or a horizontal tab is to be taken as the final value? In other words,
- How does the software know whether or not the decimal value needs to be converted to its ASCII character equivalent?
- Whether the tab key or the digit 9 key was pressed?
- How, or in what form, or with what details does the system fire an event for a keypress?
I would be glad if you could help me out (in simple terms, of course), and please do point out if I am mistaken at something. Thank you! |
Any way to return information about/from a Powershell File-Watcher that has been triggered? Posted: 07 May 2022 05:14 AM PDT Situation Summary Currently I have two separate Powershell(PS) Consoles, each with its own Filewatcher(FW), watching for a created file(txt file) from each Build. The code is nearly identical excluding the Notify Filter. The both currently call the same script to start the tests. I have 2 sets of logs(Output added to a txt file) that come as a result of a triggered FW, One Log is for the TestPS Script and then the other is the Test Results pumped out through a CMD prompt(The tests are using Selenium Webdriver). The TestPS Script doesn't determine which tests to run but I cannot log which one was called because the of the handoff from FW to TestPS. I only know which one was called from the Test Results after the fact. The order of operations are as follows: -2 PS Scripts each with a FW are started prior, left running. -One FW with Notify Filter "A" watching folder location "A" -Second FW with Notify Filter "B" watching folder location "B" -One Builds kicks off, creates file in corresponding location and filter -Triggered FW calls Main PS script to start Tests What I want it to do: -Only One FW is started prior, left running -FW with Notify Filters "A" and "B", Watches Folder Location "C" -One of Builds kicks off, Triggers location "C" -FW somehow Filters or Passes some sort of information(Such as the Filename which I can Parse in the Test PS for a key phrase or something) to the TestPS to indicate which build had been triggered. -FW calls Main PS script to start Tests (Could happen in the same step as above, Doesn't necessarily matter) I have tried the Following: Method A: 2 PSs each with their own FW watching their own location with a filter variation each with a Register-ObjectEvent that calls the TestPS. (Current/technically works) Method B: 1 PS with 2 FWs each with filter variation with 1 Register-ObjectEvent that calls the TestPS Method C: 1 PS with 2 FW each with filter variation with 2 Register-ObjectEvents that calls the TestPS Method D: 1 PS with 1 FW watching Subdirectories with 1 Register-ObjectEvent that calls the TestPS Method E:(Theory) 1 PS with 1 FW with 2 filters that passes which filter was detected to TestPS Function FileWatcher{ $folder = New-Object IO.FileSystemWatcher " <FilePathA> ", "*.triggerOne" -Property @{ IncludeSubdirectories = $false NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' } $folderTwo = New-Object IO.FileSystemWatcher " <Either FilePathA or FilePathB> ", "*.triggerTwo" -Property @{ IncludeSubdirectories = $false NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' } $eventAction = Register-ObjectEvent ($folder) Created -SourceIdentifier FileCreated -Action { try{ Start-Process -FilePath Powershell -ArgumentList " <FilePath to TestPS> " #Within this powershell I want to somehow be able to determine which Filewatcher was triggered } catch [System.Exception]{ Add-Content -Path " <FilePath to Txt file for logging errors> " -Value ("Error: "+$error[0]) Write-Warning ("Error: "+$error[0]) } } $eventActionTwo = Register-ObjectEvent ($folderTwo) Created -SourceIdentifier FileCreated -Action { try{ Start-Process -FilePath Powershell -ArgumentList " <FilePath to TestPS> " #Within this powershell I want to somehow be able to determine which Filewatcher was triggered } catch [System.Exception]{ Add-Content -Path " <FilePath to Txt file for logging errors> " -Value ("Error: "+$error[0]) Write-Warning ("Error: "+$error[0]) } } } FileWatcher #Method Call Results: Method A: Current/Technically works, but requires setup as described in Summary. Method B: Works, but No indication of which is called/No way to Create one Register-ObjectEvent with two filters Method C: Apparently cannot have two Register-ObjectEvent with FileCreated source even with different filters. Error: Register-ObjectEvent : Cannot subscribe to the specified event. A subscriber with the source identifier 'FileCreated' already exists. <...> + CategoryInfo : InvalidArgument: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent], ArgumentException + FullyQualifiedErrorId : SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand Method D: No indication to TestPS of which build was triggered Method E: Theory, Haven't tried |
Identifying the same Web Elements with Selenium Posted: 07 May 2022 05:13 AM PDT I am an Automation Engineer, I am currently trying to create test cases for a webpage that are sustainable ( that I can run at a later time and have still pass) Here is my problem: I am trying to select multiple web buttons that have the same exact class name. Now I can 'select' these buttons but these are only temporary x paths that are subject to change. I need UNIQUE ID's (or some way of distinguishing them) for the same web elements. The only difference in the x paths are: HTML format code that I can find each button, however if one button is moved my tests will fail. HTML code that is the class name + nth of the button. But again my tests will fail if a button is taken out of the webpage. //*[@id="tenant-details-accordion"]/div[1]/div[2]/div/div[2]/div[1]/div/a/div //*[@id="tenant-details-accordion"]/div[1]/div[2]/div/div[2]/div[2]/div/a/div //*[@id="tenant-details-accordion"]/div[1]/div[2]/div/div[2]/div[3]/div/a/div ^^The above code is how I currently find each button with Selenium If I copy each classes x path this is what I get <div class="src-js-components-DateControl-___DateControl__dateControl___2nYAL"><a tabindex="0"><div class="src-js-components-DateControl-___DateControl__icon___2z6Ak null"></div><!-- react-text: 392 -->Set +<!-- /react-text --></a></div> <div class="src-js-components-DateControl-___DateControl__dateControl___2nYAL"><a tabindex="0"><div class="src-js-components-DateControl-___DateControl__icon___2z6Ak null"></div><!-- react-text: 386 -->Set +<!-- /react-text --></a></div> <div class="src-js-components-DateControl-___DateControl__dateControl___2nYAL"><a tabindex="0"><div class="src-js-components-DateControl-___DateControl__icon___2z6Ak null"></div><!-- react-text: 398 -->Set +<!-- /react-text --></a></div> I have talked to the Development team about this issue however they tell me that assigning Unique ID's to these web elements is a big no-no. (something to do with globalization of the project when we go to production) Even if they did assign Unique Id's they tell me that they would have to strip them before the project can be sent to production. Which ultimately would render my tests useless in the end... I now come to Stack Overflow for help, everything I look up online cannot give me an answer, however this does seem to be a valid question between QA and Development departments. Is there a way to assign Id's to a web element so that a tester using selenium can identify them and yet it will not affect a Developers ability to use that element through an entire project? Edit: With the framework that my company uses, I am not actually writing any code in selenium. I save the Xpath to an object and then later in a manual test call that object with a pre-existing method. I can ONLY select Xpaths to be saved in an object. I'll talk to Dev later to have them explain the big 'no-no' so that I may be able to communicate that with all of you..Thank you for your time and input For example: BirthDateSet= someXpath Click() using {BirthDateSet} Here are some pictures to help give you a visual |
How do I see changes made to a kernel module? Posted: 07 May 2022 05:14 AM PDT I have a module running on my Linux machine and can see it using lsmod command. Now I made some changes (added some printk) to this module, recompiled it and got the .ko. Now I did rmmod to remove this module (some other modules also which are using this module), did insmod xxx.ko and rebooted the system. Now where do I see the statements added using printk? I tried to see using dmesg grep | "SPI RW" But I couldn't find anything. What am I doing wrong here? |
Selenium Parallel Browser testing in python Posted: 07 May 2022 05:14 AM PDT I am working with Selenium for a while and doing some testing and it's been great. Now I have created a test case which I want to run it on IE, Firefox and Google Chrome at the same time. I have run it separately and they run just fine, but I was wondering if there a way to change my script and run them all together. I already set up the grid with a hub and three remote controls (Firefox port=5556, IE port=5557 and Chrome port=5558). Now when it comes to the script I set up the three divers: def setUp(self): # Setting up the driver for Firefox self.driverFF = webdriver.Firefox() ... # Setting up the driver for IE self.driverIE = webdriver.Ie() ... # Setting up the driver for IE self.driverCh = webdriver.Chrome() ... Then I created three different methods and run them with each driver. I have not test it yet, but I was wondering: Is there a efficient way to do this? Thanks in advance! |
No comments:
Post a Comment