how to write a Trigger to insert data from aurora to redshift Posted: 01 Feb 2022 09:49 AM PST I am having some data inn aurora mysql db, I would like to do two things: HISTORICAL DATA: - To read the data from aurora(say TABLE A) do some processing and update some columns of a table in redshift(say TABLE B).
ALSO, LATEST DAILY LOAD 2. To have a trigger like condition where whenever a new row is inserted in aurora table A then a trigger should update the columns in redshift table B with some processing. what should be the best approach to handle such situation. Please understand I don't have a simple read ans insert situation , I also have to perform some process as well between read and write. |
What purpose does a queue serve in System Verilog? Posted: 01 Feb 2022 09:49 AM PST They are not used for RTL but rather verification, correct? They would not be synthesizable. Do they have better memory management features in turn optimizing program time? If I recall correctly, System Verilog has an automatic garbage collector, so there is no need to deallocate memory. The official IEEE documentation does a great job of explaining how they work. I am just wondering in what scenarios I would use one vs an array. One guess would be that they have associated methods that allow for easier data manipulation? Thank you in advance for your knowledge and expertise. |
Pandas puts unevenly spaced indexes in barplot from 3 nested dictionaries Posted: 01 Feb 2022 09:49 AM PST I have a df like this (this is just the final part, cause it's big): THR 500 -0.836377 NaN NaN THR 500 NaN -0.477983 NaN THR 500 NaN NaN -1.829530 ASN 501 -3.644400 NaN NaN TYR 501 NaN NaN -4.616558 ASN 501 NaN -3.643328 NaN GLY 502 -0.857395 NaN NaN GLY 502 NaN -0.829729 NaN GLY 502 NaN NaN -0.580206 VAL 503 NaN NaN -0.651733 VAL 503 -0.713642 NaN NaN VAL 503 NaN -0.690845 NaN TYR 505 -1.912762 NaN NaN TYR 505 NaN -1.738743 NaN HIS 505 NaN NaN -1.251550 which is plotted with this small function: def plot_lig(): df = pd.DataFrame.from_dict(lig_dec_residue['s1']) df2 = pd.DataFrame.from_dict(lig_dec_residue['s2']) df3 = pd.DataFrame.from_dict(lig_dec_residue['s3']) concat = pd.concat([df, df2, df3]) concat = concat[concat <= -0.25] concat = concat.sort_index(key=lambda x: x.str.split().str[1].str.zfill(5)) concat.dropna(how='all', inplace=True) concat.plot(kind='bar', edgecolor='black', width=1) print(concat) plt.legend(['X var', 'Y var', 'Z var']) plt.show() plt.close() output: You can see how the spaces between indexes above look weird. I assume there's something wrong with the .sort_index as if i remove that line the plot seems just fine but the index are "separated" per dataframe: I have tried with sorting the individual dfs, sorting the concatenation of the dfs, but there's surely something I am missing. I need to have each line plotted (so no merging) to make a comparison and it would be good to have them grouped by the number (or individually if they are unique). Thank you! Ludovico |
Logic after tkinter object does not get executed in a class Posted: 01 Feb 2022 09:49 AM PST I have this script where I initialize a tkinter object with some labels, entries, and buttons with commands. when I run the script, the init function executes fine and the instance of the tkinter window gets spawned and the buttons work just fine. The problem is that, the logic after the init function does not get executed and the tkinter window stays looping for ever unless I hit the exit button and then it just finishes the script. I want to be able to use the inputs from the tkinter.Entry() and the tkinter.filedialog.askopenfilename() functions to do more stuff later in the application such as loading an excel sheet based on the path passed on the askopenfilename() sections but I can't get it to continue. Note: I am new to using classes so I believe my mistake is somewhere in the way I am laying down the building blocks of the instance itself. Also, while putting this scrip together so many other questions arised and it has been very hard to find concise answers online. I will post some of those questions here in case someone wants to answer them (not needed though) 1- Do I need to declare every single new variable that come in new methods of the class in the init function, if so, why? I just did it here because pycharm game me warning every time I did not do it but not sure what is the reason behind it. 2- When calling a variable on a new method within the class, and the variable is already defined in the init fucntion, do I need to include the variable in the arguments section of the method? if so, do I add the value with the self argument or not? import pandas as pd from openpyxl import load_workbook import tkinter as tk from tkinter import ttk from tkinter import filedialog from tkinter.messagebox import showinfo from datetime import datetime import openpyxl # The class App is inheriting from the superclass tkinter (tk) by using the super() method # By using the super() method I can use the methods of the tkinter class in the app class class App(tk.Tk): def __init__(self): super().__init__() # Define global parameters self.current_PR_report = "" self.new_PR_report = "" self.path = "" self.raw_excel = None self.new_report = None self.current_report = "" self.writer = "" self.data = "" self.data2 = "" self.final_report = None # Configure the root window self.title("PR Reader") self.geometry('250x200') # Label self.label = ttk.Label(self, text="Merge Problem Reports!") self.label.pack() # Severity Label and Entry self.severity_label = tk.Label(self, text="Severity Level") self.severity_label.pack() self.severity_label_entry = tk.Entry(self) self.severity_label_entry.pack() # Date Label and Entry self.date_label = tk.Label(self, text="Enter Date (MM-DD-YYYY)") self.date_label.pack() self.date_label_entry = tk.Entry(self) self.date_label_entry.pack() # Run button self.button = ttk.Button(self, text="Run", command=self.select_file) self.button.pack() # Button for closing self.exit_button = tk.Button(self, text="Exit", command=self.destroy) self.exit_button.pack(pady=20) # Bring Dialog box to obtain Excel files paths def select_file(self): self.current_PR_report = filedialog.askopenfilename( title="Select Current PR Report", initialdir="some path", filetypes=[("Excel Files", "*.xlsx")]) showinfo(title="Selected File", message=self.current_PR_report) self.new_PR_report = filedialog.askopenfilename( title="Select New PR Report", initialdir="some path", filetypes=[("Excel Files", "*.xlsx")]) showinfo( title="Selected File", message=self.new_PR_report) # Load the spreadsheets self.new_report = self.read_excel_report(self.new_PR_report) self.current_report = self.read_excel_report(self.current_PR_report) # Load the new data into a new sheet in the workbook def load_new_data(self): # Create a Pandas Excel writer using XlsxWriter as the engine. self.writer = pd.ExcelWriter(self.current_PR_report, engine='openpyxl') # Load, save and close the file self.new_report.to_excel(self.writer, sheet_name=self.date_label_entry, index=False) self.writer.save() self.writer.close() # Clean the data self.data = self.clean_data(self.new_report) self.data2 = self.clean_data(self.current_report) self.final_report = self.compare_reports(self.data, self.data2) # Define function to load Excel data def read_excel_report(self, path): try: # sheet_name=None indicates you want a dictionary of data frames, each item in the dictionary # representing a different worksheet. self.raw_excel = pd.read_excel(path, sheet_name=-1, engine='openpyxl') self.raw_excel = self.raw_excel.fillna('') print("data extracted") return self.raw_excel except Exception as e: print(e) |
variable passed to DriverManager.getConnection() not working Posted: 01 Feb 2022 09:48 AM PST I am trying to connect to MySQL using JDBC. I have one strange behavior if I passed the hardcode value for url, username and password to DriverManager.getConnection() the connection to database is OK. But if I passed argument as variable the connection to JDBC failed with below Error. java.sql.SQLException: No suitable driver found for "jdbc:mysql://localhost:3306/hplus" FileInputStream fis = new FileInputStream(path+"config.properties"); Properties prop = new Properties(); prop.load(fis); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println(url); System.out.println(username); System.out.println(password); conn=DriverManager.getConnection(url, username, password); //conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/hplus","root","123Nbr@");; }catch(Exception e) { System.out.println(e); } Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. "jdbc:mysql://localhost:3306/hplus" "root" "123Nbr@" java.sql.SQLException: No suitable driver found for "jdbc:mysql://localhost:3306/hplus" |
Why does a Xamarin.Forms border draw on top of its contents in iOS, but below its contents in Android Posted: 01 Feb 2022 09:48 AM PST Summary If the contents of a Frame spill over the edge and if the frame has a border, the frame's border draw on top of the contents on iOS, but below the contents on Android. Is it possible to make the iOS border draw below the contents? Details I suspect this may be a bug in Xamarin.Forms, or maybe even the expected behavior on iOS, but nonetheless it is causing problems in my application visuals so I'd like to fix it if possible. The following code reproduces the problem: var frameInstance = new Frame(); var grid = new Grid(); AbsoluteLayout.SetLayoutBounds(frameInstance, new Rectangle(58f, 103f, 222f, 304f)); AbsoluteLayout.SetLayoutFlags(frameInstance, AbsoluteLayoutFlags.None); frameInstance.WidthRequest = 222f; frameInstance.HeightRequest = 304f; frameInstance.IsClippedToBounds = false; frameInstance.HasShadow = false; frameInstance.CornerRadius = 10; frameInstance.BorderColor = Color.Gray; absoluteLayout.Children.Add(frameInstance); grid.HeightRequest = 42f; grid.Margin = new Thickness(-32, -32, 0, 0); grid.HorizontalOptions = LayoutOptions.Fill; grid.VerticalOptions = LayoutOptions.Start; grid.BackgroundColor = Color.Red; frameInstance.Content = grid; Notice that the frame is hosted in an AbsoluteLayout, but this is not necessary, it can be hosted in any top-level layout object in the page. The important thing is that the frame is offset from the top-left of the page so the contents of the frame can spill over and be seen clearly. When running On iOS, the code above produces the following image: If the code is run on Android, it produces the following image: Is it possible to somehow suppress the rendering of the iOS frame on top of the contents? perhaps through a renderer? The reason I need to solve this is because my app's login page has an icon which sits halfway over a frame, as shown in the following image (on iOS): |
Script (e) get active spreadsheet suddenly stopped working Posted: 01 Feb 2022 09:48 AM PST Here's the script I have that was working and has been working for months until now. function onformsubmit(e){ var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = e.source.getActiveSheet(); var activeRange = e.source.getActiveRange(); var sortRange = sheet.getRange(2,1,sheet.getLastRow(),sheet.getLastColumn()); if(sheet.getName() == "Shopping List" && (activeRange.getColumn() == 6 || activeRange.getColumn() == 11) && activeRange.getValue() !== "SpartanNash"){ sortRange.sort([{column: 11, Decending: true },{column: 6, Decending: false }]); } else if(sheet.getName() == "SpartanNash" && activeRange.getColumn() == 11){ sortRange.sort({column: 11, Decending: false }); } else if(sheet.getName() == "Shopping List" && activeRange.getColumn() == 6 && activeRange.getValue() === "SpartanNash") { var activeRow = activeRange.getRow(); var spartanNashSheet = spreadsheet.getSheetByName("SpartanNash"); var spartanNashRange = spartanNashSheet.getRange(spartanNashSheet.getLastRow() + 1, 1); sheet.getRange(activeRow, 1, 1, 11).copyTo(spartanNashRange); sheet.deleteRow(activeRow); } } function switchList(e){ var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var activeRange = e.range; var sheet = activeRange.getSheet(); var store = e.values[5]; if(sheet.getName() == "Shopping List" && store == "SpartanNash") { var activeRow = activeRange.getRow(); var spartanNashSheet = spreadsheet.getSheetByName("SpartanNash"); var spartanNashRange = spartanNashSheet.getRange(spartanNashSheet.getLastRow() + 1, 1); sheet.getRange(activeRow, 1, 1, 11).copyTo(spartanNashRange); sheet.deleteRow(activeRow); } } This is the error message I'm getting: 11:43:16 AM Notice Execution started 11:43:16 AM Error TypeError: Cannot read property 'source' of undefined onformsubmit @ Code.gs:3 Please help me figure out why it's not working and what I need to change. |
What permissions should I have on directories for a systemd .service file to run? Posted: 01 Feb 2022 09:48 AM PST I have a belmarket.service file located at /etc/systemd/system that when I invoke as "sudo systemctl start belmarket.service" throws an error: belmarket.service: Changing to the requested working directory failed: Permission denied belmarket.service: Failed at step CHDIR spawning /root/env/bin/gunicorn: Permission denied belmarket.service: Main process exited, code=exited, status=200/CHDIR belmarket.service: Failed with result 'exit-code'. Failed to start gunicorn daemon. Apparently, changing permissions to 777 recursively on /root/ fixes that issue, but that's so unprofessional and was used as a last resort tactic. The question is what exact permissions do I need to specify for the user that a .service file runs on? I realise it might depend on its contents, but still. Running on Ubuntu 20.04. .service file as follows: [Unit] Description=gunicorn daemon [Service] Type=simple User=root Group=root PIDFile=/root/website/gunicorn.pid EnvironmentFile=/root/conf/gunicorn.env WorkingDirectory=/root/website ExecStart=/root/env/bin/gunicorn --config /root/conf/gunicorn_config.py belmarket.wsgi ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID |
Where should I use OnClickListner in firebase adapter? Posted: 01 Feb 2022 09:48 AM PST I am retriewing data from firebase real time database and upon clicking a new activity will be opened which will show Name, blood group and other information of the users. I want to know where should I have an OnClickListner in my recyclerview i.e. ViewHolder class or in OnBindViewHolder (Adapter). What are the pros and cons of both. Below is my code Thank You all Adapter public class personAdapter extends FirebaseRecyclerAdapter< person, personAdapter.personsViewholder> { public personAdapter( @NonNull FirebaseRecyclerOptions<person> options) { super(options); } @Override protected void onBindViewHolder(@NonNull personsViewholder holder, int position, @NonNull person model) { holder.firstname.setText(model.getFirstname()); holder.bloodgroup.setText(model.getBloodgroup()); holder.phone.setText(model.getPhone()); } @NonNull @Override public personsViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.person, parent, false); return new personsViewholder(view); } static class personsViewholder extends RecyclerView.ViewHolder { TextView firstname, bloodgroup, phone; public personsViewholder(@NonNull View itemView) { super(itemView); firstname = itemView.findViewById(R.id.firstname); bloodgroup = itemView.findViewById(R.id.bloodGroup); phone = itemView.findViewById(R.id.phoneNumber); } } } Model public class person { private String firstname; private String phone; private String bloodgroup; public person(String firstname, String phone, String bloodgroup) { this.firstname = firstname; this.phone = phone; this.bloodgroup = bloodgroup; } public person() {} public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getBloodgroup() { return bloodgroup; } public void setBloodgroup(String bloodgroup) { this.bloodgroup = bloodgroup; } |
How to calculate days between two dates only if they belong to a certain month Posted: 01 Feb 2022 09:48 AM PST For example the date range is 28-01-2022 and 20-03-2022 I want to count separately the days that belong to january (3) february (27) and march (19) I would really appreciate the help!! |
How to pass column name as an arguments in the function Posted: 01 Feb 2022 09:48 AM PST I am trying to convert ggplot code which is repetitive into function i have done almost but only concern is i need to pass the application as a variable Here is the plot code where i used column called Application inside the summarise and mutate. The challenge is same column has been used for y axis ggplot_common_function <- function(data,x,y,z){ Removestring(ggplotly( data %>% group_by(m_year,status) %>% summarise(Applications = sum(Applications)) %>% mutate(total_sum = sum(Applications))%>% ggplot(mapping = aes({{x}},{{y}},text = paste(total_sum))) + geom_col(aes(fill = {{z}}))+theme_classic()+ theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom")+ labs(x="", y="Agreements Values (In Lakhs)", fill="")+ theme(axis.title.y =element_text(size=8))+ scale_fill_manual(values=c("#1F7A3F","#70B821"))+ scale_y_continuous(labels = function(x) format(x, scientific = FALSE),expand = expansion(mult = c(0,.3)),breaks = integer_breaks()),tooltip = c("text"))%>% layout(legend = list(orientation = "h", x = 0.1, y = -0.2,font=list( family='Arial', size=10, color='black')),xaxis = x_labels,yaxis = y_labels)%>% config(displaylogo = FALSE,modeBarButtonsToRemove = list('sendDataToCloud', 'autoScale2d', 'resetScale2d', 'toggleSpikelines','hoverClosestCartesian', 'hoverCompareCartesian','zoom2d','pan2d','select2d','lasso2d','zoomIn2d','zoomOut2d'))) } ggplot_common_function(data,m_year,Applications,status) To run the above code there is some pre function integer_breaks <- function(n = 5, ...) { fxn <- function(x) { breaks <- floor(pretty(x, n, ...)) names(breaks) <- attr(breaks, "labels") breaks } return(fxn) } Removestring = function(d){ for (i in 1:length(d$x$data)){ if (!is.null(d$x$data[[i]]$name)){ d$x$data[[i]]$name = gsub("\\(","",str_split(d$x$data[[i]]$name,",")[[1]][1]) } } return(d) } Plan <- "#288D55" multicolor = c("#135391","#0098DB","#828388","#231F20","#C41330","#698714","#162FBF","#F36717","#BD00FF") x_labels = list(tickangle = -45,tickfont = list(family = "Arial",size = 10,color = "black",face="bold")) y_labels = list(tickfont = list(family = "Arial",size = 10,color = "black",face="bold")) structure(list(Month = structure(c(5L, 5L, 5L, 5L, 7L, 7L, 6L, 6L, 6L, 6L), .Label = c("Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar"), class = "factor"), m_year = structure(c(1L, 1L, 1L, 1L, 3L, 3L, 2L, 2L, 2L, 2L), .Label = c("Aug-2021", "Sep-2021", "Oct-2021"), class = "factor"), Applications = c(182, 121, 115, 187, 0, 0, 18, 15, 15, 28 ), status = c("Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open")), row.names = c(NA, -10L), class = "data.frame") Any suggestions would be appreciated |
Convert object field to date and the also the display format of the date Posted: 01 Feb 2022 09:49 AM PST I Have a Dataframe with 2 columns Object like that: id object date object +------+-----------------+ | ID | DATE | +------+-----------------+ | 1 01/10/2000 | | 2 09/03/2005 | | 3 1 January 2020 | | 4 "21/08/1995" | | 5 27 April 2020 | +------------------------+ I would like to convert the dates in the same format dd/mm/yyyy I tried to use df["DATE"] = pd.to_datetime(df["DATE"]) and this df['DATE'].astype("datetime") But i got this errpr : TypeError: data type 'datetime' not understood Can you help me please ? |
Problem with getting data using Quandl in RStudio Server Pro Posted: 01 Feb 2022 09:48 AM PST When I try to get data from NASDAQ using the Quandl package in R Studio Server Pro, I'm getting the following error: Error in curl::curl_fetch_memory(url, handle = handle) : Peer's certificate issuer has been marked as not trusted by the user. Has anyone who used Quandl in R Studio Server Pro ever seen this issue before? How were you able to resolve the problem? Here is the code I'm using to retrieve the data: Quandl.api_key("API KEY") silver <- Quandl::Quandl("LBMA/SILVER", collapse = "monthly", start_date =Sys.Date() - lubridate::years(2),end_date = Sys.Date(), type = "ts") This code works on my local machine but when I use R Studio Server Pro I get the error above. |
Trying to copy all column names from one table and put it into another column in a second table Posted: 01 Feb 2022 09:49 AM PST I'm trying to copy all column names from one table and put it into a 'Field_Names' column in another table. I'm having trouble doing that because I get an error saying Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. My code is below: INSERT INTO TempData.Fields(Field_Names) SELECT Field_Names = (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE Table_Name ='AddressData_NY' AND Table_Schema ='RawData') I know what the issue is, but I'm having some trouble rectifying it. Is there a way I can insert all column names as a list into that one 'Field_Names' column? I can do it in Python by looping over the column names and appending that to the 'Field_Names' column, but I'm trying to find a way to do that using SSMS, if possible. Any help is appreciated - thanks in advance! |
sending while loop radio button data to database using php Posted: 01 Feb 2022 09:49 AM PST The first two values of the radio are not being inserted, is there any problem with the condition in for loop? I have the html code(form) and the php code on the bottom <?php $i=1; $name=$data['username']; $sql1 = "SELECT * from membre where groupe='$name'"; $run1 = mysqli_query($db,$sql1); while($row = mysqli_fetch_assoc($run1)){ ?> <tr> <td> <?php echo $i; $i++; ?></td> <td style="display: none;" ><input value="<?php echo $i; ?>" name="id[]" class="form-control" readonly="readonly" > </td> <td ><input value="<?= $row['nom']; ?>" name="nom1[]" class="form-control" readonly="readonly" > </td> <td><input type="radio" name="presence[<?php echo $i; ?>]" value="Présent"></td> <td><input type="radio" name="presence[<?php echo $i; ?>]" value="Absent"></td> </tr> <?php } ?> for($i=0; $i<$_POST['id'][$i]; $i++) { $id = mysqli_real_escape_string($db,trim($_POST['id'][$i])); $nom1= mysqli_real_escape_string($db,trim($_POST['nom1'][$i])); $presence= mysqli_real_escape_string($db,trim($_POST['presence'][$i])); $v1 = "INSERT INTO presence(rapport_id,groupe,dat,nom,presence) values('$rapport_id','$groupe','$dat','$nom1','$presence')"; $r = mysqli_query($db,$v1); |
SaveData is not output and instanceRef null Posted: 01 Feb 2022 09:48 AM PST I have a problem with react-editor-js library. I'm trying to get data from it, but it doesn't output and when I check instanceRef it's null. Here is the code. const Create = () => { const instanceRef = React.useRef(null); let data = { '1': 'test' } async function handleSave() { const savedData = await instanceRef.current.save() console.log(savedData) } return ( <div> <Header Name='Создание'/> <Menu/> <div className="editor"> <ReactEditorJS instanceRef={(instance) => (instanceRef.current = instance)} tools={EDITOR_JS_TOOLS} data={data} onChange={() => handleSave} /> </div> </div> ); }; Thanks for your help! Update: If I use onChage={() => handleSave} I get this error. Uncaught (in promise) TypeError: Cannot read properties of null (reading 'save') |
One-sided one sample T test by group on data frame? Posted: 01 Feb 2022 09:48 AM PST I am trying to perform a one-sided, one sample T test by group on a pandas data frame in python. I feel like I am so close, but I just can't close the last bit. I was trying to follow something similar to these questions (One Sided One Sample T Test Python and T-test for groups within a Pandas dataframe for a unique id). Say for example I have a data frame df df = pd.DataFrame({'ID': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'], 'value': [0.200, 0.201, 0.189, 0.199, 0.205, 0.220, 0.225, 0.209, 0.218, 0.230, 0.308, 0.291, 0.340, 0.444, 0.275]}) and I wanted to generate a new data frame df_pval with just two columns: the 'ID' and p-value from a one-sided, one sample T test. I could do this in R like so: library(dplyr) df_pval <- df %>% group_by(ID) %>% summarise(res = list(t.test(value, mu = 0.220, alternative = 'greater'))) df_pval <- data.frame(ID = df_pval$ID, pval = sapply(df_pval$res, function(x) x[['p.value']])) In fact, right now I use os to run an external R script to perform this action, but I know it must be possible just in python. I have tried creating a 'groupby' object and then running .apply : df_groupID = df.groupby('ID').agg({'value': list}) df_groupID.apply(lambda x: stats.ttest_1samp(x['value'], 0.220)) but this doesn't work. As of now I'm stuck. Any help on this issue would be greatly appreciated. Thank you in advance and sorry if this has already been answered before (and I just didn't understand the solution). |
Permanent Redirect of a variable URL Posted: 01 Feb 2022 09:48 AM PST I'm having troubles with my .htaccess permanent redirection code which is not working: RedirectPermanent ^shop/?attro-attributes=([0-9]*) http://www.second-website.example I would like to redirect URLs from first-website: first-website.example/shop/?attro-attributes=01 first-website.example/shop/?attro-attributes=02 first-website.example/shop/?attro-attributes=... first-website.example/shop/?attro-attributes=9999 to second-website URL: http://www.second-website.example/ |
Need VBA code snippet for selenium to click on a web page element Posted: 01 Feb 2022 09:49 AM PST I previously used the following code snippet to click on a selector button in a web page that was opened in internet explorer. ''' Set inputSelector = HTMLDoc.getElementsByClassName("idp") '<== the collection of input tags on the page For Each MyHTML_Element In inputSelector If MyHTML_Element.className = "idp" Then MyHTML_Element.Click: Exit For End If Next I need to click the same button in Selenium and I tried using Set inputBoxes = htmlDoc.FindElementByCss("idp").Text which generates a compiler error that the object doesn't support this property or method. Other than my effort to find the class and the for loop below, the rest of the code works. I need help replacing the IE code snippet above with code that works with Selenium. Public Sub Sample() Dim pid As Long Dim pno As Long: pno = 17556 Dim htmlDoc As WebDriver 'Create Selenium htmlDoc, Verify MS Edge Webdriver and continue Set htmlDoc = CreateObject("Selenium.WebDriver") pid = StartEdgeDriver(PortNo:=pno) If pid = 0 Then Exit Sub 'Specify URL, create Selenium html document and open webpage sLoginURL = "https://empowercentral.ussco.com/" htmlDoc.StartRemotely "http://localhost:" & pno & "/", "MicrosoftEdge" htmlDoc.Get sLoginURL Set inputBoxes = htmlDoc.FindElementByCss("idp").Text For Each MyHTML_Element In inputSelector If MyHTML_Element.className = "idp" Then MyHTML_Element.Click: Exit For End If Next htmlDoc.FindElementById("userNameInput").SendKeys "username" htmlDoc.FindElementById("nextButton").Click htmlDoc.FindElementById("passwordInput").SendKeys "password" htmlDoc.FindElementById("submitButton").Click End Sub What should I use if I want FindElementByCss to return a collection? I'm new to Selenium and I copied the .text from an example on the web. What should I use if I want FindElementByCss to return a collection? |
Reading doc with nested dictionary inside array and returning value Posted: 01 Feb 2022 09:49 AM PST This is my .txt file {'word1': {'doc1': 2}} {'word2': {'doc2': 5}} {'word3': {'doc3': 4}} {'word4': {'doc4': 2}} {'word5': {'doc5': 1}} The .txt file means: { word : {doc in which word appears : position on that doc} } What I want to do is to read the text file and give me the position of a specific word on that doc. An example of what I was trying to do: def search(word, doc): with open('extras/file.txt', 'r') as fp: for line in fp: if word and doc in line: print(word, "|", doc, "|", line) search("word2", "doc2") In this example I want the retrieve the "5", but I don't know on how to access the position. Any tips? |
Is there a VBA code that check and moves values from A column to the beginning of B column? Posted: 01 Feb 2022 09:48 AM PST I found a lot of formulas on the Internet which copies "n characters" but they did not provide a solution for me. I am searching for a VBA code which is able to move the specific value from a column to the beginning of adjacent column. For example, the VBA code will check the A column for the word "Warm" and "Cold", and if they are available, it will move them as shown in the example. Thank you in advance for your help. Example Edit ( Solution by @Dominique ): =IF(A1<>"";IF(RIGHT(A1;4)="Warm";"Warm "&B1;B1)) |
Flutter: Invalid value: Only valid value is 0: 1 Posted: 01 Feb 2022 09:48 AM PST am very new at flutter. I try to read JSON files local. it still has a bug that I do not understand. it seems like itemCount: data.length is not working for some reason. and I'm not sure that is because of this or not and I get the error like Another exception was thrown: RangeError (index): Invalid value: Only valid value is 0: 1 And this is my code import 'dart:convert'; import 'package:salomon_bottom_bar/salomon_bottom_bar.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Room management', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Room management'), debugShowCheckedModeBanner: false, ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { var _currentIndex = 0; @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[400], title: Text(widget.title, style: TextStyle( fontSize: 32, )), toolbarHeight: 70, centerTitle: true, ), body: Container( padding: const EdgeInsets.all(15), child: ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), child: FutureBuilder( builder: (context, snapshot) { var data = json.decode(snapshot.data.toString()); return ListView.builder( itemBuilder: (BuildContext context, int index) { return RoomCard(data[index]['roomNum'], data[index]['peopleNum'], data[index]['price']); }, itemCount: data.length, ); }, future: DefaultAssetBundle.of(context) .loadString('assets/data.json'), ), )), bottomNavigationBar: SalomonBottomBar( currentIndex: _currentIndex, onTap: (i) => setState(() => _currentIndex = i), items: [ /// Home SalomonBottomBarItem( icon: Icon(Icons.home), title: Text("Home"), selectedColor: Colors.deepPurple[400], ), /// Likes SalomonBottomBarItem( icon: Icon(Icons.favorite_border), title: Text("Likes"), selectedColor: Colors.pink, ), /// Search SalomonBottomBarItem( icon: Icon(Icons.search), title: Text("Search"), selectedColor: Colors.orange, ), /// Profile SalomonBottomBarItem( icon: Icon(Icons.person), title: Text("Profile"), selectedColor: Colors.teal, ), ], ), ), ); } } Widget RoomCard(String roomNum, String peopleNum, String price) { return Container( margin: EdgeInsets.only(top: 8), padding: EdgeInsets.fromLTRB(8, 8, 8, 8), height: 91, child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.2), spreadRadius: 1, blurRadius: 10, // offset: Offset(0, 3), // changes position of shadow ), ], ), padding: EdgeInsets.fromLTRB(16, 4, 16, 4), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Room", style: TextStyle( fontFamily: 'WorkSans', fontSize: 16, color: Colors.deepPurple[400])), Text(roomNum, style: TextStyle( fontFamily: 'WorkSans', fontSize: 48, color: Colors.deepPurple[400], height: 0.95, fontWeight: FontWeight.bold)), ], ), ), Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( Icons.people_alt, color: Colors.deepPurple[400], size: 35.0, ), SizedBox( width: 8, ), Text(peopleNum, style: TextStyle( fontFamily: 'WorkSans', fontSize: 16, color: Colors.deepPurple[400])), ], ), ], ), ), Expanded( flex: 2, child: Text("Price: " + price + " Baht", style: TextStyle( fontFamily: 'WorkSans', fontSize: 16, color: Colors.deepPurple[400])), ), Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( Icons.settings_outlined, color: Colors.deepPurple[400], size: 35.0, ), ], )) ], ), ), ); } And this is it shown on the simulator. error on simulator this is my JSON file [ { "roomNum": "101", "peopleNum": "1", "price": "3,500" }, { "roomNum": "102", "peopleNum": "1", "price": "3,500" } ] |
Solution to the finding the digits problem using recursion in Common Lisp doesn't give the expected result Posted: 01 Feb 2022 09:48 AM PST In order to solve the finding the digits problem using recursion in Common Lisp (CL): If CCC + BBB + AAA = CAAB, then find the numbers A, B, C. The numbers are unique integers I've written this code: (defun find! () (found? 0 ;; initially show the number 1 '(1 2 3) ;; initial list '() ;; initially no numbers found 3 ;; numbers list width is 3 ) ) (defun found? (index lst occupied width) (if (< index (1- width)) (do ( (j 1 (1+ j) ) ) ( (> j 9) lst) (unless (some (lambda (x) (= x j)) occupied) (setf (nth index lst) j) (push j occupied) (if (found? (1+ index) lst occupied width) ;; recursion lst (setf occupied (remove j occupied))))) (do ( (j 1 (1+ j) ) ) ( (> j 9) lst) (unless (some (lambda (x) (= x j)) occupied) (setf (nth index lst) j) (let ((lefthnd (* 111 (reduce #'+ lst))) (rghthnd (reduce #'+ (mapcar (lambda (x y) (* x y)) '(1000 100 10 1) (list (third lst) (first lst) (first lst) (second lst)) )))) (if (= lefthnd rghthnd) lst 'nil)))))) The delivered result (lst ) is (9 9 9) The expected result (lst ) is (9 8 1) Which parts of the CL code should I change so that it gives the expected result? Can someone fix the code? Note that using recursion is a must. |
Laravel create custom exception with parameters & return as JSON Posted: 01 Feb 2022 09:48 AM PST I want to throw a custom exception if the variable is null and return it as JSON. I've tried like this: Controller try { $check_api_key = $attendance_libraries->check_api_key($this->request); if ($check_api_key == null) { throw new NullException(false, 'API Key Not Found', null, 500); } } catch (NullException $e) { return $e; } catch (\Exception $e) { // do something else } Custom Exception <?php namespace App\Exceptions; use Exception; use Illuminate\Http\Response; class NullException extends Exception { public $is_success; public $message; public $code; public $data; public function __construct($is_success, $message, $code, $data = null, Exception $previous = NULL) { $this->is_success = $is_success; $this->message = $message; $this->code = $code; $this->data = $data; } public function render() { return response()->json([ 'success' => $this->is_success, 'message' => $this->message, 'data' => $this->data, ], $this->code); } } But when I am trying to test it using postman, the return I got is not the same as I wrote in NullException. It becomes like this: |
Squence generator for camunda Posted: 01 Feb 2022 09:48 AM PST How can I set my own IdGenerator for camunda via processes.xml. Before switching to using processes.xml, I used ProcessEngineConfiguration.setIdGenerator(IdGenerator); Which uses a sequence of a oracle database. |
Constrain pitch, yaw, & roll Posted: 01 Feb 2022 09:49 AM PST I've a rotation represented as a quaternion and am trying to constrain the pitch, yaw, & roll axes. I tried doing so thusly: public struct Orientation { public Vector3 up, forward; public Orientation(Vector3 up, Vector3 forward) { this.up = up; this.forward = forward; } } public static Orientation[] orientations = new Orientation[3] { new Orientation(Vector3.right, Vector3.up), new Orientation(Vector3.up, Vector3.forward), new Orientation(Vector3.forward, Vector3.right) }; public enum Axis { Pitch, Yaw, Roll }; private Vector3 ConstrainAxis(Vector3 vector, Axis axis, float from, float to) { Orientation orientation = orientations[(int)axis]; float theta = (to - from) * 0.5F; Vector3 cons = Quaternion.AngleAxis(from + theta, orientation.up) * orientation.forward; Vector3 proj = Vector3.ProjectOnPlane(vector, orientation.up); return ConstrainVector(cons.normalized, proj.normalized, theta); } private Vector3 ConstrainVector(Vector3 from, Vector3 to, float angle) { float theta = Mathf.Abs(angle / Vector3.Angle(from, to)); if(theta < 1.0F) { return Vector3.Slerp(from, to, theta); } return to; } Which turned out to be nothing more than an over-complicated way of constraining the individual components of an euler angle representation, of which both are subject to a strange jittering issue (gimbal lock related?). What is the best approach to constraining these axes? |
Android Studio - Device is connected but 'offline' Posted: 01 Feb 2022 09:49 AM PST This is quite a common question, but none of the solutions appear to work for me. First time asker, so apologies if I get the conventions wrong. I am trying to connect my Galaxy S5 to my computer running Ubuntu 14.04 so I can do some android development. I have recently downloaded and installed Android Studio and the SDK and my device is detected when it's connected via USB but the device either appears as 'unauthorized' or 'offline'. I know I should be expecting the RSA key prompt but this never appears. I have tried: - Checking debugging was enabled
- Running adb kill-server and adb devices
- Restarting (the device, developer options, the machine)
- Simple unplugging and replugging the USB cable
- Checking my adb version (it is 1.0.31)
- Trying different USB ports
- Revoking USB debugging authorizations
- Toggling enabling ADB Integration from within Android Studio
- Connecting as PTP device and MTP device
I have tried it on a separate machine that runs fedora and this works fine with no issues, the promopt appears right away. Therefore I imagine it is not the USB cable that is faulty. Any ideas? |
ggplot2 is there an easy way to wrap annotation text? Posted: 01 Feb 2022 09:49 AM PST I'm currently using ggplot2 and the annotate function, an example from the documentation is below. I have limited width to annotate text of unknown length and need an automatic way to wrap it within some x_start and x_end values. Since I don't want to change the font size, I will also need to shift the y value depending on how many breaks are introduced. Is there an easy way to accomplish this? # install.packages(c("ggplot2"), dependencies = TRUE) require(ggplot2) p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() p + annotate("text", x = 4, y = 25, label = "Some arbitrarily larger text") |
Two output file names resolved to the same output Posted: 01 Feb 2022 09:48 AM PST Recently I created new Form called WorkersScreen . When I try to run the project I got this error: Error 1 Two output file names resolved to the same output path: "obj\x86\Debug\DryWash.WorkersScreen.resources" What does it mean and how does one resolve it? |
Why both no-cache and no-store should be used in HTTP response? Posted: 01 Feb 2022 09:48 AM PST I'm told to prevent user-info leaking, only "no-cache" in response is not enough. "no-store" is also necessary. Cache-Control: no-cache, no-store After reading this spec http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, I'm still not quite sure why. My current understanding is that it is just for intermediate cache server. Even if "no-cache" is in response, intermediate cache server can still save the content to non-volatile storage. The intermediate cache server will decide whether using the saved content for following request. However, if "no-store" is in the response, the intermediate cache sever is not supposed to store the content. So, it is safer. Is there any other reason we need both "no-cache" and "no-store"? |
No comments:
Post a Comment