How to convert a string array to float array? Posted: 20 Jun 2022 06:54 PM PDT I basically first converted a multidimensional array to a string array in order to set the values as my dictionary key, and now I need to convert the string array back to a regular float array. For example, what I have is: str_array = ['[0.25 0.2916666666666667]', '[0.5833333333333334 0.2916666666666667]', '[0.5555555555555555 0.3333333333333332]'] And I literally just need it back as a regular array array = [[0.25 0.2916666666666667], [0.5833333333333334 0.2916666666666667], [0.5555555555555555 0.3333333333333332]] I have tried all the following : (*independently) for i in str_arr: i.strip("'") np.array(i) float(i) Yet none of them work. They either cannot convert str --> float or they still keep the type as a str. Please help. |
React - Handle clicking a button to display some text Posted: 20 Jun 2022 06:53 PM PDT I map buttons and need them to display text once clicked. I use an ID state to grab which key was clicked and then the classname should display that text, and should only display one description at a time. Here's my code for the component: import { useState } from 'react'; const items = [ { name: 'Pizza', description: 'Cheese, bread, red sauce', price: '4.99', key: 0, }, { name: 'Spaghetti', description: 'cooked noodles, red sauce, parmesan', price: '3.99', key: 1, }, { name: 'Soda', description: 'pepsi products', price: '4.99', key: 2 }, ]; const MenuItem = () => { const [ID, setID] = useState(null); const itemHandler = (item) => { console.log(item); if (ID === null) { setID(item.key); } else { setID(null); } console.log(ID); }; return ( <li className="items"> {items.map((item) => { return ( <ul key={item.key}> <button className="menu-item" onClick={itemHandler}> {`${item.name} ${item.price}`} </button> <h4 className={`menu-description ${ ID === item.key ? 'active-item' : 'none' }`} > {item.description} </h4> </ul> ); })} </li> ); }; export default MenuItem; When I console.log(item) I get the event (clicking the button) instead of item from the items array. Not sure what I can do to fix. |
Loop over a list of ids and foreach id get data from api Posted: 20 Jun 2022 06:53 PM PDT Loop over a list of ids and foreach id get data from api but, i can make only 40 requests per 10 seconds, i'm getting data from tbdb but i'm getting kicked by the api here is my code Popular.findAll({ limit: 25 }).then((filmes) => { for (let index = 0; index < filmes.length; index++) { const element = filmes[index]; const id_filme = element.id_filme; i get each movie id so i can make requests to the api with this function.. function fetchdata(id_filme) { setTimeout(function () { axios .all([ axios.get( `https://api.themoviedb.org/3/movie/${id_filme}?api_key=${process.env.API_KEY}&language=pt-BR` ), axios.get( `https://api.themoviedb.org/3/movie/${id_filme}/videos?api_key=${process.env.API_KEY}&language=pt-BR` ), ]) .then( axios.spread(function (detalhes, linksyt) { var filme = detalhes.data; var youtube = linksyt.data; // console.log(filme, youtube); var filmesLista = new Array(); const title = filme.title; const filmeid = filme.id; if (Object.keys(filme.genres).length === 0) { var genre = filme.genres; } else { var genre = filme.genres[0].name; } const overview = filme.overview; const poster_path = "https://image.tmdb.org/t/p/w500" + filme.poster_path; const release_date = filme.release_date; const vote_average = parseFloat(filme.vote_average); const backdrop_path = "https://image.tmdb.org/t/p/original" + filme.backdrop_path; const imdb_id = filme.imdb_id; const runtime = filme.runtime; if (Object.keys(youtube.results).length === 0) { var trailer = ""; } else { var trailer = "http://www.youtube.com/watch?v=" + youtube.results[0].key; } filmesLista.push([ filmeid, title, genre, overview, poster_path, release_date, vote_average, backdrop_path, imdb_id, runtime, trailer, ]); console.log(filmesLista); filmesLista.forEach((i) => { const filmeid = i[0]; const title = i[1]; const genre = i[2]; const overview = i[3]; const poster_path = i[4]; const release_date = i[5]; const vote_average = i[6]; const backdrop_path = i[7]; const imdb_id = i[8]; const runtime = i[9]; const trailer = i[10]; Detalhes.create({ id_filme: `${filmeid}`, title: `${title}`, genre: `${genre}`, release_date: `${release_date}`, vote_average: `${vote_average}`, imdb_id: `${imdb_id}`, runtime: `${runtime}`, overview: `${overview}`, poster_path: `${poster_path}`, backdrop_path: `${backdrop_path}`, trailer: `${trailer}`, }); }); }) ); o++; if (o < 25) { fetchdata(id_filme); } }, 10000); console.log("INSERIDO NO BANCO"); } fetchdata(id_filme); the code works but, works so fast and i get kicked every time i run with more than 40 ids.. i'm strugling on just make 40 request every 10 secconds. anyone can help me please? |
How to track JVM native memory Posted: 20 Jun 2022 06:52 PM PDT JVM native memory leak is suspected, so I want to track memory. I tried Native tracking using the JVM tuning flag as follows, but I couldn't find a memory leak point. java -XX:NativeMemoryTracking=detail Probably because of the following reasons in the document. NMT in this release does not track third party native code memory allocations and JDK class libraries. Also, this release does not include NMT MBean in HotSpot for JMC. Is there any other way to track JVM native memory? |
Is there a lightweight threading alternative for python? Posted: 20 Jun 2022 06:51 PM PDT I basically need 3 threads for my python program - Quiz application and UI
- Countdown timer functionality
- Timer UI
Tried this and it always leads to segmentation faults. Only two threads are allowed to be working based on my experience Are there ways on how I can make this work? Like maybe lightweight threads so that it doesn't lead to segmentation faults? Or should I change languages that maybe supports multi threading more? |
How do i render child route components under a parent route in react router without routing to the child paths Posted: 20 Jun 2022 06:51 PM PDT <Route path="/dashboard" element={<DashboardLayout />}> <Route index element={<DashboardHome />} /> <Route path="update-profile" element={<UpdateProfileForm />} /> <Route path="bookmarks" element={<Bookmarks />} /> </Route> I have my routes setup like this, but i want all the child routes of dashboard to render under the same path without actually routing to the child routes Example: The index route is dashboard Home component and it renders in /dashboard path I want update-profile , bookmarks to render under /dashboard path only not like switching to /dashboard/update-profile path in the browser. |
error occured during initialization of boot layer Posted: 20 Jun 2022 06:51 PM PDT Error occurred during initialization of boot layer java.lang.module.ResolutionException: Modules stax.api and java.xml export package javax.xml.stream.events to module commons.logging |
How to translate the Search button label and the search title page in Drupal 9 Posted: 20 Jun 2022 06:51 PM PDT How in Drupal 8 or 9 can we translate the name of the search page and the label of the search button to is french translation "Rechercher" My site is just in french, no other language. |
What is the name of this kind of histogram and how do i plot it (in python/plotly) Posted: 20 Jun 2022 06:51 PM PDT What is the name of this kind of histogram and how do i plot it (in python/plotly) (if you only know one of the answers thats very welcome too) unknown histogram I mean the blue/red graph |
what is the exactly difference between dto assembler and factory Posted: 20 Jun 2022 06:50 PM PDT As far as I know, factory is responsible for creating complex entity(Aggregate)in DDD, it may contain some business logic. And factory exists in Domain Layer. And the same time, DTO assembler(usually exists in application layer)can also convert DTO to an Entity(dto assembler is not a concept in DDD). Now consider a situation: I need to create an aggregate, but the essential information is in DTO(assume it has many attributes), how can factory get the information?As far as I know, DTO should not pass to Domain Layer where factory exists. And I think DTO assembler should not be responsible for creating Aggregate too. How can I do? Or what is the best practice for this situation? Thanks in advance. |
How to run JMeter scripts with arguments from secrets on GitHub actions Posted: 20 Jun 2022 06:50 PM PDT I set secrets on github as snapshot below: In the ci.yml file, I created a job to jun jmeter scirpts with arguments that getting from secrets action set above: - name: Get current date id: date run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - name: Create a report directory run: | mkdir OutputReports-${{ steps.date.outputs.date }} - name: Set up Jmeter id: setup-jmeter run: | sudo apt update wget https://downloads.apache.org//jmeter/binaries/apache-jmeter-$JMETER_VERSION.zip unzip apache-jmeter-$JMETER_VERSION.zip mv apache-jmeter-$JMETER_VERSION jmeter echo "$GITHUB_WORKSPACE/jmeter/bin" >> $GITHUB_PATH - name: Run JMeter Action on a test run: | jmeter -n -t load_test.jmx -Jusername=${{ secrets.DEV_USERNAME }} -Jpassword=${{ secrets.DEV_PASSWORD }} -f -l OutputReports-${{ steps.date.outputs.date }}/results.jtl -e -o OutputReports-${{ steps.date.outputs.date }}/report-html -j OutputReports-${{ steps.date.outputs.date }}/jmeter.log The arguments -Jusername=${{ secrets.DEV_USERNAME }} -Jpassword=${{ secrets.DEV_PASSWORD }} are not working in my JMeter command line. If I pass value directly into these arguments as: -Jusername=user -Jpassword=pass , it worked okay. I tried echo secrets to make sure I have full access to secret actions, it is shown for me: *** So please help me if you know that how to run JMeter scripts with arguments from secrets on GitHub actions? Thanks! |
How can I serialise and deserialise a custom type array rabbitMq Posted: 20 Jun 2022 06:52 PM PDT I have a simple parking-lot simulation which simulates the entry and exit of customers. A class called entrySimulation is used as the producer and the exitSimulation consumes the message and peforms checks to see if a customer should enter.The entry simulation class is as follows: package parking.experiment_2; public class entrySimulation implements Runnable { public static void main(String[] args) { ScheduledExecutorService entrySimulation = Executors.newScheduledThreadPool(1); entrySimulation.scheduleAtFixedRate(new entrySimulation(), 2, 4, TimeUnit.SECONDS); } ///PRODUCER CLASS int numOfRuns = 100;//1000 runs public securityGuard_exp_1 myGuard = new securityGuard_exp_1(); //System.out.println("Customer Exiting"); //Thread.sleep(randomTime.nextInt(5000)); public meterClass_exp_1 myMeter = new meterClass_exp_1(); //Details are only set if there is space available //The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min //instantiation of the info generator class public infoGenerator_exp_1 info = new infoGenerator_exp_1(); //Generating random Car info //spot_exp_1 mySpot = new spot_exp_1(); //Use an iterator public List<ticketClass_exp_1> ticketArray = new ArrayList<>(); Iterator<ticketClass_exp_1> iter = ticketArray.iterator(); public final spot_exp_1 availableSpot = new spot_exp_1(); //Random time generator Random randomTime = new Random(); //List<Employee> empList = new ArrayList<>(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos; { try { oos = new ObjectOutputStream(bos); } catch (IOException e) { throw new RuntimeException(e); } } public List<ticketClass_exp_1> randomEntry() throws IOException, TimeoutException { Gson gson = new GsonBuilder().create(); carClass_exp_2 car = null; String queueName = "exitQueue"; String message = null; for (int currentRuns = 0; currentRuns < numOfRuns; currentRuns++) { String plateNumber = info.plateGenerator(); String carModel = info.modelGenerator(); String color = info.colorGenerator(); myMeter.setPurchasedMinutes(randomTime.nextInt(30)); carClass_exp1_1 vehicle = new carClass_exp1_1(carModel, color, plateNumber, randomTime.nextInt(2880)); ticketClass_exp_1 myTicket = myGuard.ticketGenerator(vehicle, myMeter); //Generating details myTicket.setmeter(myMeter); myTicket.setCar(vehicle); myTicket.getCar().plateSetter(plateNumber); myTicket.getCar().colorSetter(color); myTicket.getCar().modelSeter(carModel); //myTicket.getGuard().setguardName("Phill"); //myTicket.getGuard().setBadgeNumber("AF170"); int spotAvail = availableSpot.assignSpot(); myTicket.setSlotNum(spotAvail); message = gson.toJson(myTicket); ticketArray.add(myTicket); return ticketArray; } public void publishMessage( ticketClass_exp_1 tickArray ) throws IOException, TimeoutException{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(tickArray); ///Direct exchange from enrtySimulation to exit simulation -Used to inform customer exit //Topic exchange from entrySimulation to individual car park types . EG: Mercedes benz lot, SRT lot, ... String exchangeName = "entryExchange"; String routingKey = "exitKey"; //Creating a connection factory ConnectionFactory factory = new ConnectionFactory(); try(Connection conVar = factory.newConnection()){ Channel channelCon = conVar.createChannel(); //Exchange declaration channelCon.exchangeDeclare(exchangeName,"customerEntry"); channelCon.basicPublish(exchangeName,routingKey,null,bos.toByteArray()); //System.out.println(message); System.out.println("Customer Entered"); }catch(Exception e){} } @Override public void run() { ticketClass_exp_1 message = null; try { message = (ticketClass_exp_1) randomEntry(); } catch (IOException e) { throw new RuntimeException(e); } catch (TimeoutException e) { throw new RuntimeException(e); } //Publishing message try { publishMessage(message); } catch (IOException e) { throw new RuntimeException(e); } catch (TimeoutException e) { throw new RuntimeException(e); } } } The consumer then consumes the array as follows; public class exitSimulation implements Runnable { //public exitSimulation(Channel channel) { //super(channel); //String storedMessage; //} public String reciver() throws Exception { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(); //Creat connection Channel channel = connection.createChannel(); //create channel String recievQueue = channel.queueDeclare().getQueue(); System.out.println(" Awaiting Cars"); consumeConvert consumer=new consumeConvert(channel); channel.basicConsume(recievQueue,true,consumer); // using return consumer.getFormatMessage(); } public class consumeConvert extends DefaultConsumer { private String storedMessage; public consumeConvert(Channel channelReceiver) { super(channelReceiver); } public String getFormatMessage() { return storedMessage; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] messageBody) throws IOException { String message = new String(messageBody, "UTF-8"); System.out.println(" MSG RECIEVED: " + message + "'"); storedMessage = message; // store message here } } public static void main(String[] args) { //Receives message when customers are entering - Contains customer information e.g. customer x is entering.. details .... // Adds them to a local array // IF any customers checkParking(ExitCar, meterOut) == true : CUSTOMER EXITS // // //Get the messages and pass as function inputs /* * public class MyConsumer extends DefaultConsumer { private String storedMessage; public MyConsumer(Object channelRecv) { super(channelRecv); } public String getStoredMessage() { return storedMessage; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); storedMessage = message; // store message here } } * * * Perfrom checks and send exiting car * */ //String qName = channelCon.queueDeclare().getQueue(); //Binding the queue //channelCon.queueBind(qName, exchangeName, routingKey); Collection<ticketClass_exp_2> ticketArray = new ArrayList<ticketClass_exp_2>(); int availableSpot = 0; Random randomTime = new Random(); //System.out.println(availableSpot.getSpotNum()); for (ticketClass_exp_2 tick : ticketArray) { if (ticketArray.size() != 0) { meterClass_exp_2 meterOut = tick.getMeter(); carClass_exp_2 ExitCar = tick.getCar(); securityGuard_exp_2 myGuard2 = new securityGuard_exp_2(); //System.out.println("IND" + tick.slotNum); if (myGuard2.checkParking(ExitCar, meterOut)) { try { Thread.sleep(randomTime.nextInt(2000)); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("\nCustomer " + ExitCar.plateGetter() + " is exiting the carpark..."); double penaltyVal = tick.getPenalty(); System.out.println("FINE: " + penaltyVal); System.out.println("=================================================================="); } } if (availableSpot == 16) { System.out.println("Carpark full, No cars allowed unitl a space is free"); //Send a message //System.out.println("Total Waiting customers: " + bouncedCustomers); } //} catch (Exception e) { //} //currentRuns += 1; ///Thread.join(5000); } } The array recived is of type ticketArray. How can I make this work please? Any enhancement recommendations are welcome |
I am .5 off when trying to figure this out Posted: 20 Jun 2022 06:54 PM PDT x = 1 / 2 + 3 // 3 + 4 ** 2 # Why is this equivalent to 17? y = 1 / 2 + 3 # This is equivalent to 3.5 z = 1 / 2 + 3 // 3 # This should be equivalent to 3.5 // 3 t = 3.5 // 3 + 4 ** 2 # Why is this 17 but the original statement is 17.5? Why are the expressions for t and x providing different results? Are they not equivalent? (Original image) |
How can I turn an array object into an object? Posted: 20 Jun 2022 06:53 PM PDT I want to put an array object called hello into a constant called answer. At this time, I want to change the key value of the answer to the value key of hello and the value of the answer to the label value of hello. how can i do that? i was thinking object entries but i couldn't do that.... is it possible?? this is my code const hello = [ { label: 'one', value: 'Tangerinefeed' }, { label: 'two', value: 'dryexamfeed' }, { label: 'three', value: 'wetfeed' }, { label: 'forth', value: 'sawdust' }, { label: 'five', value: 'etc' }, ] ; expected answer const answer = {Tangerinefeed: 'one', dryexamfeed: 'two', wetfeed: 'three', sawdust: 'forth', etc: 'five'} |
split dataframe rows according to ratios Posted: 20 Jun 2022 06:50 PM PDT I want to turn this dataframe | ID| values| |:--|:-----:| | 1 | 10 | | 2 | 20 | | 3 | 30 | into the below one by splitting the values according to the ratios 2:3:5 | ID| values| |:--|:-----:| | 1 | 2 | | 1 | 3 | | 1 | 5 | | 2 | 4 | | 2 | 6 | | 2 | 10 | | 3 | 6 | | 3 | 9 | | 3 | 15 | Is there any simple code/convenient way to do this? Thanks! |
How do I repopulate multiple textareas with their specific user input (saved as an array in localStorage) on refresh? Posted: 20 Jun 2022 06:54 PM PDT I'm building a scheduling web app, and it shows a table of rows with time of day, a text area, and a save button side by side for each hour of the day. The user can type their info into the textarea next to a given time, click the button, and it will save their input to localStorage. On refresh, the localStorage still shows the saved user input when I console.log it, but it won't repopulate the textareas with it. I want their user input to still show up in those textareas when they refresh the page, but something about how I'm using localStorage.getItem doesn't seem to be working. I'd love some help, and thank you! (Sorry in advance that the images are posting as links, it won't let me embed them) Here's an example of the HTML I have for each row of the table, which includes the textarea. This is my current JS for adding the user input to localStorage. And this is all I've got for my getItem function so far, which is what I need help fixing! |
Iterate through fields using array Django Posted: 20 Jun 2022 06:52 PM PDT I have this model: class Some_model(models.Model): field_1 = models.CharField(max_length=200, blank=True, null=True) field_2 = models.CharField(max_length=200, blank=True, null=True) and this function: # create a function to upload a model object given a json object def upload_object_values(model, json_values, keys=None): if json_values: # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object has keys to check if keys: # check if exists using the keys when called like this: upload_object_values(Some_model(), {'field_1': 'val', 'field_2': 'val_2'}, ['field_2']) It would do a get or create inside the upload_object_values function using the fields inside the keys parameter (e.g.: field_2 as the parameter). Some_model.objects.get_or_create(field_2='val_2') UPDATE: |
Hello, need help solving a issue in listbox c++ mfc Posted: 20 Jun 2022 06:53 PM PDT I'm still learning c++ mfc and my question is: how can I get the CurSel of 2 listbox as the number, then add them and print the result? the result displays a weird 659998896 number instead of 2. What have I done wrong here? BOOL CEngravingCalculatorDlg::OnInitDialog(){ CListBox* emplistbox1 = static_cast<CListBox*>(GetDlgItem(IDC_LIST1)); emplistbox1->AddString(L"1"); emplistbox1->SetCurSel(0); CListBox* emplistbox3 = static_cast<CListBox*>(GetDlgItem(IDC_LIST3)); emplistbox3->AddString(L"1"); emplistbox3->SetCurSel(0); } void CEngravingCalculatorDlg::OnBnClickedButton1() { CListBox* emplistbox1 = static_cast<CListBox*>(GetDlgItem(IDC_LIST1)); CListBox* emplistbox3 = static_cast<CListBox*>(GetDlgItem(IDC_LIST3)); int num1 = emplistbox1->GetCurSel(); int num2 = emplistbox3->GetCurSel(); int equal = num1 + num2; CString str; str.Format(_T("%d", equal)); GetDlgItem(IDC_Display)->SetWindowTextW(str); } |
Pass data from cloud task to a firebase cloud function - currently getting an error Posted: 20 Jun 2022 06:55 PM PDT My question is this: how do I call a Firebase Cloud Function from a Cloud task and pass a payload through? I tried following the tutorial here, but when I initialized my cloud function the starting syntax is different (I think he is using a regular cloud function). Here is my cloud function. const functions = require("firebase-functions"); exports.myFunction = functions.https.onRequest((req, res) => { console.log(req.query); //I've also tried console.log(req) and I'm having the same problem res.send('success'); }); When I query the url in the browser with parameters like ?myparams=data I can log the data var successfully. But when I try to call it from my queue (below) I get: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) I've been looking at this SO question and I am wondering if it has something to do with needing to use bodyParser for onRequest functions. HTTP Event Cloud Function: request body value is undefined Here is the task queue code. const seconds = 5; const project = 'spiral-productivity'; const queue = 'spiral'; const location = 'us-west2'; const url = 'https://us-central1-spiral-48266.cloudfunctions.net/writeDB'; const payload = 'My data'; const parent = client.queuePath(project, location, queue); const task = { httpRequest: { httpMethod: "POST", url: url, body: Buffer.from(JSON.stringify(payload)).toString("base64"), headers: { "Content-Type": "application/json" }, oidcToken: { serviceAccountEmail } } }; task.scheduleTime = { seconds: seconds + Date.now() / 1000, }; const request = {parent: parent, task: task}; await client.createTask(request) .then(response => { const task = response[0].name; console.log(`Created task ${task}`); return {'Response': String(response)} }) .catch(err => { console.error(`Error in createTask: ${err.message || err}`); next() }); It calls the function, but for some reason it results in the error. Can anyone help? As always, I'm happy to clarify the question if anything is unclear. Thanks! |
Share queue between processes Posted: 20 Jun 2022 06:50 PM PDT I am pretty new to multiprocessing in python and trying to achieve something which should be a rather common thing to do. But I cannot find an easy way when searching the web. I want to put data in a queue and then make this queue available to different consumer functions. Of course when getting an element from the queue, all consumer functions should get the same element. The following example should make clear what I want to achieve: from multiprocessing import Process, Queue def producer(q): for i in range(10): q.put(i) q.put(None) def consumer1(q): while True: data = q.get() if data is None: break print(data) def consumer2(q): while True: data = q.get() if data is None: break print(data) def main(): q = Queue() p1 = Process(target=producer, args=(q,)) p2 = Process(target=consumer1, args=(q,)) p3 = Process(target=consumer2, args=(q,)) p1.start() p2.start() p3.start() p1.join() p2.join() p3.join() if __name__ == '__main__': main() Since the script is not terminating and I only get the print output of one function I guess this is not the way to do it. I think sharing a queue implies some things to consider? It works fine when using only one consumer function. Appreciate the help! |
Buttons that start invisible (Binding to false property) don't fire command when made visible later Posted: 20 Jun 2022 06:53 PM PDT In my MainPage.xaml I have a CollectionView in a frame and three image buttons in a frame I'd like the first button to be visible and when I tap it it makes the other two buttons visible and tap again and make the other two buttons invisible. Seems pretty straightfoward and I can get it working IF they are all visible at first. If however the other two buttons start off invisible then the button will not respond. Aside: I also note that hot reload doesn't seem to work if changes made to the controls(views) inside a frame. I tried without the frames and no difference. Here's the code: MainPage.xaml <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Census.ViewModels" x:Class="Census.MainPage"> <Grid RowDefinitions="*, 65, 100" RowSpacing="10"> <Frame Grid.Row="0" CornerRadius="10" BorderColor="White" BackgroundColor="Black" Margin="0,0,0,0"> <CollectionView ItemsSource="{Binding FriendsOC}" SelectionMode="Single" SelectedItem="{Binding SelectedItem}" SelectionChangedCommand="{Binding SelectionChangedCommand}" SelectionChangedCommandParameter="{Binding .}" > <CollectionView.ItemTemplate> <DataTemplate> <Grid ColumnDefinitions="*, 200"> <Label Grid.Column="0" Text="{Binding FName}" FontSize="20" TextColor="Yellow" /> <Label Grid.Column="1" Text="{Binding LName}" FontSize="20" TextColor="Yellow" /> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </Frame> <Frame Grid.Row="1" CornerRadius="10" BorderColor="White" BackgroundColor="Black" HeightRequest="60" Margin="0,0,0,0" Padding="0,2,0,0"> <Grid ColumnDefinitions="*, *, *"> <ImageButton Grid.Column="0" Source="nullx.svg" BorderColor="Yellow" BorderWidth="2" WidthRequest="45" HeightRequest="45" Command="{Binding RevealCommand}"/> <ImageButton Grid.Column="1" Source="nullx.svg" BorderColor="Green" BorderWidth="2" WidthRequest="45" HeightRequest="45" IsVisible="{Binding ImportVisible}" Command="{Binding ImportFriendsCommand}"/> <ImageButton Grid.Column="2" Source="nullx.svg" BorderColor="Red" BorderWidth="2" WidthRequest="45" HeightRequest="45" IsVisible="{Binding DestroyVisible}" Command="{Binding DestroyCommand}"/> </Grid> </Frame> <Button Grid.Row="2" Text="Add" Command="{Binding AddFriendCommand}" WidthRequest="100" Margin="25,25,25,25"/> </Grid> </ContentPage> MainPage.xaml.cs namespace Census; public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); BindingContext = new CensusViewModel(); } protected override void OnAppearing() { base.OnAppearing(); //ImportVisible = false; <--things I tried to no avail //DestroyVisible = false; //FriendsList.ItemsSource = await App.Friends.GetFriendsAsync(); //because App.xaml.cs is where th db code is } } and the viewmodel namespace Census.ViewModels; public partial class CensusViewModel : ObservableObject { [ObservableProperty] public bool importVisible = true; [ObservableProperty] public bool destroyVisible = true; ... //Reveal Actions public ICommand RevealCommand => new Command(() => { Console.WriteLine("Reveal"); ImportVisible = !ImportVisible; DestroyVisible = !DestroyVisible; }); ... } This works fine but if I do [ObservableProperty] public bool importVisible = false; [ObservableProperty] public bool destroyVisible = false; It works in terms of hiding the two buttons, but does not respond if I tap the first button, except it does hit the code and change the properties. Now in my head I am thinking of a question I asked here .net Maui databinding to shell flyout item IsVisible property I've tried different variation on a theme but haven't been able to figure out what I could do. (Hence why I use the code binding in the codebehind as per the solution. Just seems so bizarre that it works when the properties start off true and works fine, but not when false. I've spent a good many hours on this by the way so I do try hard to figure it out myself. |
How to remove list of objects from another list of Objects by id and add removed object in another list Posted: 20 Jun 2022 06:52 PM PDT How can I remove list of objects (list1) comparing another list of Objects(list2) by id and add removed object from list1 into another list (list3) using java 8 Example : List<Employee> list1 = Stream.of( new Employee("100","Boston","Massachusetts"), new Employee("400","Atlanta","Georgia"), new Employee("300","pleasanton","California"), new Employee("200","Decatur","Texas"), new Employee("500","Cumming","Atlanta"), new Employee("98","sula","Maine"), new Employee("156","Duluth","Ohio")) .collect(Collectors.toList()); From the above list need to remove employee object based on id of below list. List<Employee> list2 = Stream.of( new Employee("100","Boston","Massachusetts"), new Employee("800","pleasanton","California"), new Employee("400","Atlanta","Georgia"), new Employee("10","Decatur","Texas"), new Employee("500","Cumming","Atlanta"), new Employee("50","sula","Maine"), new Employee("156","Duluth","Ohio")) .collect(Collectors.toList()); Expected Output : list1 and list3 List<Employee> list1 = Stream.of( new Employee("100","Boston","Massachusetts"), new Employee("400","Atlanta","Georgia"), new Employee("500","Cumming","Atlanta"), new Employee("156","Duluth","Ohio")) .collect(Collectors.toList()); List<Employee> list3 = Stream.of( new Employee("300","pleasanton","California"), new Employee("200","Decatur","Texas"), new Employee("98","sula","Maine") ) .collect(Collectors.toList()); Tried below way but not working as expected List<Employee> list3 = new ArrayList<>(); if(CollectionUtils.isNotEmpty(list1) && CollectionUtils.isNotEmpty(list2)){ list2.stream().forEachOrdered( l2 -> { Optional<Employee> nonMatch = list1.stream().filter(l1 -> !l1.getId().equalsIgnoreCase(l2.getId())).findAny(); if(nonMatch.isPresent()){ list3.add(nonMatch.get()); list1.removeIf(l1 -> l1.getId().equalsIgnoreCase(nonMatch.get().getId())); } }); } System.out.println(list1); System.out.println(list3); |
How to add user-agent value into subprocess.Popen in selenium v4.2 while using debug mode Posted: 20 Jun 2022 06:53 PM PDT mates! i've got some problem whilst i'm using Selenium 4.2 as debug mode I would like to switch selenium browser's user-agent value as random value so i created a random user-agent generator then tried to write the value from it into subprocess.Popen(~~~~~~~) but i had no luck, it wasn't work after this code runs, selenium browser's user-agent returns {user_agent} as string value and chrome_options.add_argument is also no working for subprocess.Popen(~~~~~~~), i cannot add any arguments into this(set add_argument in debug mode), does anyone knows how to solve this, please help me! thank you #switch user-agent from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import subprocess import user_agent_generator user_agent = (ex. generated_user_agent_value) #open chrome as debug mode subprocess.Popen([r'C:\Program Files\Google\Chrome\Application\chrome.exe', '--remote-debugging-port=9222', r'--user-data-dir="C:\chrometemp" ', '--user-agent = {}'.format(user_agent)]) chrome_options.add_argument('--user-agent = generated_user_agent_value') #not working driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()) , options=chrome_options) #navigator.user-agent returns {variable name} |
Get point geometries as rows for each vertex in SDO_GEOMETRY line Posted: 20 Jun 2022 06:53 PM PDT Oracle 18c: It's possible to get SDO_GEOMETRY line vertex ordinates as rows using the sdo_util.getvertices() function: with cte as ( select 100 as asset_id, sdo_geometry('linestring (10 20, 30 40)') shape from dual union all select 200 as asset_id, sdo_geometry('linestring (50 60, 70 80, 90 100)') shape from dual union all select 300 as asset_id, sdo_geometry('linestring (110 120, 130 140, 150 160, 170 180)') shape from dual) select cte.asset_id, id as vertex_id, v.x, v.y from cte, sdo_util.getvertices(shape) v ASSET_ID VERTEX_ID X Y ---------- ---------- ---------- ---------- 100 1 10 20 100 2 30 40 200 1 50 60 200 2 70 80 200 3 90 100 300 1 110 120 300 2 130 140 300 3 150 160 300 4 170 180 The resulting rows have columns with ordinates as numbers. I want to do something similar, but I want to get point geometries as rows for each vertex in the lines, instead of numbers. The result would look like this: ASSET_ID VERTEX_ID SHAPE ---------- ---------- ---------------- 100 1 [SDO_GEOMETRY] 100 2 [SDO_GEOMETRY] 200 1 [SDO_GEOMETRY] 200 2 [SDO_GEOMETRY] 200 3 [SDO_GEOMETRY] 300 1 [SDO_GEOMETRY] 300 2 [SDO_GEOMETRY] 300 3 [SDO_GEOMETRY] 300 4 [SDO_GEOMETRY] Idea: There is an undocumented function called SDO_UTIL.GET_COORDINATE(geometry, point_number) . (The name of that function seems misleading: it returns a point geometry, not a coordinate.) select cte.asset_id, sdo_util.get_coordinate(shape,1) as first_point from cte ASSET_ID FIRST_POINT ---------- --------------------- 100 [MDSYS.SDO_GEOMETRY] 200 [MDSYS.SDO_GEOMETRY] 300 [MDSYS.SDO_GEOMETRY] That function could be useful for getting vertices as point geometries. Question: Is there a way to get point geometries as rows for each vertex in the SDO_GEOMETRY lines? |
SQL advanced grouping & case statements , is this possible? Posted: 20 Jun 2022 06:52 PM PDT I have the following scenario System | Subsystem & Filename | File Load Start Time | File Load End Time | Alpha | A1 transactiontxt | 2022-06-19 08:00:00 | 2022-06-19 08:00:02 | Alpha | A2 userscsv | 2022-06-19 08:00:02 | 2022-06-19 08:00:05 | Alpha | A2 employeescsv | 2022-06-19 08:00:05 | 2022-06-19 08:00:08 | Alpha | A1 managerscsv | 2022-06-19 08:00:08 | 2022-06-19 08:00:16 | Alpha | A3 customerscsv | 2022-06-19 08:00:01 | 2022-06-19 08:00:04 | Gamma | A1 transactiontxt | 2022-06-19 10:00:48 | 2022-06-19 10:00:53 | Gamma | A2 userscsv | 2022-06-19 10:00:53 | 2022-06-19 10:00:54 | Gamma | A2 employeescsv | 2022-06-19 10:00:27 | 2022-06-19 10:00:30 | Gamma | A1 managerscsv | 2022-06-19 10:00:11 | 2022-06-19 10:00:17 | Gamma | A3 customerscsv | 2022-06-19 10:00:13 | 2022-06-19 10:00:14 | I want to be able to group the summary statistics by System. The info needed is when the overall started (earliest time), when it ended (latest time), and the time it took for each subsystem to occur, in seconds. From the example above, the result should look as below: System | Overall System Load Start Time | Overall System Load End Time | A1 Time Taken | A2 Time Taken | A3 Time Taken | Alpha | 2022-06-19 08:00:00 | 2022-06-19 08:00:16 | 00:00:10 | 00:00:06 | 00:00:03 | Gamma | 2022-06-19 10:00:11 | 2022-06-19 10:00:54 | 00:00:11 | 00:00:04 | 00:00:01 | I cannot find a way to do this in a query, I'm trying to do select subqueries in the select clause for each column, and at the end group by only System. But this is not possible because I'd have to use an aggregate function which is not being supported with case statements in subqueries in the select clause My approach was something like SELECT System, min(StartTime) as 'File Load Start Time', max(EndTime) as 'File Load End Time', CASE WHEN SubSystem LIKE 'A1%' THEN SUM(DATEDIFF(s, min(StartTime), max(EndTime))) Else 0 END AS 'A1 Time Taken', CASE WHEN SubSystem LIKE 'A2%' THEN SUM(DATEDIFF(s, min(StartTime), max(EndTime))) Else 0 END AS 'A2 Time Taken', CASE WHEN SubSystem LIKE 'A3%' THEN SUM(DATEDIFF(s, min(StartTime), max(EndTime))) Else 0 END AS 'A3 Time Taken' FROM TABLE GROUP BY SYSTEM But this does not work because the case statements need to be in a group by clause as well, and I cannot aggregate them |
Delphi 11 and WinAPI.WinSvc (function EnumServiceState) Posted: 20 Jun 2022 06:54 PM PDT I used the code below to get a list of Windows services. It works well for Delphi 10.2.3 and earlier: const // // Service Types // SERVICE_KERNEL_DRIVER = $00000001; SERVICE_FILE_SYSTEM_DRIVER = $00000002; SERVICE_ADAPTER = $00000004; SERVICE_RECOGNIZER_DRIVER = $00000008; SERVICE_DRIVER = (SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER or SERVICE_RECOGNIZER_DRIVER); SERVICE_WIN32_OWN_PROCESS = $00000010; SERVICE_WIN32_SHARE_PROCESS = $00000020; SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS); SERVICE_INTERACTIVE_PROCESS = $00000100; SERVICE_TYPE_ALL = (SERVICE_WIN32 or SERVICE_ADAPTER or SERVICE_DRIVER or SERVICE_INTERACTIVE_PROCESS); uses WinSvc; //------------------------------------- // Get a list of services // // return TRUE if successful // // sMachine: // machine name, ie: \SERVER // empty = local machine // // dwServiceType // SERVICE_WIN32, // SERVICE_DRIVER or // SERVICE_TYPE_ALL // // dwServiceState // SERVICE_ACTIVE, // SERVICE_INACTIVE or // SERVICE_STATE_ALL // // slServicesList // TStrings variable to storage // function ServiceGetList( sMachine : string; dwServiceType, dwServiceState : DWord; slServicesList : TStrings ) : boolean; const // // assume that the total number of // services is less than 4096. // increase if necessary cnMaxServices = 4096; type TSvcA = array[0..cnMaxServices] of TEnumServiceStatus; PSvcA = ^TSvcA; var // // temp. use j : integer; // // service control // manager handle schm : SC_Handle; // // bytes needed for the // next buffer, if any nBytesNeeded, // // number of services nServices, // // pointer to the // next unread service entry nResumeHandle : DWord; // // service status array ssa : PSvcA; begin Result := false; // connect to the service // control manager schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_ALL_ACCESS); // if successful... if(schm > 0)then begin nResumeHandle := 0; New(ssa); EnumServicesStatus( schm, dwServiceType, dwServiceState, ssa^[0], SizeOf(ssa^), nBytesNeeded, nServices, nResumeHandle ); // // assume that our initial array // was large enough to hold all // entries. add code to enumerate // if necessary. // for j := 0 to nServices-1 do begin slServicesList. Add( StrPas( ssa^[j].lpDisplayName ) ); end; Result := true; Dispose(ssa); // close service control // manager handle CloseServiceHandle(schm); end; end; To get a list of all Windows services into a ListBox named ListBox1 : ServiceGetList( '', SERVICE_WIN32, SERVICE_STATE_ALL, ListBox1.Items ); I tried to use the same code in Delphi 10.4 and Delphi 11, but there is a problem with the EnumServicesStatus function: [dcc32 Error] Unit1.pas(145): E2010 Incompatible types: 'LPENUM_SERVICE_STATUSW' and '_ENUM_SERVICE_STATUSW' When I tried LPENUM_SERVICE_STATUSW instead TEnumServiceStatus : type TSvcA = array[0..cnMaxServices] of LPENUM_SERVICE_STATUSW;// instead TEnumServiceStatus; I got an 'access violation' error. Maybe the point is in the external function in Winapi.WinSvc.pas : function EnumServicesStatus; external advapi32 name 'EnumServicesStatusW'; |
Convert SQL to JPQL Spring boot Posted: 20 Jun 2022 06:52 PM PDT I'm wondering how to convert this query to JPQL: SELECT t.id, t.title , (select count(l.id) from topic_like l where t.id = l.topic_id) as countt from topics t; |
How would I make a UiPanGestureRecognizer check if the finger is in the buttons frame? Posted: 20 Jun 2022 06:54 PM PDT I am trying to make an app where the user could drag a finger on top of multiple buttons and get some actions for each button. There was a similar question from a while back but when I tried to use CGRectContainsPoint(button.frame, point) it said it was replaced with button.frame.contains(point) but this didn't seem to work for me. Here is a link to the Photo What I have done so far: var buttonArray:NSMutableArray! override func viewDidLoad() { super.viewDidLoad() let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureMethod(_:))) a1.addGestureRecognizer(panGesture) a2.addGestureRecognizer(panGesture) } @objc func panGestureMethod(_ gesture: UIPanGestureRecognizer) { if gesture.state == UIGestureRecognizer.State.began { buttonArray = NSMutableArray() } let pointInView = gesture.location(in: gesture.view) if !buttonArray.contains(a1!) && a1.frame.contains(pointInView) { buttonArray.add(a1!) a1Tapped(a1) } else if !buttonArray.contains(a2!) && a2.frame.contains(pointInView) { buttonArray.add(a2!) a2Tapped(a2) } The code did run fine but when I tried to activate the drag nothing happened. Any tips? |
"AUTH-010 Access token provided is invalid or expired". How to solve this error? Posted: 20 Jun 2022 06:50 PM PDT SOLVED: I figured it out, but hopefully this will help someone else. I was using the wrong URL to get the 2-legged token. "/authentication/v1/authenticate" gets the 2-legged token, "/authentication/v1/gettoken" gets the 3-legged token. Some API calls require a 2-legged token, and some require a 3-legged token (and some will take either). It is not always obvious what is required. Original question: I have four (essentially identical) Forge apps, but each with a separate callback server, (which I am using identically). Unfortunately, one of the four generates the above error. My code is identical for all four, as are the users/projects (I am testing the same BIM 360 project & members via each server). All four Apps have "BIM 360 Account Administration" (BIM360 API) and "Document Management" (Document Management API) access. All four seem to work perfectly for generating the 2- and 3-legged OAuth tokens (2LT/3LT), and making the initial call to Get Hubs (Data Management API) using the 3LT. From there, three apps succeed in making all of my other calls; however the fourth server (Production, of course) fails immediately on the next call to Get Projects (hq/v1/accounts/:account_id/projects, BIM360 API), with the above error. The call is immediate, so it can't have expired; nor can I understand how it is invalid. I have run into this same error several times in the last few months; but I can't recall a specific fix. Code is the same; member access is the same (because it's the same member); 3LT OAuth is clearly working because I am able to make the Hubs call; I've never had any trouble before with the 2LT, but I can't verify that it's still good in this case. Troubleshooting on the server is going to be a challenge. Any suggestions would be highly appreciated. Thanks! |
No comments:
Post a Comment