text
stringlengths
15
59.8k
meta
dict
Q: Google charts color change I need help changing axis color to black and background color to transparent for google charts... I have looked all over the web with no luck Also I've tried with css, still no luck I am using the following script: //Set-up the values for the Axis on the chart $maxWeeks = count($priceResults); //Set chd parameter to no value $chd = ''; //Limit in my example represents weeks of the year $limit = 52; //Start to compile the prices data for ($row = 0; $row < $limit; $row++) { //Check for a value if one exists, add to $chd if(isset($priceResults[$row]['price'])) { $chd .= $priceResults[$row]['price']; } //Check to see if row exceeds $maxWeeks if ($row < $maxWeeks) { //It doesn't, so add a comma and add the price to array $scaleValues $chd .= ','; $scaleValues[] = $priceResults[$row]['price']; } else if ($row >= $maxWeeks && $row < ($limit - 1)) { //Row exceeds, so add null value with comma $chd .= '_,'; } else { //Row exceeds and is last required value, so just add a null value $chd .= '_'; } } //Use the $scaleValues array to define my Y Axis 'buffer' $YScaleMax = round(max($scaleValues)) + 5; $YScaleMin = round(min($scaleValues)) - 5; //Generate the number of weeks of the year for A Axis labels $graphSequence = generateSequence(1, 10, "|"); $cht = 'lc';//Set the chart type $chxl = '';//custom axis labels $chxp = '';//Axis Label Positions $chxr = '0,' . $YScaleMin . ',' . $YScaleMax . '|1,1,52|3,1,12|5,' . $YScaleMin . ',' . $YScaleMax . '';//Axis Range $chxtc = '0,5|1,5|5,5';//Axis Tick Mark Styles $chxt = 'y,x';//Visible Axes $chs = '500x200';//Chart Size in px $chco = '76E32C';//Series Colours $chds = '' . $YScaleMin . ',' . $YScaleMax . '';//Custom Scaling $chg = '-1,-1,1,5';//Grid lines $chls = '2';//line styles $chm = '';//Shape Markers //Build the URL $googleUrl = 'http://chart.apis.google.com/chart?'; $rawUrl = $googleUrl . 'cht=' . $cht . '&chxl=' . $chxl . '&chxp=' . $chxp . '&chxr=' . $chxr . '&chxs=' . $chxs . '&chxtc=' . $chxtc . '&chxt=' . $chxt . '&chs=' . $chs . '&chco=' . $chco . '&chd=t:' . $chd . '&chds=' . $chds . '&chg=' . $chg . '&chls=' . $chls . '&chm=' . $chm; $output = $rawUrl; return $output; } /** * A nicer way to test arrays */ function displayArray($val) { echo "<pre>"; print_r($val); echo "</pre>"; return; } /** * a simple numeric sequence generator. requires a min and max for the sequence, and can take an optional seperator */ function generateSequence($min, $max, $seperator = "") { $output = ''; for ($i = $min; $i <= $max; $i++) { $output .= $i . $seperator; } return $output; } $chart = generateGoogleChart(); $html = '<div id="chart">'; $html .= '<img src="' . $chart . '" />'; $html .= '</div>'; echo $html; ?> Thank you for your time. A: I have used the Image Charts API in the past and implemented the builder pattern to generate my chart URL. Transparent backgrounds and coloured axis were used in our app with the method call providing transparency shown below; /** * Remove any background fill colours. The #chco parameter is used for {@link ChartType#BAR} * fills. * * @return this. * @see https://developers.google.com/chart/image/docs/chart_params#gcharts_solid_fills */ public GoogleImageChartBuilder withTransparentBackgroundFill() { stringBuilder.append("&chf=bg,s,00000000"); return this; } So on re-reading the documentation linked to above I have said with the chf parameter; "give me a solid background fill that is transparent"... perhaps a more sensible way of putting it would have been "give me a transparent background fill"! i.e. stringBuilder.append("&chf=bg,t,00000000"); The axis colouring is defined by the chxs parameter. Take a look at the last optional argument documented here named <opt_axis_color>. Hope that helps you out. Remember the image charts API is now deprecated. The JavaScript version isn't so terrifying :)
{ "language": "en", "url": "https://stackoverflow.com/questions/14667994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to gather hierarchical data items and build a tree considering their dependencies There is a table containing hierarchical data, e.g.: | table "attribute_instances" | +----+----------+------------+---------------+----------+ | id | tree_ref | parent_ref | attribute_ref | data_ref | +----+----------+------------+---------------+----------+ | 1 | 1 | -1 | 1 | 1 | | 2 | 1 | 1 | 2 | 2 | | 3 | 2 | -1 | 1 | 3 | | 4 | 2 | 3 | 2 | 2 | It contains many separate trees (see tree_ref), each of them instantiating some attributes (see attribute_ref) and have a data reference data_reference, where data might be referenced in other trees, too. Now, those trees should be merged into a single tree, in which (by now) up to 5 attributes may be chosen as level for that tree, e.g.: attribute => level ------------------ 2 => 1 1 => 2 What I need is one or more queries, that collects the data from table attribute_instances and gives a result as follows: | table "merged_attribute_instances" | +----+------------+---------------+----------+ | id | parent_ref | attribute_ref | data_ref | | 5 | -1 | 2 | 2 | | 6 | 5 | 1 | 1 | | 7 | 5 | 1 | 3 | This is the desired merged tree: id:5 - data_ref:2 id:6 - data_ref:1 id:7 - data_ref:3 Note, that attribute_ref = 2 occurs only once in the resulting tree, as all instances of it have same data_ref value (that is 2). I've tried some joins like select * from attribute_instances a join attribute_instances b on a.tree_ref = b.tree_ref But that seems to me being bad for having user-defined tree depth. I'm sure there is a better solution. UPDATE: I should add, that table merged_attribute_instances is a temporary table. And the collecting query is iterated with for..do. In the loop the collected attribute_instances are then added to the temporary table. A: OK, then use this: SET TERM ^ ; create or alter procedure GETTREENODES returns ( ID integer, TREE_REF integer, PARENT_REF integer, ATTRIBUTE_REF integer, DATA_REF integer) as declare variable DATAREFEXISTS varchar(4096); begin DATAREFEXISTS = ','; for Select id, tree_ref, parent_ref, attribute_ref, data_ref from attribute_instances into :id, :tree_ref, :parent_ref, :attribute_ref, :data_ref do begin IF (position(',' || data_ref || ',', DATAREFEXISTS) =0) THEN begin suspend; DATAREFEXISTS = DATAREFEXISTS || data_ref || ',' ; end end end^ SET TERM ; ^ /* Following GRANT statetements are generated automatically */ GRANT SELECT ON ATTRIBUTE_INSTANCES TO PROCEDURE GETTREENODES; /* Existing privileges on this procedure */ GRANT EXECUTE ON PROCEDURE GETTREENODES TO SYSDBA; Call it like this: Select * from gettreenodes order by tree_ref, parent_ref
{ "language": "en", "url": "https://stackoverflow.com/questions/31076620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gaps and Islands Months only I am working with a data set of clients and their date records. I am trying to apply a gaps and island problem only using MONTHS,( currently var char 'YYYYMM'). I need to take individual records and group by gaps in months(irregardless of year). I cant figure out how to go from: drop table RUNNING_LOG; create table running_log ( run_date date not null, time_in_seconds int not null, distance_in_miles int not null, SERV_YRMO VARCHAR2(6) ); insert into running_log values (date'2018-01-01', 420, 1,'201801'); insert into running_log values (date'2018-01-02', 2400, 5,'201801'); insert into running_log values (date'2018-01-03', 2430, 5,'201801'); insert into running_log values (date'2018-01-06', 2350, 5,'201801'); insert into running_log values (date'2018-02-07', 410, 1,'201802'); insert into running_log values (date'2018-02-10', 400, 1,'201802'); insert into running_log values (date'2018-02-13', 2300, 5,'201802'); insert into running_log values (date'2018-12-31', 425, 1,'201803'); insert into running_log values (date'2019-01-01', 422, 1,'201901'); insert into running_log values (date'2019-01-06', 2350, 5,'201901'); insert into running_log values (date'2019-02-07', 410, 1,'201902'); insert into running_log values (date'2019-02-10', 400, 1,'201902'); insert into running_log values (date'2019-02-13', 2300, 5,'201902'); insert into running_log values (date'2019-03-14', 425, 1,'201903'); insert into running_log values (date'2019-03-15', 422, 1,'201903'); insert into running_log values (date'2020-03-01', 425, 1,'202003'); insert into running_log values (date'2021-03-31', 422, 1,'202103'); commit; select * from running_log; To: A: The solution below uses the tabibitosan method to create the groups. If you are not familiar with this concept, google for it - you will find many good write-ups on it. (Sometimes also called the "fixed differences" method.) The heart of the method is the creation of groups in the subquery; select the subquery and run it by itself, without the outer query, to see what it does. Look particularly at the GRP column in the subquery; if you ask yourself HOW it does that, that's where you need to read about the method. As I explained in a Comment under your question, the SERV_YRMO column is not needed (if it is computed from the RUN_DATE value anyway), and in fact your INSERT statements have errors in that column. The solution below only uses RUN_DATE - you may as well drop the SERV_YRMO column, which will only cause trouble. Note also that, as I pointed out in another Comment under your question, your arithmetic seems wrong. My output is different from yours, for that reason. select to_char(min(run_date), 'yyyymm') as min_yrmo, to_char(max(run_date), 'yyyymm') as max_yrmo, sum(distance_in_miles) as total_distance from ( select rl.*, add_months( trunc(run_date, 'mm'), -dense_rank() over (order by trunc(run_date, 'mm')) ) as grp from running_log rl ) group by grp order by min_yrmo ; MIN_YRMO MAX_YRMO TOTAL_DISTANCE -------- -------- -------------- 201801 201802 23 201812 201903 16 202003 202003 1 202103 202103 1 EDIT The OP's version is 11 of some description. Still, for readers who may have the same question and have Oracle version 12.1 or higher, MATCH_RECOGNIZE can be used for a more efficient solution. It looks like this: select * from running_log match_recognize( order by run_date measures to_char(first(run_date), 'yyyymm') as min_yrmo, to_char(last (run_date), 'yyyymm') as max_yrmo, sum(distance_in_miles) as total_distance pattern ( a b* ) define b as run_date < add_months(trunc(prev(run_date), 'mm'), 2) ) ; A: One method is uses dense_rank() and truncating dates to months: select to_char(min(run_date), 'YYYY-MM'), to_char(max(run_date), 'YYYY-MM'), sum(distance) from (select t.*, dense_rank() over (order by trunc(run_date, 'Month')) as seqnum from t ) t group by trunc(run_date, 'Month') - seqnum * interval '1' month order by min(run_date); A: Check below SQL which use tabibitosan method of finding gap. resut consider count=1 as lake count >1 as Island select min(run_date), MAX(run_date), count(grp), decode (count(grp),1,'LAKE','ISLAND') from ( select run_date, run_date - rownum as grp from omc.running_log order by RUN_DATE ) group by grp ;
{ "language": "en", "url": "https://stackoverflow.com/questions/57663850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R apply: loses dimname names this is a simple enough question that I'm suprised I can't find any reference to anyone having asked it before. It's not the same as this, nor is it covered by this discussion. I have a 4-d matrix (dimensions 16x10x15x39) with named dimnames (it's what happens when you cast a dataframe from, e.g. a csv. You get to the names of the dimnames with names(dimnames(matrix))) I then want to replace the columns (i.e. the first dimension) with fractions of the row total, so I do this: matrix2 <- apply(matrix1, c(2,3,4), function(x){x/sum(x)}) But now names(dimnames(matrix2)) is blank for the first dimension. The other dimname names have been preserved. So: how can I run apply over a matrix with named dimnames and keep the names of all the remaining dimensions? A reproducable example Here's simple example of the problem. Just run the whole code and look at the last two lines. x <- data.frame( name=c("bob","james","sarah","bob","james", "sarah","bob","james","sarah","bob", "james","sarah"), year=c("1995","1995","1995","1995","1995", "1995","2005","2005","2005","2005", "2005","2005"), sample_num=c("sample1","sample1","sample1", "sample2","sample2","sample2", "sample1","sample1","sample1", "sample2","sample2","sample2"), value=c(1,2,3,2,3,4,1,2,3,2,3,4) ) x <- cast(x, sample_num ~ name ~ year) x_fractions <- apply(y,c(2,3),function(x){x / sum(x)}) names(dimnames(x)) names(dimnames(x_fractions)) A: I'm not quite sure what you're looking for, but I think sweep function fits well for your goal. Try: result <- sweep(test, c(2,3,4), colSums(test), FUN='/') Where test is the array created by @user2068776. dimnames are preserved. dimnames(result) $a [1] "a1" "a2" $b [1] "b1" "b2" $c [1] "c1" "c2" $d [1] "d1" "d2" A: It is really ambiguous to answer question without a reproducible example. I answer this question, because producing an example here is interesting. dat <- array(rnorm(16*10*15*39)) dim(dat) <- c(16,10,15,39) dimnames(dat) <- lapply(c(16,10,15,39), function(x) paste('a',sample(1:1000,x,rep=F),sep='')) dat2 <- apply(dat, c(2,3,4), function(x){x/sum(x)}) identical(dimnames(dat2) ,dimnames(dat)) [1] TRUE I get the same dimanmes for dat and dat2. So surely I miss something here. A: I can't reproduce this behavior using a non-casted array. Could you provide a reproducable example of what your dataframe/array actually looks like? Otherwise it is difficult to find out where the problem is. Here is the code I used for testing this: # example a <- c(1,2,11,22) b <- c(3,4,33,44) c <- c(5,6,55,66) d <- c(7,8,77,88) test <- array(c(a,b,c,d), c(2,2,2,2), dimnames=list( a=c("a1","a2"), b=c("b1","b2"), c=c("c1","c2"), d=c("d1","d2") ) ) dimnames(test) names(dimnames(test)) # apply test2 <- apply(test, c(2,3,4), function(x){ entry <- sum(x) }) dimnames(test2) names(dimnames(test2)) Sorry for the comment "diguised" as an answer. I am new to SO and as it seems you need a higher rep to post comments. Edit: Your dimnames might get lost, because for whatever reason the function your defined produces unnamed results. You can try saving x/sum(x) as an object (like I did) and then naming that object inside your function. I skipped the last part, because for me there were no missing names / dimnames
{ "language": "en", "url": "https://stackoverflow.com/questions/14874769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: maximum difference between two time series of different resolution I have two time series data that gives the electricity demand in one-hour resolution and five-minute resolution. I am trying to find the maximum difference between these two time series. So the one-hour resolution data has 8760 rows (hourly for an year) and the 5-minute resolution data has 104,722 rows (5-minutly for an year). I can only think of a method that will expand the hourly data into 5 minute resolution that will have 12 times repeating of the hourly data and find the maximum of the difference of the two data sets. If this technique is the way to go, is there an easy way to convert my hourly data into 5-minute resolution by repeating the hourly data 12 times? for your reference I posted a plot of this data for one day. P.S> I am using Python to do this task A: Numpy's .repeat() function You can change your hourly data into 5-minute data by using numpy's repeat function import numpy as np np.repeat(hourly_data, 12) A: I would strongly recommend against converting the hourly data into five-minute data. If the data in both cases refers to the mean load of those time ranges, you'll be looking at more accurate data if you group the five-minute intervals into hourly datasets. You'd get more granularity the way you're talking about, but the granularity is not based on accurate data, so you're not actually getting more value from it. If you aggregate the five-minute chunks into hourly chunks and compare the series that way, you can be more confident in the trustworthiness of your results. In order to group them together to get that result, you can define a function like the following and use the apply method like so: def to_hour(date): date = date.strftime("%Y-%m-%d %H:00:00") date = dt.strptime(date, "%Y-%m-%d %H:%M:%S") return date df['Aggregated_Datetime'] = df['Original_Datetime'].apply(lambda x: to_hour(x)) df.groupby('Aggregated_Datetime').agg('Real-Time Lo
{ "language": "en", "url": "https://stackoverflow.com/questions/60645104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Golang - How to "convert" an array ( [ ] ) to a list ( ... )? I'm using the UI lib (https://github.com/andlabs/ui) to make a program about students' groups. The ui.SimpleGrid allows a "list" of Control to be entered: func NewSimpleGrid(nPerRow int, controls ...Control) SimpleGrid I feel like in Java and other languages, it worked just as an array, which basically means that giving it one would work. However, this appears not to be the same in Go. func initStudentsGrid(students ...Student) ui.SimpleGrid { var i int var grd_studentsList []ui.Grid for i = 0; i < len(students); i++ { grd_student := ui.NewGrid() grd_student.Add(ui.NewLabel(students[i].group), nil, ui.West, true, ui.LeftTop, true, ui.LeftTop, 1, 1) grd_student.Add(ui.NewLabel(students[i].lastName), nil, ui.West, true, ui.LeftTop, true, ui.LeftTop, 1, 1) grd_student.Add(ui.NewLabel(students[i].firstName), nil, ui.West, true, ui.LeftTop, true, ui.LeftTop, 1, 1) grd_studentsList = append(grd_studentsList, grd_student) } return ui.NewSimpleGrid(1, grd_studentsList) The program's not compiling because: cannot use grd_studentsList (type []ui.Grid) as type ui.Control in argument to ui.NewSimpleGrid: []ui.Grid does not implement ui.Control (missing ui.containerHide method) Is there any way to do a kind of "cast" from an array to the required format, since it isn't possible to add the grids one by one (no append method on SimpleGrid)? A: It it doesn't work either... cannot use grd_studentsList (type `[]ui.Grid`) as type `[]ui.Control` in argument to `ui.NewSimpleGrid` As I mentioned before ("What about memory layout means that []T cannot be converted to []interface{} in Go?"), you cannot convert implicitly A[] in []B. You would need to copy first: var controls []ui.Control = make([]ui.Control, len(grd_studentsList)) for i, gs := range grd_studentsList{ controls [i] = gs } And then use the right slice (with the right type) return ui.NewSimpleGrid(1, controls...) A: Try something like: return ui.NewSimpleGrid(1, grd_studentsList...) ^^^^ This is mentioned in the spec Passing arguments to ... parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/29031625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select a row of a dataframe and order columns in ascending or descending order in R I have df<-data.frame(time=c("one", "two", "three", "four", "five"), A=c(1,2,3,4,5), B=c(5,1,2,3,4), C=c(4,5,1,2,3), D=c(3,4,5,1,2), E=c(2,3,4,5,1), EF=c(1,2,3,4,5)) I would like to select for example df[df$time=="one,] and order the columns in descending order (if possible in base R and dplyr), and output a data frame. For example for df[df$time=="one,] it would be output.one<-data.frame(time=c("one"), B=c(5), C=c(4), D=c(3), E=c(2), A=c(1)) output.one time B C D E A 1 one 5 4 3 2 1 and for df[df$time=="five,] > output.five<-data.frame(time=c("five"), A=c(5), B=c(4), C=c(3), D=c(2), E=c(1)) > output.five time A B C D E 1 five 5 4 3 2 1 A: in Base R order.one <- 1+order(df[df$time=="one",][(2:ncol(df))],decreasing = TRUE) output.one <- df[df$time=="one",][c(1,order.one)] The order can be switch to ascending by removing decreasing = TRUE A: Using pipes: library(magrittr) df %>% .[.$time == "one", ] %>% .[c(1, 1 + order(-.[-1]))] # "-" short for decreasing = TRUE time B C D E A 1 one 5 4 3 2 1
{ "language": "en", "url": "https://stackoverflow.com/questions/60775983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I do a grow and shrink counter in Jquery and HTML? I want to try and make a circle grow from 20px to 300px. It is supposed to only enlarge just to reduce back down in size. There is a button meant to be clicked to start the action. Every time the button is clicked, it is supposed to add one to the counter that says "Grow and Shrink Counter:". $(document).ready(function() { $("button").click(function() { $("div").animate({ height: '300px', width: '300px' }); $("div").animate({ height: '20px', width: '20px' }); }); }); let counter = 0 document.querySelector("#counter").addEventListener('click', function() { counter++ this.innerHTML = counter }) html { height: 100%; } #shrink { height: 1px; width: 1px; border-radius: 50%; background-color: lightgreen; margin: 5px; position: relative; color: white; } #container1 { display: flex; align-items: center; flex-direction: column; } #container2 { display: flex; align-items: center; flex-direction: column; justify-content: center; height: 75%; } #grow { margin: 5px; border-radius: 10px; } #counter { text: black; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container1"> <button id="grow"><span style="font-size:20px">Grow</span> and <span style="font-size:8px">Shrink</span></button> <p id="counter">Grow and Shrink Counter:</p> </div> <div id="container2"> <div id="shrink"></div> </div> A: Few mistakes I could find right off the bat: * *In your html, there are no opening and closing quotes for the ids *counter variable is declared twice. You can name the counter button variable to something like counterButton *In the code snippet, include jQuery library
{ "language": "en", "url": "https://stackoverflow.com/questions/72297873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling a specific validator on a specific attribute I defined a custom EachValidator to see if an attribute has leading or trailing whitespace. I know you can add it to the model like so: validates :name, whitespace: true But in the controller I want to call just run just the whitespace validator for some form feedback. I can run it like this: Validators::WhitespaceValidator.new(attributes: :name).validate_each(obj, :name, obj.name) Is there a shorter way to call the specific validator? Like you can do user.valid? but that runs all of the validations. I only want the whitespace validator on the name attribute. A: Since you did not come here to be told that your idea is bad and people will hate it: here is an idea that you can play with: :on https://guides.rubyonrails.org/active_record_validations.html#on validates :name, whitespace: true, on: :preview and then in the controller: def something @model.valid?(:preview) end If you want to run the validation also on createand update you can specify something like on: [:create,:update,:preview] (Thanks engineersmnky) Also: I don't think that giving early feedback to users, before they actually save the record is a bad idea if properly implemented. A: This feels like trying to solve a problem (leading/trailing whitespace) by creating a new problem (rejecting the object as invalid), and I agree with the comment about this being a brittle strategy. If the problem you want to solve here is whitespace, then solve that problem for the specific attributes where it matters before saving the object; check out Rails before_validation strip whitespace best practices
{ "language": "en", "url": "https://stackoverflow.com/questions/75242455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I get localized date pattern string? It is quite easy to format and parse Java Date (or Calendar) classes using instances of DateFormat. I could format the current date into a short localized date like this: DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); String today = formatter.format(new Date()); My problem is that I need to obtain this localized pattern string (something like "MM/dd/yy"). This should be a trivial task, but I just couldn't find the provider. A: The following code will give you the pattern for the locale: final String pattern1 = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale)).toPattern(); System.out.println(pattern1); A: Java 8 provides some useful features out of the box for working with and formatting/parsing date and time, including handling locales. Here is a brief introduction. Basic Patterns In the simplest case to format/parse a date you would use the following code with a String pattern: DateTimeFormatter.ofPattern("MM/dd/yyyy") The standard is then to use this with the date object directly for formatting: return LocalDate.now().format(DateTimeFormatter.ofPattern("MM/dd/yyyy")); And then using the factory pattern to parse a date: return LocalDate.parse(dateString, DateTimeFormatter.ofPattern("MM/dd/yyyy")); The pattern itself has a large number of options that will cover the majority of usecases, a full rundown can be found at the javadoc location here. Locales Inclusion of a Locale is fairly simple, for the default locale you have the following options that can then be applied to the format/parse options demonstrated above: DateTimeFormatter.ofLocalizedDate(dateStyle); The 'dateStyle' above is a FormatStyle option Enum to represent the full, long, medium and short versions of the localized Date when working with the DateTimeFormatter. Using FormatStyle you also have the following options: DateTimeFormatter.ofLocalizedTime(timeStyle); DateTimeFormatter.ofLocalizedDateTime(dateTimeStyle); DateTimeFormatter.ofLocalizedDateTime(dateTimeStyle, timeStyle); The last option allows you to specify a different FormatStyle for the date and the time. If you are not working with the default Locale the return of each of the Localized methods can be adjusted using the .withLocale option e.g DateTimeFormatter.ofLocalizedTime(timeStyle).withLocale(Locale.ENGLISH); Alternatively the ofPattern has an overloaded version to specify the locale too DateTimeFormatter.ofPattern("MM/dd/yyyy",Locale.ENGLISH); I Need More! DateTimeFormatter will meet the majority of use cases, however it is built on the DateTimeFormatterBuilder which provides a massive range of options to the user of the builder. Use DateTimeFormatter to start with and if you need these extensive formatting features fall back to the builder. A: Please find in the below code which accepts the locale instance and returns the locale specific data format/pattern. public static String getLocaleDatePattern(Locale locale) { // Validating if Locale instance is null if (locale == null || locale.getLanguage() == null) { return "MM/dd/yyyy"; } // Fetching the locale specific date pattern String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance( DateFormat.SHORT, locale)).toPattern(); // Validating if locale type is having language code for Chinese and country // code for (Hong Kong) with Date Format as - yy'?'M'?'d'?' if (locale.toString().equalsIgnoreCase("zh_hk")) { // Expected application Date Format for Chinese (Hong Kong) locale type return "yyyy'MM'dd"; } // Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd").replaceAll( "M{1,2}", "MM").replaceAll("y{1,4}|Gy", "yyyy"); // Replacing all blank spaces in the locale date pattern localeDatePattern = localeDatePattern.replace(" ", ""); // Validating the date pattern length to remove any extract characters if (localeDatePattern.length() > 10) { // Keeping the standard length as expected by the application localeDatePattern = localeDatePattern.substring(0, 10); } return localeDatePattern; } A: For SimpleDateFormat, You call toLocalizedPattern() EDIT: For Java 8 users: The Java 8 Date Time API is similar to Joda-time. To gain a localized pattern we can use class DateTimeFormatter DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); Note that when you call toString() on LocalDate, you will get date in format ISO-8601 Note that Date Time API in Java 8 is inspired by Joda Time and most solution can be based on questions related to time. A: For those still using Java 7 and older: You can use something like this: DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); String pattern = ((SimpleDateFormat)formatter).toPattern(); String localPattern = ((SimpleDateFormat)formatter).toLocalizedPattern(); Since the DateFormat returned From getDateInstance() is instance of SimpleDateFormat. Those two methods should really be in the DateFormat too for this to be less hacky, but they currently are not. A: It may be strange, that I am answering my own question, but I believe, I can add something to the picture. ICU implementation Obviously, Java 8 gives you a lot, but there is also something else: ICU4J. This is actually the source of Java original implementation of things like Calendar, DateFormat and SimpleDateFormat, to name a few. Therefore, it should not be a surprise that ICU's SimpleDateFormat also contains methods like toPattern() or toLocalizedPattern(). You can see them in action here: DateFormat fmt = DateFormat.getPatternInstance( DateFormat.YEAR_MONTH, Locale.forLanguageTag("pl-PL")); if (fmt instanceof SimpleDateFormat) { SimpleDateFormat sfmt = (SimpleDateFormat) fmt; String pattern = sfmt.toPattern(); String localizedPattern = sfmt.toLocalizedPattern(); System.out.println(pattern); System.out.println(localizedPattern); } ICU enhancements This is nothing new, but what I really wanted to point out is this: DateFormat.getPatternInstance(String pattern, Locale locale); This is a method that can return a whole bunch of locale specific patterns, such as: * *ABBR_QUARTER *QUARTER *YEAR *YEAR_ABBR_QUARTER *YEAR_QUARTER *YEAR_ABBR_MONTH *YEAR_MONTH *YEAR_NUM_MONTH *YEAR_ABBR_MONTH_DAY *YEAR_NUM_MONTH_DAY *YEAR_MONTH_DAY *YEAR_ABBR_MONTH_WEEKDAY_DAY *YEAR_MONTH_WEEKDAY_DAY *YEAR_NUM_MONTH_WEEKDAY_DAY *ABBR_MONTH *MONTH *NUM_MONTH *ABBR_STANDALONE_MONTH *STANDALONE_MONTH *ABBR_MONTH_DAY *MONTH_DAY *NUM_MONTH_DAY *ABBR_MONTH_WEEKDAY_DAY *MONTH_WEEKDAY_DAY *NUM_MONTH_WEEKDAY_DAY *DAY *ABBR_WEEKDAY *WEEKDAY *HOUR *HOUR24 *HOUR_MINUTE *HOUR_MINUTE_SECOND *HOUR24_MINUTE *HOUR24_MINUTE_SECOND *HOUR_TZ *HOUR_GENERIC_TZ *HOUR_MINUTE_TZ *HOUR_MINUTE_GENERIC_TZ *MINUTE *MINUTE_SECOND *SECOND *ABBR_UTC_TZ *ABBR_SPECIFIC_TZ *SPECIFIC_TZ *ABBR_GENERIC_TZ *GENERIC_TZ *LOCATION_TZ Sure, there are quite a few. What is good about them, is that these patterns are actually strings (as in java.lang.String), that is if you use English pattern "MM/d", you'll get locale-specific pattern in return. It might be useful in some corner cases. Usually you would just use DateFormat instance, and won't care about the pattern itself. Locale-specific pattern vs. localized pattern The question intention was to get localized, and not the locale-specific pattern. What's the difference? In theory, toPattern() will give you locale-specific pattern (depending on Locale you used to instantiate (Simple)DateFormat). That is, no matter what target language/country you put, you'll get the pattern composed of symbols like y, M, d, h, H, M, etc. On the other hand, toLocalizedPattern() should return localized pattern, that is something that is suitable for end users to read and understand. For instance, German middle (default) date pattern would be: * *toPattern(): dd.MM.yyyy *toLocalizedPattern(): tt.MM.jjjj (day = Tag, month = Monat, year = Jahr) The intention of the question was: "how to find the localized pattern that could serve as hint as to what the date/time format is". That is, say we have a date field that user can fill-out using the locale-specific pattern, but I want to display a format hint in the localized form. Sadly, so far there is no good solution. The ICU I mentioned earlier in this post, partially works. That's because, the data that ICU uses come from CLDR, which is unfortunately partially translated/partially correct. In case of my mother's tongue, at the time of writing, neither patterns, nor their localized forms are correctly translated. And every time I correct them, I got outvoted by other people, who do not necessary live in Poland, nor speak Polish language... The moral of this story: do not fully rely on CLDR. You still need to have local auditors/linguistic reviewers. A: You can use DateTimeFormatterBuilder in Java 8. Following example returns localized date only pattern e.g. "d.M.yyyy". String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern( FormatStyle.SHORT, null, IsoChronology.INSTANCE, Locale.GERMANY); // or whatever Locale A: Since it's just the locale information you're after, I think what you'll have to do is locate the file which the JVM (OpenJDK or Harmony) actually uses as input to the whole Locale thing and figure out how to parse it. Or just use another source on the web (surely there's a list somewhere). That'll save those poor translators. A: Im not sure about what you want, but... SimpleDateFormat example: SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy"); Date date = sdf.parse("12/31/10"); String str = sdf.format(new Date()); A: You can try something like : LocalDate fromCustomPattern = LocalDate.parse("20.01.2014", DateTimeFormatter.ofPattern("MM/dd/yy"))
{ "language": "en", "url": "https://stackoverflow.com/questions/4594519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Using loop and sum functions with Vlookup I've got a macro that essentially searches column C in Sheet1 for the value "Rec" and copies the corresponding value in column D, then pastes it into the last open cell in column B of Sheet2. It does just what it is supposed to do and is as follows: Sub FindPasteGSVInNextCell() Worksheets("Sheet2").Activate Range("B" & Rows.Count).End(xlUp).Offset(1, 0).Value = _ WorksheetFunction.VLookup("Rec", Sheet1.Range("C2:H25"), 2, False) End Sub I now want the code, instead of just searching for a single "Rec" value, to search for all rows with "Rec" in column C and to sum up all of their corresponding values in column D, then place that sum into Sheet2. I am assuming that I need some kind of Do Until loop or something, but I am not exactly sure how to format it... I am a beginner with VBA, so any help would be greatly appreciated. A: vlookup will not work as it will continue to only grab the first instance of "Rec". On Sheet 2 list all the possible categories in column A then in column B1 put = sumif(Sheet1!C:C,A1,Sheet1!D:D) then copy down. This will Get you the totals by category. If you want to use VBA, you will still need a list of categories setup somewhere, either hard coded or listed somewhere that you can loop through. If your list was in column A on Sheet2 then you would: dim ws as worksheet set ws = Worksheets("Sheet2") For each i in ws.range(ws.Range("A1"),ws.Range("A1").offset(xldown)).Cells i.offset(,1) = WorksheetFunction.Sumif(Worksheets("Sheets1").Range("C:C"), _ i,Worksheets("Sheets1").Range("D:D")) next i
{ "language": "en", "url": "https://stackoverflow.com/questions/32768571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search only get or set references for property in VS2010? I use VS 2010 and C#. When I want to found all references to the methods or properties I press Shift+F12. It's possible to find only get or set references for examined property. It's possible? Maybe I should install any extension? A: The poor man's way is to simply remove/comment-out either the getter or setter and recompile: all the errors will be your references. ;) EDIT: Instead of deleting it (which could be invalid syntax), change the visibility of the particular get/set to private. A: I would suggest you to evalutate the ReSharper product which has extremely powerful features that enhance Visual Studio a lot. Find Usages is what you are looking for. If you find the ReSharper to be ok (and you will!) then go ahead and buy a license after evaluation. Just make sure to try it out at least!
{ "language": "en", "url": "https://stackoverflow.com/questions/11140088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: WPF memory fragmentation I've got what I assume is a memory fragmentation issue. We've recently ported our WinForms application to a WPF application. There's some image processing that this application does, and this processing always worked in the WinForms version of the app. We go to WPF, and the processing dies. Debugging into the library has the death at random spots, but always with an array that's nulled, ie, allocation failed. The processing itself is done in a C++ library called by a p/invoke and is fairly memory intense; if the given image is N x M pixels big, then the image is N x M x 2 bytes big (each pixel is an unsigned short, and it's a greyscale image). During the processing, image pyramids are made, which are in float space, so the total memory usage will be N x M x (2 + 2 + 4 + 4 + 4 + 4), where the first 2 is the input, the second 2 is the output, the first 4 is the input in floats, the second 4 is the 0th level difference image, and the last two fours are the rest of the pyramid (since they're pyramids and each level is half the size in each direction, these 4s are upper bounds). So, for a 5000x6000 image, that's 600 mb, which should fit into memory just fine. (There's the possibility that using marshalling is increasing the memory requirement by another N x M x 4, ie, the input and output images on the C# side and then the same arrays copied to the C++ side-- could the marshalling requirement be bigger?) How fragmented is WPF compared to WinForms? Is there a way to consolidate memory before running this processing? I suspect that fragmentation is the issue due to the random nature of the breakages, when they happen, and that it's always a memory allocation problem. Or should I avoid this problem entirely by making the processing run as a separate process, with data transfer via sockets or some such similar thing? A: If I read this correctly, the memory allocation failure is happening on the non-managed side, not the managed side. It seems strange then to blame WPF. I recognize that you are drawing your conclusion based on the fact that "it worked in WinForms", but there are likely more changes than just that. You can use a tool like the .NET Memory Profiler to see the differences between how the WPF application and the WinForms application are treating memory. You might find that your application is doing something you don't expect. :) Per comment: Yup, I understand. If you're confident that you've ruled out things like environment changes, I think you have to grab a copy of BoundsChecker and Memory Profiler (or DevPartner Studio) and dig in and see what's messing up your memory allocation. A: I'm guessing that the GC is moving your memory. Try pinning the memory in unmanaged land as long as you have a raw pointer to the array, and unpin it as soon as possible. It's possible that WPF causes the GC to run more often, which would explain why it happens more often with it, and if it's the GC, then that would explain why it happens at random places in your code. Edit: Out of curiosity, could you also pre-allocate all of your memory up front (I don't see the code, so don't know if this is possible), and make sure all of your pointers are non-null, so you can verify that it's actually happening in the memory allocation, rather than some other problem? A: It sounds like you want to be more careful about your memory management in general; ie: either run the processing engine in a separate address space which carefully manages memory, or pre-allocate a sufficiently large chunk before memory gets too fragmented and manage images in that area only. If you're sharing address space with the .NET runtime in a long-running process, and you need large contiguous areas, it's always going to potentially fail at some point. Just my 2c. A: This post might be useful http://blogs.msdn.com/tess/archive/2009/02/03/net-memory-leak-to-dispose-or-not-to-dispose-that-s-the-1-gb-question.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/865735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nested Marshmallow field does not show data in nested Schema I have a table type and language. I have a 1 to many relationship called languages from Type to Language. Marshmallow keeps showing there is no data inside a Type entry despite the data showing up in the console. Does anyone have any idea why? schemas.py class LanguageSchema(ma.SQLAlchemySchema): class Meta: model = Language ordered = True language = ma.auto_field() class TypeSchema(ma.SQLAlchemySchema): class Meta: model = Type ordered = True id = ma.auto_field(dump_only=True) name = ma.auto_field(required=True, validate=validate.Length(min=3, max=64)) settings = ma.Nested(TypeSettingsSchema, dump_only=True) languages = ma.Nested(LanguageSchema, many=False) models.py class Language(Updateable, db.Model): __tablename__ = 'language' id = sqla.Column(sqla.Integer, primary_key=True) language = sqla.Column(sqla.String(2), nullable=False) type_id = sqla.Column(sqla.Integer, sqla.ForeignKey(Type.id), index=True) type = sqla_orm.relationship('Type', back_populates='languages') class Type(Updateable, db.Model): __tablename__ = 'type' languages = sqla_orm.relationship('Language', back_populates='type') Output from query { "data": [ { "id": 1, "languages": {}, "name": "Grocery", "settings": { "isHome": true, "layoutType": "classic", "productCard": "neon" } }] } console output showing what the query for id1 brings up and you can clearly see languages has data. >>> t1.id 1 >>> t1.languages[0].language 'en' >>> t1.name 'Grocery' A: You have a one to many relationship from type to language. So set the many parameter for the nested languages attribute within the TypeSchema to True and it should work. from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow app = Flask(__name__) db = SQLAlchemy(app) ma = Marshmallow(app) class Language(db.Model): id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(2), nullable=False) type_id = db.Column(db.Integer, db.ForeignKey('type.id')) type = db.relationship('Type', backref='languages') class Type(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) class LanguageSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Language class TypeSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Type languages = ma.Nested(LanguageSchema, only=('code',), many=True) with app.app_context(): db.drop_all() db.create_all() l = Language(code='en') t = Type( name='Grocery', languages=[l] ) db.session.add(t) db.session.commit() @app.route('/') def index(): types = Type.query.all() types_schema = TypeSchema(many=True) types_data = types_schema.dump(types) return jsonify(data=types_data) { "data": [ { "id": 1, "languages": [ { "code": "en" } ], "name": "Grocery" } ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/73840186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update records using named scopes in rails I use this bit of code to search for records using the the like query. Is it possible to create another scope which can update a record. scope :search, lambda{|query| where(["name LIKE ?", "%#{query}%"])} A: You can use rails' update_all method. See here for a description: http://apidock.com/rails/ActiveRecord/Relation/update_all EDIT: It's part of the Relation class, so you may call this on scopes (It doesn't say that explicit in the documentation) EDIT2: It works very much like destroy_all which may also be called on scopes (Relation)
{ "language": "en", "url": "https://stackoverflow.com/questions/5550460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: guidance needed for corda Application design I have a web background majorly with javascript, I have started learning Corda recently for project implementation and need guidance in this regard, So our application is based on the web, the user signs up with different school name, create question papers, and then want to share either part of it or whole with teachers of some other school in our platform. they can make changes and assign it back to creator and the process goes back and forth, finally signing the paper to be finalized, once finalized it cannot be changed by anyone. I need to store these transactions in Corda application, not sure how to go about it, I did try replicating it using negotiation application in corda/kotlin/sample, but stuck in a bug as I was trying to send a list of objects. I do have the following questions in mind * *Should I use enterprise edition or go with open source as I think I need schema design for this. web db is in postgress *As far as I have seen each node is predefined in the config with username and password,is there a way to create the node while the user signs up. *I have schools and teachers inside the school, do I need a separate node for each school and then create states in each node(not sure if a node can be set up at run time). or do I use the account's library provided for creating the account of each teacher, if yes id there a way to use passwords in it, unable to find password field in it. *how do I send an array of objects to the state, or should I create a separate state for each question, as different questions can be assigned to different teachers, but again multiple questions can be assigned to the same teacher. These are few questions on my mind any help is much appreciated, as most of the examples gave IOU samples or states with int and string, Please guide me in the right direction. A: Alessandro has good advice here, definitely look at the samples repos for inspiration on how to build what you're looking for. * *start with open source, it's easier to prototype and you can switch to enterprise later it won't be an issue for you *this depends on design, you wouldn't really want to create a new corda node per-person, you might want to have corda accounts that run on a single node instead. See accounts sdk here: https://github.com/corda/accounts *what you might do is make a corda node for each school and then accounts per teacher like you were already were thinking. That would mean only a couple of nodes based on the number of schools you have. *as long as your state is marked with @CordaSerializable you won't have problems sending arrays of data, I send an array in a state in this sample here: https://github.com/corda/samples-java/blob/master/Advanced/secretsanta-cordapp/contracts/src/main/java/net/corda/samples/secretsanta/states/SantaSessionState.java#L24 https://github.com/corda/samples-java https://github.com/corda/samples-kotlin
{ "language": "en", "url": "https://stackoverflow.com/questions/67097436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is there a way to create multiple columns from existing columns of a dataframe in Scala? I am trying to ingest an RDBMS table into Hive. I have obtained the dataframe in the following way: val yearDF = spark.read.format("jdbc").option("url", connectionUrl) .option("dbtable", "(select * from schema.tablename where source_system_name='DB2' and period_year='2017') as year2017") .option("user", devUserName) .option("password", devPassword) .option("numPartitions",15) .load() These are the columns of the dataframe: geography:string| project:string| reference_code:string product_line:string book_type:string cc_region:string cc_channel:string cc_function:string pl_market:string ptd_balance:double qtd_balance:double ytd_balance:double xx_last_update_tms:timestamp xx_last_update_log_id:int xx_data_hash_code:string xx_data_hash_id:bigint The columns ptd_balance, qtd_balance, ytd_balance are double datatypes which are precision columns. Our project wants to convert their datatype from Double to String by creating new columns: ptd_balance_text, qtd_balance_text, ytd_balance_text with same data inorder to avoid any data truncation. withColumn will create a new column in the dataframe. withColumnRenamed will rename the existing column. The dataframe has nearly 10 million records. Is there an effective way to create multiple new columns with same data and different type from the existing columns in a dataframe ? A: You can do this creating query from all columns like below import org.apache.spark.sql.types.StringType //Input: scala> df.show +----+-----+--------+--------+ | id| name| salary| bonus| +----+-----+--------+--------+ |1001|Alice| 8000.25|1233.385| |1002| Bob|7526.365| 1856.69| +----+-----+--------+--------+ scala> df.printSchema root |-- id: integer (nullable = false) |-- name: string (nullable = true) |-- salary: double (nullable = false) |-- bonus: double (nullable = false) //solution approach: val query=df.columns.toList.map(cl=>if(cl=="salary" || cl=="bonus") col(cl).cast(StringType).as(cl+"_text") else col(cl)) //Output: scala> df.select(query:_*).printSchema root |-- id: integer (nullable = false) |-- name: string (nullable = true) |-- salary_text: string (nullable = false) |-- bonus_text: string (nullable = false) scala> df.select(query:_*).show +----+-----+-----------+----------+ | id| name|salary_text|bonus_text| +----+-----+-----------+----------+ |1001|Alice| 8000.25| 1233.385| |1002| Bob| 7526.365| 1856.69| +----+-----+-----------+----------+ A: If i was in your shoes, i would make changes in the extraction query or ask BI team to put some effort :P for adding and casting the fields on the fly while extracting, but any how what you are asking is possible. You can add the columns from the existing columns as below. Check the addColsTosampleDF dataframe. I hope the comments below will be enough to understand, if you have any questions feel free to add in the comments and i will edit my answer. scala> import org.apache.spark.sql.functions._ import org.apache.spark.sql.functions._ scala> import org.apache.spark.sql.{DataFrame, Row, SparkSession} import org.apache.spark.sql.{DataFrame, Row, SparkSession} scala> val ss = SparkSession.builder().appName("TEST").getOrCreate() 18/08/07 15:51:42 WARN SparkSession$Builder: Using an existing SparkSession; some configuration may not take effect. ss: org.apache.spark.sql.SparkSession = org.apache.spark.sql.SparkSession@6de4071b //Sample dataframe with int, double and string fields scala> val sampleDf = Seq((100, 1.0, "row1"),(1,10.12,"col_float")).toDF("col1", "col2", "col3") sampleDf: org.apache.spark.sql.DataFrame = [col1: int, col2: double ... 1 more field] scala> sampleDf.printSchema root |-- col1: integer (nullable = false) |-- col2: double (nullable = false) |-- col3: string (nullable = true) //Adding columns col1_string from col1 and col2_doubletostring from col2 with casting and alias scala> val addColsTosampleDF = sampleDf. select(sampleDf.col("col1"), sampleDf.col("col2"), sampleDf.col("col3"), sampleDf.col("col1").cast("string").alias("col1_string"), sampleDf.col("col2").cast("string").alias("col2_doubletostring")) addColsTosampleDF: org.apache.spark.sql.DataFrame = [col1: int, col2: double ... 3 more fields] //Schema with added columns scala> addColsTosampleDF.printSchema root |-- col1: integer (nullable = false) |-- col2: double (nullable = false) |-- col3: string (nullable = true) |-- col1_string: string (nullable = false) |-- col2_doubletostring: string (nullable = false) scala> addColsTosampleDF.show() +----+-----+---------+-----------+-------------------+ |col1| col2| col3|col1_string|col2_doubletostring| +----+-----+---------+-----------+-------------------+ | 100| 1.0| row1| 100| 1.0| | 1|10.12|col_float| 1| 10.12| +----+-----+---------+-----------+-------------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/51729222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (Python 3.9) Calling Objects created using a loop I am new to Python, and I am working on a Tic Tac Toe game coded using OOP. After completing the tile, however, I cannot figure out how to determine the winner (or draw). Here is the code: import tkinter as tk root =tk.Tk() root.title('Tic Tac Toe') player = 'cross' class Tile(): def __init__(self): self.tile = tk.Button( root, font = ('Arial', 35), width=3, command = self.write ) def write(self): global player if player == 'cross': self.tile.config(text = 'X', state = tk.DISABLED) player = 'circle' elif player == 'circle': self.tile.config(text = 'O', state = tk.DISABLED) player = 'cross' else: print('wrong var') def grid(self, row, column): self.tile.grid(row=row, column=column) for row in range(0,3): for column in range(0,3): Tile().grid(row, column) root.mainloop() I wonder if I can assign a name to each of the tile objects, so that I can call them later and get the button text of each of them, hence compare them with the win conditions. A: If you change your setup to tiles = [] for row in range(0,3): tiles.append([]) for column in range(0,3): tiles[-1].append(Tile()) tiles[-1][-1].grid(row, column) you can access your tiles as tiles[row][column] at the end and get the text to compare against the win conditions.
{ "language": "en", "url": "https://stackoverflow.com/questions/68221251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cant install botman for Laravel I wanted to try to create a simple chatbot web-app using Laravel Botman. I've created a new Laravel project but when I try to install Botman through the terminal. I get this error. Your requirements could not be resolved to an installable set of packages. Problem 1 - Conclusion: don't install botman/botman 2.6.1 (conflict analysis result) - symfony/mailer v6.0.7 requires symfony/service-contracts ^1.1|^2|^3 -> satisfiable by symfony/service-contracts[v3.0.1]. - laravel/framework v9.7.0 requires symfony/mailer ^6.0 -> satisfiable by symfony/mailer[v6.0.7]. - Root composer.json requires botman/botman ^2.6 -> satisfiable by botman/botman[2.6.0, 2.6.1]. - Conclusion: don't install psr/container 2.0.2 (conflict analysis result) - Conclusion: don't install psr/container 1.1.2 (conflict analysis result) - laravel/framework is locked to version v9.7.0 and an update of this package was not requested. - Conclusion: don't install psr/container 2.0.1 (conflict analysis result) - botman/botman 2.6.0 requires psr/container ^1.0 -> satisfiable by psr/container[1.0.0, ..., 1.x-dev]. - You can only install one version of a package, so only one of these can be installed: psr/container[dev-master, 1.0.0, ..., 1.x-dev, 2.0.0, 2.0.1, 2.0.2]. - psr/container 2.0.x-dev is an alias of psr/container dev-master and thus requires it to be installed too. - symfony/service-contracts v3.0.1 requires psr/container ^2.0 -> satisfiable by psr/container[2.0.0, 2.0.1, 2.0.2, 2.0.x-dev (alias of dev-master)]. - Conclusion: don't install psr/container[2.0.0] | install one of psr/container[2.0.1, 2.0.2] (conflict analysis result) Installation failed, reverting ./composer.json and ./composer.lock to their original content. I've tried deleting the composer.lock file and installing it again. I tried using composer require botman/botman --with-all-dependencies but it still didn't work. Can anyone help me out? Thank you. A: Try adding to composer.json in the section requires "psr/container": "2.0.2 as 1.1.2","symfony/http-foundation": "6.0.3 as 5.4.3" and after that in the terminal 'composer requires botman/botman --with-all-dependencies A: try composer require botman/botman composer require mpociot/botman package is abandoned
{ "language": "en", "url": "https://stackoverflow.com/questions/71820960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run specific gradle task only if this given test was activated at gradle test phase? I want to make sure that a particular gradle task is running before tests only if specific tests is enabled. For instance, let's say I have test called TranslationTests that look something like this: @EnabledIfSystemProperty(named = "org.shabunc.tests.TranslationTests", matches = "true") class TranslationTests { ... } Which is activated the following way: test { if (project.hasProperty(projectProperty)) { systemProperty(projectProperty, "org.shabunc.tests.TranslationTests") } } Now I want to be sure that each time I'm running: gradle test -Porg.shabunc.tests.TranslationTests before tests some specific gradle task, say gradle prepareTranslationSetup is triggered. Strictly speaking I want this task to be triggered each time I know TranslationTests are running - and don't be triggered otherwise. A: You can use onlyIf() on task prepareTranslationSetup and make test depend on it. onlyIf() is defined as follows: You can use the onlyIf() method to attach a predicate to a task. The task’s actions are only executed if the predicate evaluates to true. (From: Authoring Tasks) Example Let's say you've got the following tasks: task doBeforeTest { onlyIf { project.hasProperty("runit") } doLast { println "doBeforeTest()" } } task runTest { dependsOn = [ doBeforeTest ] doLast { println "runTest()" } } doBeforeTest's actions are only executed if the project has the specified property. runTest is configured to depend on doBeforeTest. Now, when you do gradlew runTest --info the output is similar to > Task :doBeforeTest SKIPPED Skipping task ':doBeforeTest' as task onlyIf is false. > Task :runTest runTest() As you can see doBeforeTest is skipped as the precondition is not fulfilled. On the other hand, running gradlew runTest -Prunit executes doBeforeTest as expected > Task :doBeforeTest doBeforeTest() > Task :runTest runTest()
{ "language": "en", "url": "https://stackoverflow.com/questions/59214601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to stop Quartz Scheduler Logging in console I have used Quartz Scheduler to schedule a job to execute on the last day of every month. Now for the job Quartz is logging lots of DEBUG information in tomcat console. I have turned off the logging using log4j properties successfully. But now for some reason I have to use log4j2 and now I have to do the same in log4j2.xml file. Can anyone tell me how to set up log4j2 xml configuration to stop quartz scheduler logging? Thanks, Surodip A: I assume you have already checked the log4j2 documentation so you know how to create a basic log4j2.xml file. I also assume you want to keep some logging but only want to switch off some very verbose logging by org.quartz.scheduler.* loggers. Then, a basic config with quartz loggers switched to ERROR-only could look like this: <?xml version="1.0" encoding="UTF-8"?> <Configuration status="warn" name="MyApp" packages=""> <Appenders> <File name="MyFile" fileName="logs/app.log"> <PatternLayout> <Pattern>%p %d %c{1.} [%t] %m%n</Pattern> </PatternLayout> </File> </Appenders> <Loggers> <Logger name="org.quartz.scheduler" level="ERROR" additivity="false"> <AppenderRef ref="MyFile"/> </Logger> <Root level="trace"> <AppenderRef ref="MyFile"/> </Root> </Loggers> </Configuration> A: <?xml version="1.0" encoding="UTF-8"?> <Configuration status="warn" name="MyApp" packages=""> <Appenders> <File name="MyFile" fileName="logs/app.log"> <PatternLayout> <Pattern>%p %d %c{1.} [%t] %m%n</Pattern> </PatternLayout> </File> </Appenders> <Loggers> <Logger name="org.quartz" level="ERROR" additivity="false"> <AppenderRef ref="MyFile"/> </Logger> <Root level="trace"> <AppenderRef ref="MyFile"/> </Root> </Loggers> </Configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/22317482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with Connecting to AWS RDS MySQL Database with Xamarin Forms App (C#, Android Emulator) Hi stackoverflow community, I am trying my hands on some Xamarin Forms to code my own app. Together with that I want to expand my knowledge about AWS RDS. While Coding a Database class in C# that should return a value from my Database as a DisplayAlert() (on Android Emulator) I ran into an exception."System.TypeInitializationException: 'The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.'" It worked on Windows Forms. My Code: using System; using System.Collections.Generic; using System.Text; using MySql.Data.MySqlClient; namespace StudyWithMe { class DB { public static MySqlConnection dbConnection; static string host = "awsEndpoint"; static string id = "myuserid"; static string pwd = "mypassword"; static string database = "mydatabase"; static string port = "3306"; public string getSalt(string email) { OpenSql(); string query = "SELECT salt"; query += " FROM Authentication WHERE email = '" + email + "';"; string salt = ExecuteQuery(query).Tables[0].Rows[0][0].ToString(); Close(); return salt; } private static void OpenSql() { try { string connectionString = string.Format("Server = {0};port={4}; Database = {1}; Uid = {2}; Pwd = {3};", host, database, id, pwd, port); MySqlConnection dbConnection = new MySqlConnection(connectionString); dbConnection.Open(); } catch (Exception e) { throw new Exception("error" + e.Message.ToString()); } } private void Close() { if (dbConnection != null) { dbConnection.Close(); dbConnection.Dispose(); dbConnection = null; } } private static DataSet ExecuteQuery(string sqlString) { if (dbConnection.State == ConnectionState.Open) { DataSet ds = new DataSet(); try { MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection); da.Fill(ds); } catch (Exception ee) { throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString()); } return ds; } return null; } } }``` Thanks for your help! PS: I did install the NuGet package MySql.Data A: Uninstall the MySql.Data NuGet package and install MySqlConnector instead; it has better cross-platform compatibility with Xamarin. FWIW, initiating a database connection from an Android device is a bad idea, because the credentials are easily extracted from the application and could be used by anyone to log into your database. The better approach is for the Xamarin app to authenticate against a web service (that you author), e.g., with username and password, and for the web service to connect to the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/64397523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does my onBindViewHolder () not run at all even though all my other recycler view methods run? I have created a recycler view that is supposed to display data in a text view and an image view. But the onBindViewHolder () for my adapter does not run. All the other methods in my adapter run. I cannot find the reason why the onBindViewHolder () does not run, everything else seems to be working fine it's just my data is not displayed in the card views for my recycler view. Any help would be appreciated thanks. Adapter code: package com.myapps.myapplication; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.util.Log; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import androidx.cardview.widget.CardView; public class captionedImagesAdapter extends RecyclerView.Adapter <captionedImagesAdapter.ViewHolder> { private Context context; private Cursor cursor; public captionedImagesAdapter (Context context, Cursor cursor) { this.context = context; this.cursor = cursor; } public captionedImagesAdapter.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); CardView cv = (CardView) inflater.inflate(R.layout.card_view, parent, false); return new ViewHolder (cv); } public void onBindViewHolder(ViewHolder holder, int position) { if (cursor.moveToPosition(position)) { return; } String info_text = cursor.getString (0); byte [] info_image = cursor.getBlob(1); Bitmap bitmap = MyDatabaseHelper.getImages(info_image); holder.textView.setText(info_text); holder.imageView.setImageBitmap(bitmap); } public int getItemCount() { return cursor.getCount(); } public static class ViewHolder extends RecyclerView.ViewHolder { private ImageView imageView; private TextView textView; public ViewHolder(CardView view) { super(view); imageView = view.findViewById(R.id.info_image); textView = view.findViewById(R.id.info_text); } } } Database code: package com.myapps.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.ByteArrayOutputStream; import java.util.ArrayList; public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "starbuzz"; private static final int DB_VERSION = 5; private Context context; private ArrayList <Bitmap> bitmapArray; private byte [] byteArray; public MyDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE GROCERY_ITEMS (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "NAME TEXT, " + "IMAGE_RESOURCE_ID BLOB);"); upgradeDatabase(db); } public void upgradeDatabase (SQLiteDatabase db) { convertToBitmap(); byteArray = convertToByte(); addItems(db); } public void convertToBitmap () { Bitmap faan = BitmapFactory.decodeResource(context.getResources(), R.drawable.faan); Bitmap milk = BitmapFactory.decodeResource (context.getResources(), R.drawable.milk); Bitmap egg = BitmapFactory.decodeResource (context.getResources(), R.drawable.egg); Bitmap toilet_tissue = BitmapFactory.decodeResource (context.getResources(), R.drawable.toilet_tissue); Bitmap kitchen_tissue = BitmapFactory.decodeResource (context.getResources(), R.drawable.kitchen_tissue); Bitmap bread = BitmapFactory.decodeResource (context.getResources(), R.drawable.bread); Bitmap potatoe = BitmapFactory.decodeResource (context.getResources(), R.drawable.potatoe); Bitmap onion = BitmapFactory.decodeResource (context.getResources(), R.drawable.onion); Bitmap flour = BitmapFactory.decodeResource (context.getResources(), R.drawable.flour); Bitmap tomatoe = BitmapFactory.decodeResource (context.getResources(), R.drawable.tomatoe); Bitmap corriandor = BitmapFactory.decodeResource (context.getResources(), R.drawable.corriandor); bitmapArray = new ArrayList <Bitmap> (); bitmapArray.add(faan); bitmapArray.add (milk); bitmapArray.add (egg); bitmapArray.add (toilet_tissue); bitmapArray.add (kitchen_tissue); bitmapArray.add (bread); bitmapArray.add (potatoe); bitmapArray.add (onion); bitmapArray.add (flour); bitmapArray.add (tomatoe); bitmapArray.add (corriandor); } public byte [] convertToByte () { ByteArrayOutputStream stream = new ByteArrayOutputStream (); for (Bitmap bitmap : bitmapArray) { bitmap.compress (Bitmap.CompressFormat.PNG, 0, stream); } return stream.toByteArray(); } public static Bitmap getImages (byte [] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } public void addItems (SQLiteDatabase db) { byte faan = byteArray [0]; byte milk = byteArray [1]; byte egg = byteArray [2]; byte toilet_tissue = byteArray [3]; byte kitchen_tissue = byteArray [4]; byte bread = byteArray [5]; byte potatoe = byteArray [6]; byte onion = byteArray [7]; byte flour = byteArray [8]; byte tomatoe = byteArray [9]; byte corriandor = byteArray [10]; insertItems (db, "Faan", faan); insertItems (db, "Milk", milk); insertItems (db, "Egg", egg); insertItems (db, "Toilet Tissue", toilet_tissue); insertItems (db, "Kitchen Tissue", kitchen_tissue); insertItems (db, "Bread", bread); insertItems (db, "Potatoe", potatoe); insertItems (db, "Onion", onion); insertItems (db, "Flour", flour); insertItems (db, "Tomatoe", tomatoe); insertItems (db, "Corriandor", corriandor); } public void insertItems (SQLiteDatabase db, String name, byte image) { ContentValues contentValues = new ContentValues(); contentValues.put ("NAME", name); contentValues.put ("IMAGE_RESOURCE_ID", image); db.insert ("GROCERY_ITEMS", null, contentValues); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("CREATE TABLE GROCERY_ITEMS (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "NAME TEXT, " + "IMAGE_RESOURCE_ID BLOB);"); upgradeDatabase(db); } } RecyclerView code: package com.myapps.myapplication; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class grocery_item extends AppCompatActivity { SQLiteDatabase db; Cursor cursor; protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.item_grocery); accessDataBase(); RecyclerView groceryRecycler = (RecyclerView) findViewById(R.id.grocery_recycler_view); captionedImagesAdapter adapter = new captionedImagesAdapter (this, cursor); GridLayoutManager layoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false); groceryRecycler.setLayoutManager(layoutManager); groceryRecycler.setAdapter (adapter); } public void accessDataBase () { MyDatabaseHelper databaseHelper = new MyDatabaseHelper(this); try { db = databaseHelper.getReadableDatabase(); cursor = db.query ("GROCERY_ITEMS", new String[] {"NAME", "IMAGE_RESOURCE_ID"}, null, null, null, null, null); } catch (SQLiteException e) { e.printStackTrace(); } } } A: You're returning from onBindViewHolder() immediately: if (cursor.moveToPosition(position)) { return; } moveToPosition() returns true on success.
{ "language": "en", "url": "https://stackoverflow.com/questions/63341169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: web.xml SAXParseException error when running a project in glassfish server When I run my project on IntelliJ, it gives me a java.io.IOException: org.xml.sax.SAXParseException error. I can't find the problem. Can someone help me with this error? web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> </web-app> Persistence.xml <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1"> <persistence-unit name="aquadinePU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/aquadine?autoReconnect=true&amp;useSSL=false&amp;allowPublicKeyRetrieval=true" /> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="ruta" /> <property name="hibernate.show_sql" value="true"/> </properties> </persistence-unit> </persistence> The error for web.xml is as follows: java.io.IOException: org.xml.sax.SAXParseExceptionpublicId: http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd; lineNumber: 1; columnNumber: 1; Deployment descriptor file WEB-INF/web.xml in archive [aquadine-jee]. Premature end of file. The error for persistence.xml is as follows: java.io.IOException: org.xml.sax.SAXParseExceptionpublicId: http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd; lineNumber: 1; columnNumber: 1; Deployment descriptor file META-INF/persistence.xml in archive [classes]. Premature end of file. A: We also started getting this Error since a few days. The uri: http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd returns a status code 301 which the SAX Parser cant handle. Our hotfix was to change the schema location in the web.xml to the new file: xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_3_1.xsd A: I changed the validation urls to https so the redirect, which is the problem, will not happen. <? xml version = "1.0" encoding = "UTF-8"?> <persistence version = "2.1" xmlns = "https://xmlns.jcp.org/xml/ns/persistence" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "https://xmlns.jcp.org/xml/ns/persistence https://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> Note: I had this problem with java 7 and glassfish 3, with java 8 and glassfish 4, it works. Another thing, in glassfish 3, I needed to disable the weld xml validations, add the parameter in the glassfish -Dorg.jboss.weld.xml.disableValidating = true
{ "language": "en", "url": "https://stackoverflow.com/questions/56736674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android AsyncTask with JSON Parsing error Error coming in this section: protected void onPostExecute(JSONObject json) { try { // Getting JSON Array user = json.getJSONArray(TAG_USER); JSONObject c = json.getJSONObject(0); String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); Log.i("id",id); } } ------- Webservice Result--- {"GetDataResult":{"ID":8,"Name":"Foo Bar"}} Working Link - http://127.0.0.1/WcfService4/Service1.svc/getData/?key=8 Provide the better solution for solving this. A: It seems you havn't use your JSONArray object JSONArray mainfoodlist = null; tipshealth = json.getJSONArray(TAG_RESPONSE); // looping through All RESPONSE for (int i = 0; i < tipshealth.length(); i++) { JSONObject jsonobj = tipshealth.getJSONObject(i); tipHealth = jsonobj.getString(KEY_HEALTHTIPS); listhealthtips.add(tipshealth.getJSONObject(i).getString("tips")); } A: It seems like that the problem comes from this section: user = json.getJSONArray(TAG_USER); JSONObject c = json.getJSONObject(0); you get a JOSNObject user but you never used it. I guess this is probably what you mean: user = json.getJSONArray(TAG_USER); JSONObject c = user.getJSONObject(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/30836720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image does not display in WinUI3 XAML I am trying to add a picture to my Window in WinUI3 and the image is never rendered. When checking in the live visual tree, the actual size of the image is 0 even though its width and height are set to 200px. Can someone tell me what's wrong with my XAML ? <Window x:Class="ClientWinUI.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:ClientWinUI" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" > <Grid Background="#FF494A51"> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="2*" /> <ColumnDefinition Width="2*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="2*" /> <RowDefinition Height="1*" /> </Grid.RowDefinitions> <Image Stretch="Fill" Width="200" Height="200" Source="Images/logo.png"/> </Grid> </Window> A: Found the bug. I was debugging the package itself and I needed to add the image to the assets found in the package.
{ "language": "en", "url": "https://stackoverflow.com/questions/72452095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return the doubly linked list and remove leaves of the tree? I was working on a SPOJ-like task. The objective was to find the leaves in the binary tree (not necessarily a BST), delete them from the tree and return them as a kind of doubly linked list, using the same structure - TreeNode and no additional imports. For example if the nodes 2, 4 and 3 are deleted from the tree, function returns the firs non-null element of the list: null <- 2 <-> 4 <-> 3 -> null. TreeNode has a value and left and right pointers. I used recursion and nullified the leaves to delete them from the tree and recreated them in a list. To keep adding element to the end of the list efficient, I held the pointer to the last element of the list. This created a well known problem of altering the object passed to the function. Here is my code: public TreeNode getLeaves(TreeNode root) { if(root == null) return null; TreeNode start = new TreeNode(Integer.MIN_VALUE); TreeNode[] end = {start}; getLeaves(root, start, end); return start; } private void getLeaves(TreeNode root, TreeNode start, TreeNode[] end) { if(root == null) return; if(root.left == null && root.right == null) { addToList(root, start, end); root = null; return; } getLeaves(root.left, start, end); getLeaves(root.right, start, end); } private void addToList(TreeNode element, TreeNode start, TreeNode[] end) { if(end[0].value != Integer.MIN_VALUE) { TreeNode t = new TreeNode (element.value); end[0].right = t; t.left = end[0]; end[0] = t; } else { start.value = element.value; } } Deleting the leaves from tree does not work, but the list is returned properly. However, setting the value of "start" TreeNode to minimal int value instead of using null reference bugs me, and so does using the array. Using Atomic Reference would make it more messy IMHO. I'm quite sure that there is a method to do it in much more elegant way (and to delete the leaves properly), probably by changing the approach of assigning start and end TreeNodes. I feel that something is wrong with my approach and/or understanding of the way it all works. Could you please help me turning it into a neat piece of code and explain my bads? A: You have an error in your second GetLeaves function. The statement root = null; sets the value of the local variable root to null, but its parent will keep the reference to the leaf. You will have a much easier time if you add a method bool isLeaf() to TreeNode. I modified your code to something I think might work. private bool isLeaf() { // This method should be in TreeNode return left == null && right == null; } // Also, TreeNode should have an Add(TreeNode) method public TreeNode getLeaves(TreeNode root) { if( root == null ) // check if the whole tree is empty return null; // return something relevant here else if( root.isLeaf() ) return root; //cannot remove this leaf, unfortunately TreeNode leaves = new TreeNode() getLeaves(root, leaves); return leaves; } private void getLeaves(TreeNode current, TreeNode leaves) { // current is guaranteed to be non-null and not a leaf itself. if( current.left.isLeaf() ) { leaves.add(current.left); current.left = null; } else { getLeaves(current.left, leaves); } if( current.right.isLeaf() ) { leaves.add(current.right); current.right = null; } else { getLeaves(current.right, leaves); } } A: David, you are 100% right. Thank you for helping. In case anyone is wondering, here is the most elegant solution I produced so far, including David's improvement. The only thing I'm not sure about is if the addToList method should be static or maybe it's more properly/universal to call it in element's context. public TreeNode getLeaves(TreeNode root) { if(root == null) return null; if(root.isLeaf()) return root; TreeNode[] listEdges = {null, null}; getLeaves(root, listEdges); return listEdges[0]; } private void getLeaves(TreeNode root, TreeNode[] edges) { if(root == null) return; if(root.left != null && root.left.isLeaf()) { addToList(edges, root.left); root.left = null; } if(root.right != null && root.right.isLeaf()) { addToList(edges, root.right); root.right = null; } getLeaves(root.left, edges); getLeaves(root.right, edges); } private static void addToList(TreeNode[] edges, TreeNode element) { if(edges[1] != null) { edges[1].right = element; element.left = edges[1]; edges[1] = element; } else { edges[0] = element; edges[1] = edges[0]; } } public boolean isLeaf() { return this.right == null && this.left == null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/34234157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stopping BackgroundWorker which is searching in database i wrote a code in c# which takes search criteria from user and search in database table and i done this with the help of background worker now while execution if i want to forcefully stop the thread. because if user gets the result and he dont want the search to be performed anymore btnStop_Click(object sender, EventArgs e) { backgroundWorkerSearch.CancelAsync(); } on dowork() if (backgroundWorkerSearch.CancellationPending) { e.Cancel = true; return; } above code doesn't work A: Cancellation pending does only tell the DoWork method that the starting thread want's it to abort. It does not automatically stop anything. See this example of a DoWork method: private void DoWork(object sender, DoWorkEventArgs e){ foreach( ... ) { //do some work if( myBackgroundWorker.CancellationPending ) { return; } } } The other possibility (your case is like this ) private void DoWork(object sender, DoWorkEventArgs e){ //perform a big task towards the database here } That last case does not give you any entry point to check for cancellation requests, so the ony option is to locate the thread and kill it without giving it the chance to shut down in a good manner, and is not a recommended pattern. Your best bet is to divide the work inside DoWork in several batches, and check for cancellation requests between each of the sub tasks.
{ "language": "en", "url": "https://stackoverflow.com/questions/5401755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Symfony user login link in chain user providers I am creating PasswordLess api for my symfony project by following this: https://symfony.com/doc/5.4/security/login_link.html I have multiple firewalls: firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false install: pattern: ^/installer security: false anonymous: true login: pattern: ^/user/(login|reset-request|send-email|check-email|auto-login)$ provider: chain_provider anonymous: true #login_link: # ERROR HERE # check_route: login_check # signature_properties: ['id'] main: pattern: ^/ provider: chain_provider form_login: csrf_token_generator: security.csrf.token_manager check_path: main_security_check login_path: main_security_login use_forward: true logout: path: main_security_logout remember_me: secret: "%env(APP_SECRET)%" name: BAPRM lifetime: 1209600 # stay logged for two weeks samesite: 'lax' anonymous: false But when I try to configure it I get this error: The old authentication system is not supported with login_link. How can I make it work, what I am missing here. I am using Symfony 5.4 Thanks. A: As mentionned in the documentation you have to enable the new authenticator system to use login links. Login links are only supported by Symfony when using the authenticator system. Before using this authenticator, make sure you have enabled it with enable_authenticator_manager: true in your security.yaml file. So modify your security.yaml to add: enable_authenticator_manager: true If you do not use it, for example if you use guards, you will have to replace it with the new system.
{ "language": "en", "url": "https://stackoverflow.com/questions/74124478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Custom section header views I have a listview which should contain different types of data. I want to group them in sections. Requirement is that each section header should have different layout for e.g. listview should have following structure. DATA A price quanitity weight color PICTURE 123.0 10 1 Green PICTURE 190.0 12 2 Orange DATA B price purity weight PICTURE 133.0 100% 10 PICTURE 142.0 92% 15 DATA C price quanity weight PICTURE 103.0 10 12 How to display such data in listview. As you can see that each section might have different section headers. Does anybody knows about such listview? Currently I am using http://code.google.com/p/android-amazing-listview/ but it only allows to have fixed header view for all sections. If someone can help me modifying it or tell me anyother listview that does it then it will be real help. Thanks A: You can use different viewTypes that means that you can use different types of layout for different types of view in your listview. Simply ovverride getViewType(int pos) in your adapter. And you can set different layouts in you getView like this if (getItemViewType(position) == VIEW_TYPE_LEFT) { convertView = inflater.inflate(R.layout.image_bubble_left, null); holder.drawable = (NinePatchDrawable) convertView.findViewById(R.id.bubble_left_layout).getBackground(); holder.bubbleLayout = (RelativeLayout)convertView.findViewById(R.id.bubble_left_layout); } else { convertView = inflater.inflate(R.layout.image_bubble_right, null); holder.drawable = (NinePatchDrawable) convertView.findViewById(R.id.bubble_right_layout).getBackground(); holder.bubbleLayout = (RelativeLayout)convertView.findViewById(R.id.bubble_right_layout); } But have you considered using a tablelayout? A: i think this link will help you. Here is a copy paste example. It just works. Is a listview with headers and multiple views in each row. Give it a try. http://w2davids.wordpress.com/android-sectioned-headers-in-listviews/
{ "language": "en", "url": "https://stackoverflow.com/questions/8724856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Open default browser when link opens a new window I am using Android WebView and I have shouldoverrideurlloading so that it doesn't open up the default browser when navigating within the browser. Is there a way to get it so it only opens the default browser when the link is one that opens a new page like: target="_blank"??
{ "language": "en", "url": "https://stackoverflow.com/questions/5764870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: LINQ include doesn't include related entities when parameters are passed I have the following code. When I don't give the param "current" and "version" so it only run the first line, the lstFile variable at the end contains the file with it's related jobs. If a give the "current" parameter or the "version" parameter, files are returned without the related Jobs. But since I include the Jobs in the first step, why does the related Jobs are lost in the process? And by the way, lazy loading is Off, that's why I need to do the include. IQueryable<File> filteredFiles = entities.Files.Include("Jobs"); if (!String.IsNullOrWhiteSpace(current)) { bool bActive = current == "1" ? true : false; filteredFiles = from f in filteredFiles join j in entities.Jobs on f.IDFile equals j.IDFile where j.Active == bActive select f; } if (!String.IsNullOrWhiteSpace(version)) { filteredFiles = from f in filteredFiles join j in entities.Jobs on f.IDFile equals j.IDFile where j.Version == version select f; } List<File> lstFile = filteredFiles.Distinct().ToList(); A: The Include merely means that the Jobs property isn't going to defer execution when the query is executed and that each record is going to also return all of the related Jobs records. In your joins you're actually filtering out the files that don't have jobs that meet the given criteria. You aren't filtering out the jobs of those files, you're filtering out all of the files that have those jobs. The Include won't prevent those files from being filtered out. A: After Eren Ersönmez point me out that there was an Include function for the IQueryable interface, I decided to try to upgrade my EF4 to EF6 and with this update, the function was available! This is not clear in the documentation from Microsoft. If that can help someone else, I have followed this tutorial on how to update from EF4 to EF6.
{ "language": "en", "url": "https://stackoverflow.com/questions/26106471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Read 2D array in C++ using boost::spirit I would like to read a simple 2D int array (whitespace separated) as here: qi::phrase_parse(b, e, +qi::int_ % qi::eol, qi::space - qi::eol, vectors) There are two differences, though: * *I want to put it into a 1D std::vector, line by line, without separating *If two lines have a different amount of ints, this shall be recognized as a parsing error. Is it possible to do this as a one liner, e.g. without writing my own parser? Just as simple as in the link mentioned above? A: Assuming you meant the Spirit version ("as a one liner"), below is an adapted version that adds the check for number of elements. Should you want more control (and on the fly input checking, instead of 'in hindsight') then I recommend you look at another answer I wrote that shows three approaches to do this: * *Boost::Spirit::QI parser: index of parsed element . #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <boost/spirit/include/karma.hpp> namespace spirit = boost::spirit; namespace qi = boost::spirit::qi; namespace karma = boost::spirit::karma; int main() { std::cin.unsetf(std::ios::skipws); spirit::istream_iterator b(std::cin), e; std::vector<std::vector<int> > vectors; if (qi::phrase_parse(b, e, +qi::int_ % qi::eol >> qi::eoi, qi::blank, vectors)) { std::cerr << "Parse failed at '" << std::string(b,e) << "'\n"; return 255; } // check all rows have equal amount of elements: const auto number_of_elements = vectors.front().size(); for (auto& v : vectors) if (v.size() != number_of_elements) std::cerr << "Unexpected number of elements: " << v.size() << " (expected: " << number_of_elements << ")\n"; // print the data for verification std::cout << karma::format(karma::right_align(8)[karma::auto_] % ',' % '\n', vectors) << std::endl; return 0; } The karma bits are not necessary (they're just there to output the whole thing for demonstration). UPDATE To build in more active error checking, you could do: int num_elements = 0; bool ok = qi::phrase_parse(b, e, (+qi::int_) [ phx::ref(num_elements) = phx::size(qi::_1) ] >> *(qi::eol >> qi::repeat(phx::ref(num_elements)) [ qi::int_ ]) >> *qi::eol, qi::blank, vectors); Which uses qi::repeat to expect the num_elements number of elements on subsequent lines. You can just store that into a 1-dimensional array: #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <boost/spirit/include/karma.hpp> namespace qi = boost::spirit::qi; namespace phx = boost::phoenix; namespace karma = boost::spirit::karma; int main() { std::cin.unsetf(std::ios::skipws); boost::spirit::istream_iterator b(std::cin), e; //std::vector<std::vector<int> > vectors; std::vector<int> vectors; int num_elements = 0; bool ok = qi::phrase_parse(b, e, (+qi::int_) [ phx::ref(num_elements) = phx::size(qi::_1) ] >> *(qi::eol >> qi::repeat(phx::ref(num_elements)) [ qi::int_ ]) >> *qi::eol, qi::blank, vectors); std::cout << "Detected num_elements: " << num_elements << "\n"; if (!ok) { std::cerr << "Parse failed at '" << std::string(b,e) << "'\n"; return 255; } if (b!=e) std::cout << "Trailing unparsed: '" << std::string(b,e) << "'\n"; // print the data for verification std::cout << karma::format_delimited(karma::columns(num_elements)[+karma::int_], ' ', vectors) << std::endl; return 0; } Note the use of karma::columns(num_elements) to split the output into the correct number of columns per row.
{ "language": "en", "url": "https://stackoverflow.com/questions/16119548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaScript Refactoring / Avoid Repitition I need to refactor this to avoid code repetition. $('#showmore-towns').toggle( function() { $('.popularTownsAdditional').show(); console.log(this); $('#showmore-town .showless').show(); $('#showmore-town .showmore').hide(); $('#showmore-town').removeClass('sd-dark28').addClass('sd-dark28down'); return false; }, function() { $('.popularTownsAdditional').hide(); $('.showless').hide(); $('.showmore').show(); $('#showmore-towns').addClass('sd-dark28').removeClass('sd-dark28down'); }); $('#showmore-cities').toggle( function() { $('.popularCitiesAdditional').show(); $('#showmore-cities .showless').show(); $('#showmore-cities .showmore').hide(); $('#showmore-cities').removeClass('sd-dark28').addClass('sd-dark28down'); return false; }, function() { $('.popularCitiesAdditional').hide(); $('#showmore-cities .showless').hide(); $('#showmore-cities .showmore').show(); $('#showmore-cities').addClass('sd-dark28').removeClass('sd-dark28down'); }); basically, it shows the same functionality but only on different divs with different IDs. A: Probably just need to reference a named function or two instead of the anon ones. function showStuff(typeToShow) { $('.popular' + typeToShow + 'Additional').show(); $('#showmore-' + typeToShow + .showless').show(); $('#showmore-' + typeToShow + .showmore').hide(); $('#showmore-' + typeToShow).removeClass('sd-dark28').addClass('sd-dark28down'); return false; } function hideStuff(typeToHide) { $('.popular' + typeToHide + 'Additional').hide(); $('#showmore-' + typeToHide + .showless').hide(); $('#showmore-' + typeToHide + .showmore').show(); $('#showmore-' + typeToHide ).addClass('sd-dark28').removeClass('sd-dark28down'); } NOTE: a) You could probably make these methods a bit slicker, but you get the idea! NOTE: b) You'd need to rename '#showmore-town' to '#showmore-towns' (with an S) if you want to use the substitution suggested. Then in your toggle you could reference these functions: $('#showmore-towns').toggle(showStuff(towns), hideStuff(towns)); $('#showmore-cities').toggle(showStuff(cities), hideStuff(cities)); A: I mean...if it's always going to start with #showmore-...we can work it down $('[id^=showmore-]').toggle( function() { var id = $(this).prop('id'); id = id.split('-')[1]; var upperID = id.charAt(0).toUpperCase() + id.slice(1); $('.popular'+upperID+'Additional').show(); $('#showmore-'+id+' .showless').show(); $('#showmore-'+id+'.showmore').hide(); $('#showmore-'+id).removeClass('sd-dark28').addClass('sd-dark28down'); return false; }, function() { var id = $(this).prop('id'); id = id.split('-')[1]; var upperID = id.charAt(0).toUpperCase() + id.slice(1); $('.popular'+upperID+'Additional').hide(); $('#showmore-'+id+' .showless').hide(); $('#showmore-'+id+' .showmore').show(); $('#showmore-'+id).addClass('sd-dark28').removeClass('sd-dark28down'); }); A: you could do: (function() { $('#showmore-towns').toggle( function() { showmorelessOn('#showmore-town'); }, function() { showmorelessOff('#showmore-town'); } ); $('#showmore-cities').toggle( function() { showmorelessOn('#showmore-town'); }, function() { showmorelessOff('#showmore-town'); } ); var showmorelessOn = function(context) { $('.popularCitiesAdditional').show(); $('.showless', context).show(); $('.showmore', context).hide(); $(context).removeClass('sd-dark28').addClass('sd-dark28down'); return false; }; var showmorelessOff = function(context) { $('.popularCitiesAdditional').hide(); $('.showless', context).hide(); $('.showmore', context).show(); $(context).addClass('sd-dark28').removeClass('sd-dark28down'); }; })(); though I agree, could perhaps be better served on codereview.stackexchange.com A: I would do this almost entirely in the CSS. Only use .toggleClass() and determine what is shown and what is hidden in the CSS. A: (function() { $('#showmore-towns').toggle( function() { showmorelessOn.call($('#showmore-town')); }, function() { showmorelessOff.call($('#showmore-town')); } ); $('#showmore-cities').toggle( function() { showmorelessOn.call($('#showmore-town')); }, function() { showmorelessOff.call($('#showmore-town')); } ); var showmorelessOn = function() { $('.popularCitiesAdditional').show(); $('.showless', this).show(); $('.showmore', this).hide(); $(this).removeClass('sd-dark28').addClass('sd-dark28down'); return false; }; var showmorelessOff = function() { $('.popularCitiesAdditional').hide(); $('.showless', this).hide(); $('.showmore', this).show(); $(this).addClass('sd-dark28').removeClass('sd-dark28down'); }; })(); (function() { $('#showmore-towns').toggle( function() { showmoreless(); } ); $('#showmore-cities').toggle( function() { showmoreless(); } ); var showmoreless = function() { if(this.hasClass('sd-dark28'){ $('.popularCitiesAdditional').show(); $('.showless', this).show(); $('.showmore', this).hide(); $(this).removeClass('sd-dark28').addClass('sd-dark28down'); } else { $('.popularCitiesAdditional').hide(); $('.showless', this).hide(); $('.showmore', this).show(); $(this).addClass('sd-dark28').removeClass('sd-dark28down'); } }.bind($('#showmore-town')); })();
{ "language": "en", "url": "https://stackoverflow.com/questions/11733139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating a 2D array in javascript please i am new to javascript and i want to create a two dimensional array. this is the code i have: var locations = new Array(track); for(var j = 0; j < track; j++){ locations[j] = new Array(); locations[j] = ['test', 'test', 'test', 'test'] } when i try to output locations, i have only one row of tests. please what could be the problem, because i am expecting track rows of test. thanks. A: If you want something to print all the rows you have to keep you what you have already printed so you have to do something like this : for(var j = 0; j < 10; j++) { document.getElementById("myResults").innerHTML = document.getElementById("myResults").innerHTML + locations[j] + "<br>"; } You can see it there: http://jsfiddle.net/Ba8TU/
{ "language": "en", "url": "https://stackoverflow.com/questions/19440700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What type of function is this? const xhr = new XMLHttpRequest(), method = "GET", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.onreadystatechange = function () { // In local files, status is 0 upon success in Mozilla Firefox if(xhr.readyState === XMLHttpRequest.DONE) { var status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // The request has been completed successfully console.log(xhr.responseText); } else { // Oh no! There has been an error with the request! } } }; xhr.send(); This code represent an XHR request and response. I was watching a tutorial on AJAX and xhr.onreadystatechange was described as an object property. I know that function expressions are anonymous functions assigned to variables but what about anonymous functions assigned to object properties. What is the name of this kind of function that is called when an object property updates? This hasn’t really been taught in basic javascript or ES6 from what I can see. A: The function that you are assigning to xhr.onreadystatechange is called an event handler. This event handler function gets executed when the actual event 'readystatechange' gets fired in your case. A: That is a event handler which differs a little bit from a callback.
{ "language": "en", "url": "https://stackoverflow.com/questions/70871711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress filtering custom post type taxonomy I've been following this guide: https://rudrastyh.com/wordpress/ajax-post-filters.html#comment-908. I've got a custom post type called "project" and a taxonomy called "producten". What i'm trying to achieve is that the filters categories under the taxonomies get called and the user can filter the posts by using those taxonomies. I did get it working with a dropdown, but what i want are filters. I've created these by using checkboxes which do work, it's just that when i actually try to filter, all posts get shown, no matter which filter i select. The code is used on a random template called test.php. I feel like there's some really obvious mistake i'm making but i can't seem to figure it out. The code in test.php: <div class="container"> <div class="row"> <div class="col-12"> <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter"> <?php if( $terms = get_terms( array( 'taxonomy' => 'producten' ) ) ) : echo '<div class="project-filters button-group-pills text-center" data-toggle="buttons">'; foreach( $terms as $term ) : echo '<label class="btn btn-transparent" for="product_' . $term->term_id . '"><input type="checkbox" id="product_' . $term->term_id . '" name="product_' . $term->term_id . '" />' . $term->name . '</label>'; endforeach; echo '</div>'; endif; ?> <button>Pas filters toe</button> <input type="hidden" name="action" value="myfilter"> </form> <div id="response"></div> </div> </div> The code in functions.php: add_action('wp_ajax_myfilter', 'misha_filter_function'); add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function'); function misha_filter_function(){ $args = array( 'post_type' => 'project', 'orderby' => 'date', // we will sort posts by date 'order' => $_POST['date'], // ASC or DESC 'posts_per_page' => '-1' ); if( $terms = get_terms( array( 'taxonomy' => 'producten' ) ) ) : $all_terms = array(); foreach( $terms as $term ) { if( isset( $_GET['product_' . $term->term_id ] ) && $_GET['product_' . $term->term_id] == 'on' ) $all_terms[] = $term->slug; } if( count( $all_terms ) > 0 ) { $args['tax_query'] = array( array( 'taxonomy' => 'producten', 'field' => 'slug', 'terms'=> $all_terms ) ); } endif; $query = new WP_Query( $args ); if( $query->have_posts() ) : echo '<div class="row projecten-wrapper">'; while( $query->have_posts() ): $query->the_post(); echo '<div class="col-12 col-md-6 col-lg-4 project">'; echo '<div class="project-wrapper"> <a href="' . get_the_permalink() . '"> <div class="project-header"> <div class="project-bottom"> <div class="project-text">'; echo '<div class="project-title"><span>'; echo the_title(); echo '</span> </div> <div class="project-subtitle"><p>'; echo the_excerpt(); echo '</p> </div> </div> <div class="project-arrow"> <div class="svg-wrapper"> <svg xmlns="http://www.w3.org/2000/svg" width="15.528" height="27.359" viewBox="0 0 15.528 27.359"> <g id="Group_5" data-name="Group 5" transform="translate(2568.865 -660.337) rotate(90)"> <g id="Group_2" data-name="Group 2" transform="translate(660.337 2553.337)"> <rect id="Rectangle_11" data-name="Rectangle 11" width="19.346" height="2.614" rx="1.307" transform="translate(0 13.679) rotate(-45)" fill="#fff"/> <rect id="Rectangle_12" data-name="Rectangle 12" width="19.346" height="2.614" rx="1.307" transform="translate(25.51 15.528) rotate(-135)" fill="#fff"/> </g> </g> </svg> </div> </div> </div> <div class="image-wrapper">'; if( has_post_thumbnail() ): echo get_the_post_thumbnail(); endif; echo '<div class="layer gradient-1"> </div> <div class="layer"> </div> </div> </div> </a> </div> </div>'; endwhile; echo '</div>'; wp_reset_postdata(); else : echo 'No posts found'; endif; die(); } And the jQuery function: jQuery(function($){ $('#filter').submit(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), // form data type:filter.attr('method'), // POST beforeSend:function(xhr){ filter.find('button').text('Processing...'); // changing the button label }, success:function(data){ filter.find('button').text('Apply filter'); // changing the button label back $('#response').html(data); // insert data } }); return false; }); }); A: Actually found the solution after hours of trying. Changing $_GET to $_POST did the trick. if( isset( $_GET['product_' . $term->term_id ] ) && $_GET['product_' . $term->term_id] Changed to: if( isset( $_POST['product_' . $term->term_id ] ) && $_POST['product_' . $term->term_id]
{ "language": "en", "url": "https://stackoverflow.com/questions/63132403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET How to access multiple form labels text property with foreach loop I have a form runat= "server" with id = "myform" . It is a profile page with lots of labels. I am getting their input text from SQL database. But if the SQL data base have null value, then i wish their text get changed to "Not Specified". For such reason i am using following code, but it is not working. foreach (Control item in myform.Controls) { Label lbl = null; bool labelIsEmpty = false; try { lbl = (Label)item; labelIsEmpty = (lbl.Text == string.Empty && lbl != null); } catch { } if (labelIsEmpty) { lbl.Text = "Not Specified"; } } A: myform.Controls will gives you a collection that contains all controls withing the container( not only labels). So you have to check for the type for control while iterating the collection in order to avoid throwing exception. In the additional comment you ware specify that label has default text "Label" so you need to include this also in the condition. The whole scenario can be implemented like the following: foreach (Control item in myform.Controls) { if (item is Label) { var lbl = (Label)item; bool labelIsEmpty = false; try { lbl = (Label)item; labelIsEmpty = (lbl != null && lbl.Text == string.Empty && lbll.Text!="Label"); } catch { //Throw error message } if (labelIsEmpty) { lbl.Text = "Not Specified"; } } } Note :- You need to reorder the conditions to avoid exception. Check for string.Empty should be comes after check for control is null. Because AND will not check for second condition if first one is false, lbl.Text will throw NullReferenceException if lbl is null A: foreach (Control item in myform.Controls) { if (item is Label) { var lbl = (Label)item; bool labelIsEmpty = false; try { lbl = (Label)item; labelIsEmpty = (lbl != null && (lbl.Text == string.Empty || lbl.Text == "Label")); } catch { //Throw error message } if (labelIsEmpty) { lbl.Text = "Not Specified"; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/35691661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Accessing / processing ArrayBuffer @ http client (websocket connection, JavaScript) I have a websocket connection between • Nodejs server (+ socket.io) • Browser A message is emitted from the server to the browser (Udp message from an Arduino) udpSocket.on("message", function (msg, rinfo) { for (i = 0; i < msg.length; i++) { console.log(msg.readInt8(i)); } console.log(""); io.sockets.emit('message', msg); }); Code in the browser (index.html): A) I started with: socket.on('message', function(message) { document.getElementById("ko1").innerHTML = message; }) <p> Arduino sends: </p> <p id="ko1"> <br> Result in browser : [object ArrayBuffer] My conclusion : message is coming in, but must be handled in another way. B) Research learned that I have to use a DataView on the Array Buffer (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). My code: socket.on('message', function(message) { var uint8 = new Uint8Array(message); document.getElementById("ko1").innerHTML = uint8[0]; }) Result : no data printed to the browser Question: what am I doing wrong? I also tried other Data Views, but no success. It’ s driving me mad. Please help.
{ "language": "en", "url": "https://stackoverflow.com/questions/28130571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to get data from database I have a doubt. I need to get the data from the sever twice every time when I load a page, one to render the HTML and another one to get the data for client side (javascript). So I don't know exactly what it's the best way and fastest. I was trying to implement a session object and store the data once using joinedload loading technique. When the data is in the client side, to kill the session object. Another one it's to call the database twice. I don't know which one is faster and better because I don't know if the database or server stores the first call in memory. If so it's not like to call the database twice, right? And if the second choice is better which loading technique (joinedload, eagerload or subqueryload) is better to use. Every call could be a bunch of data. Any help could be really useful. Thanks in advance! A: I'm not really sure about all this stuff you asked, so I'll try 2 different scenarios. * *If the data you need to display the html and data needed for the javascript is the same - you're doing it very wrong. All you need to do is to query the db only for the html, then structure the data needed for javascript in hidden fields, then, on client side, query the html's hidden fields with javascript and use the data onward. *If the data sets are different than you'll probably need an ajax request from the client side after the html is displayed. That is, an additional http request. I say you close the db connection after the first call, and then reopen again with the next http request. Every http request is on its own, you'll need to take care with opening/closing connections inside a single request. [That is, if you don't use pooling, but that is another issue]
{ "language": "en", "url": "https://stackoverflow.com/questions/4047942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting user programmatically in ASP.NET MVC5 I want to log user programatically in ASP.NET MVC5. I'm setting auth cookies like this: FormsAuthentication.SetAuthCookie(username, true); I thouth it will be enough. But then I want to check value of Request.IsAuthenticated and it is always false. Also when I'm checking value of User.Identity.Name I'm getting empty string, not the username I passed earlier. What should I do to make this work and set this values correctly? EDIT: One more thing. I'm not using any login form, I'm passing user data (login and token) from different application. A: Make sure form Athentication is enabled in your web.config file. <system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> ... </system.web> A: MVC5 comes with Identity instead of the older SimpleMembership and ASP.NET Membership. Identity doesn't use forms auth, hence why what you're doing has no effect. To log a user in via Identity, first, you need an actual user instance, which you can get by doing something like: var userManager = new UserManager<ApplicationUser>(context); var user = userManager.FindByName(username); Then if you have a valid user (user != null), you need to generate a claims identity for that user via: var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); Finally, you can use that identity to sign the user in: var authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity); (If you want a persistent login, change that to true)
{ "language": "en", "url": "https://stackoverflow.com/questions/24637037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to carry data of a variable to the rest of the same page? It really is easy for me to do it in the following way: if(mysqli_num_rows($result) > 0){ while ($row = mysqli_fetch_array($result)) { $id_product = $row['id_courses']; $product = $row['product']; $title = $row['title']; $subtitle = $row['subtitle']; $price = $row['price']; } } Then later only print the value of the variable on any part of the page as follows: echo $product; How can I do the same with an object-oriented query? like the previous query, this query also works, I perform the same procedure and print the value correctly: echo $product; but it is correct that this code while ($stmt->fetch()) {} is left empty in the following query $stmt->bind_param("i",$active); $stmt->execute(); $stmt->bind_result( $id_product,$product,$subtitle,$price); while ($stmt->fetch()) { } A: Just get rid of while. It was useless with your old approach and become harmful with second one. You have to understand that this while thing is not some obligatory part of the database interaction but the way to get multiple rows. But since you are fetching only one row, you shouldn't use while at all. Your first code block should be $result = mysqli_query(...); $row = mysqli_fetch_array($result); $id_product = $row['id_courses']; ... and the second one as well $stmt->bind_param("i",$active); $stmt->execute(); $stmt->bind_result( $id_product,$product,$subtitle,$price); $stmt->fetch(); in the first block you saved variables manually inside while, and thet's why they were available outside the loop. But in the second they are populated directly by fetch() method and therefore it makes them all empty on the last iteration when no more data left.
{ "language": "en", "url": "https://stackoverflow.com/questions/46783185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AC_FL_Runcontent is not defined , Exadel Fiji I am using Exadel-Fiji 1.0, Richfaces 3.3.3, Jboss 4.3 -EAP, Seam 2.1.0, JSF-1.2_09 When I try to render a exadel fiji line chart , the page just throws up a blank screen and the firefox error console says AC_FL_Runcontent is not defined A: I found the solution. I had the following code in my web.xml. I had to comment it out to get it working <context-param> <param-name>org.richfaces.LoadScriptStrategy</param-name> <param-value>NONE</param-value> </context-param> A: This script error is because one of the fiji related js file is missing in your jsf page. Please add the following script in your xhtml/jsf page to resolve this issue: <script type="text/javascript" src="/[your-application-context-name]/a4j/g/3_3_1.CR1com/exadel/fiji/renderkit/html/AC_OETags.js.jsf" /> Before testing this in your application, please check that you are able to view Javascript with your browser using the following URL: http://[url]:8080/[your-application-context-name]/a4j/g/3_3_1.CR1com/exadel/fiji/renderkit/html/AC_OETags.js.jsf or http://[url]:8080/your-application-context-name/a4j/g/3_3_1.CR1com/exadel/fiji/renderkit/html/AC_OETags.js If you are able to see the script content in your browser, your problem has been resolved, and there will be no need to comment the web.xml changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/5081325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel VBA Macro MsgBox auto converts number to Scientific notation, how do I stop this? I am trying to get the current date into milliseconds so I can compare it to the AD "LastLogon" time stamp. The problem is that the current date automatically becomes scientific notation instead of the 18 digit number I am in need of. How do I force it to display all digits? Dim currentDate currentDate = Now * (8.64 * 10 ^ 11) + 109205 'MsgBox (DateAdd("d", -90, Now)) MsgBox (currentDate) A: MsgBox( Format(currentDate, "#0")) or other format you prefer A: Dim currentDate currentDate = Now * (8.64 * 10 ^ 11) + 109205 'MsgBox (DateAdd("d", -90, Now)) MsgBox (Format(currentDate(), "MM dd, yyy")) MsgBox (Format(Now(), "MM dd, yyy")) Now() displays a date currentDate is an over flow. How to format date in VBA?
{ "language": "en", "url": "https://stackoverflow.com/questions/20704966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Red arrows on line numbers codelite Just downloaded codelite, when I try to include iostream I get a red arrow on that line when hovered over it says file not found. It doesn't cause any warnings or errors however. I have tried reinstalling. If I include the string library I don't get the red arrows on it . Any help is appreciated they are very annoying. A: Select 'Plugins'->'Language Server'->'Settings' and uncheck the box that says 'Display Diagnostics' at the bottom of the page then click OK.
{ "language": "en", "url": "https://stackoverflow.com/questions/62665634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Failing to run Rake-Task in Textmate I'm starting to write Ruby code for Chef using Textmate 1.5.11, and need some help with an error i'm getting when attempting to run tasks from a RakeFile. When I try to run Bundles->Ruby->rake->run rake task, I'm expecting to be prompted for which task i'd like to run from my rakefile. Instead, I'm getting the following error: /opt/chef/embedded/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in require': cannot load such file -- run_rake_task (LoadError) from /opt/chef/embedded/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:inrequire' from /Applications/TextMate.app/Contents/SharedSupport/Bundles/Ruby.tmbundle/Support/RakeMate/rake_mate.rb:7:in `' Any help greatly appreciated. Thank you A: See Textmate + RVM + Rake = Rake not using expected gem environment for some answers about this particular problem, and some advice on how to diagnose your own situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/18285114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create a where condition on a sub table in LINQ This is in response to this question in the answers section of another question. I have a collection of Orders, each Order a collection of OrderItems, and each OrderItem has a PartId. Using LINQ how do I implement the following SQL statements: 1) Select all the orders that have a specific part ID SELECT * FROM Order WHERE Id in (SELECT OrderId FROM OrderItems WHERE PartId = 100) 2) Select the Order.OrderNumber and OrderItem.PartName SELECT Order.OrderNumber, OrderItem.PartName FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId WHERE OrderItem.partId = 100 3) SELECT the Order.OrderNumber and the whole OrderItem detail: SELECT Order.OrderNumber, OrderItem.* FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId WHERE OrderItem.partId = 100 A: Actual code should be 1) var orders = from o in Orders where o.OrderItems.Any(i => i.PartId == 100) select o; The Any() method returns a bool and is like the SQL "in" clause. This would get all the order where there are Any OrderItems what have a PartId of 100. 2a) // This will create a new type with the 2 details required var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new() { o.OrderNumber, i.PartName } The two from clauses are like an inner join. 2b) // This will populate the OrderItemSummary type var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new OrderItemSummary() { OriginalOrderNumber = o.OrderNumber, PartName = i.PartName } 3) // This will create a new type with two properties, one being the // whole OrderItem object. var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new() { OrderNumber = o.OrderNumber, Item = i } Since "i" is an object of Type OrderItem, Item is create as an OrderItem.
{ "language": "en", "url": "https://stackoverflow.com/questions/648782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Use MySQL Flask connection in different python file i have a app.py with: from flask import FlasK from flask_mysqldb import MySQL # Objeto Flask app = Flask(__name__) # Secret key app.secret_key = "appLogin" # BD config app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'xxx' app.config['MYSQL_PASSWORD'] = 'xxxx' app.config['MYSQL_DB'] = 'feedlotdb' # Obj MySQL mysql = MySQL(app) @app.route('/register', methods=["GET", "POST"]) def register(): # USE BD sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)" cur = mysql.connection.cursor() cur.execute(sQuery, (mail, password, name)) mysql.connection.commit() QUESTION: I put part of the code above How can I take "/Register" and encapsulate the user code there in a file like user.py and use the same sql.connection? thx A: you can create user.py and import mysql and app users.py from app import mysql import app from flask import Blueprint, render_template, abort users_bp = Blueprint('users_bp', __name__) @users_bp.route('/register', methods=["GET", "POST"]) def register(): # USE BD sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)" cur = mysql.connection.cursor() cur.execute(sQuery, (mail, password, name)) mysql.connection.commit() register blueprint in main app :- from users import users_bp app.register_blueprint(users_bp, url_prefix='/users')
{ "language": "en", "url": "https://stackoverflow.com/questions/60659440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving average that takes into account NAs in value and gaps in available dates I'm working with a time series that spans 2008 to 2015, but am restricting attention to the months of March to August in each year. To further complicate the matter, some values have been marked NA. Here's what a subset (not sorted by date) of the df looks like: Date Value Site 1 2008-08-20 NA Kenya 2 2008-08-29 12.954 Kenya 3 2008-08-18 29.972 Kenya 4 2008-08-16 5.080 Kenya 5 2009-04-21 3.048 Kenya 6 2009-04-22 12.954 Kenya Probably an unimportant detail since subsetting is pretty straightforward, but in the interest of clarifying the purpose of the Site column, I'll mention there are five sites in all with time series data over the same span. I want to add a column Value10 that gives a 10-day moving average. I've found this can be easily accomplished using one of several packages such as zoo or TTR, but I want the moving average to be sensitive to the date and site so that it * *generates an NA for the day if any one of the previous 10 values produces an NA *generates an NA for the day when the previous 10 values include a jump in the Date, e.g. going from August of 2008 to March of 2009. *is sensitive to which Site's data it's acting on A: The data in the question was replicated for Congo and we use a width of 2 instead of 10 so we can run this without having a trivial result of all NA: # data for DF Lines <- " Date Value Site 2008-08-20 NA Kenya 2008-08-29 12.954 Kenya 2008-08-18 29.972 Kenya 2008-08-16 5.080 Kenya 2009-04-21 3.048 Kenya 2009-04-22 12.954 Kenya 2008-08-20 NA Congo 2008-08-29 12.954 Congo 2008-08-18 29.972 Congo 2008-08-16 5.080 Congo 2009-04-21 3.048 Congo 2009-04-22 12.954 Congo" # set up DF, convert Date column to "Date" class DF <- read.table(text = Lines, header = TRUE) DF$Date <- as.Date(DF$Date) Sort the rows and use ave to perform the rolling mean by Site and year/month: # sort rows o <- order(DF$Site, DF$Date) DF <- DF[o, ] # perform rolling mean library(zoo) # w <- 10 w <- 2 roll <- function(x) rollapplyr(c(rep(NA, w-1), x), w, mean) DF$mean <- ave(DF$Value, DF$Site, as.yearmon(DF$Date), FUN = roll) This gives: > DF Date Value Site mean 10 2008-08-16 5.080 Congo NA 9 2008-08-18 29.972 Congo 17.526 7 2008-08-20 NA Congo NA 8 2008-08-29 12.954 Congo NA 11 2009-04-21 3.048 Congo NA 12 2009-04-22 12.954 Congo 8.001 4 2008-08-16 5.080 Kenya NA 3 2008-08-18 29.972 Kenya 17.526 1 2008-08-20 NA Kenya NA 2 2008-08-29 12.954 Kenya NA 5 2009-04-21 3.048 Kenya NA 6 2009-04-22 12.954 Kenya 8.001 UPDATES Rearranged presentation and added changed ave line to use yearmon.
{ "language": "en", "url": "https://stackoverflow.com/questions/32695062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add prefix to img src with Javascript/JQuery how can I add a prefix to every img src? <div id="div_1"> <h1> Title 1 </h1> <div><img src="blah.jpg" /></div> <div><p> Lorem Ipsum </p></div> </div> <div id="div_2"> <h1> Title 2 </h1> <div><img src="blah2.jpg" /></div> <div><p> Lorem Ipsum </p></div> </div> <div id="div_3"> <h1> Title 3 </h1> <div><img src="blah3.jpg" /></div> <div><p> Lorem Ipsum </p></div> </div> Every img src should look like this: <img src="prefix/blah.jpg" /> <img src="prefix/blah2.jpg" /> <img src="prefix/blah3.jpg" /> A: jQuery: Using jQuery to change all images on page http://jsfiddle.net/aamir/FnPd5/ $('img').each(function(){ this.src='prefix/'+this.src }) jQuery way to find images on in divs starting with div_: http://jsfiddle.net/aamir/FnPd5/2/ jQuery("[id^='div_']").each(function(){ var img = $(this).find('img')[0]; img.src='prefix/'+img.src }) Vanilla Javascript Vanilla Javascript: http://jsfiddle.net/aamir/FnPd5/1/ var items = document.getElementsByTagName("img"); for (var i = items.length; i--;) { var img = items[i]; img.src='prefix/'+img.src; } Vanilla Javascript to find images on in divs starting with div_: http://jsfiddle.net/aamir/FnPd5/3/ var divs = document.getElementsByTagName("div"); for(var i = 0; i < divs.length; i++) { if(divs[i].id.indexOf('div_') == 0) { var img = divs[i].getElementsByTagName("img")[0]; img.src='prefix/'+img.src; } } A: DEMO HERE $("[id^='div_'] img").each(function(){ var src = $(this).attr("src"); var newSrc="prefix/"+src; $(this).attr("src",newSrc) }) A: $(function(){ $('img').each(function(i,e){ $(e).attr('src','prefix/'+$(e).attr('src')); }); }); A: My solution based on your code: $(document).ready(function(){ $('div div img').each(function(){ var imagen = $(this).attr('src') ; $(this).attr("src","prefix/"+imagen); }); }); Working fiddle: http://jsfiddle.net/robertrozas/kR5ZW/ A: Try this solution. $('img').each(function(){ var imgSrc = $(this).attr('src') $(this).attr('src','prefix/'+imgSrc); }) Fiddle Demo A: Another option: $('img').attr('src', function(ii, oldSrc) { return 'prefix/' + oldSrc; }); A: function addPrefixToImg(prefix) { $( "img" ).each(function( index ) { this.src = prefix + this.src; }); } addPrefixToImg('prefix/'); you can test on http://jsfiddle.net/f32MQ/
{ "language": "en", "url": "https://stackoverflow.com/questions/23765436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "OleDbException was unhandled...Syntax error in From clause" I am getting this error saying OleDbException was unhandled...Syntax error in From clause My code for login is given below. Imports System.Data.OleDb Public Class Login Dim con As New OleDbConnection Dim dt As New DataTable Dim ds As New DataSet Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Project work\anshu\fitness_0.1\Fitness.accdb" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click Me.Close() End Sub Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click If check() = True Then Main.Show() Me.Hide() Else MsgBox("Enter vailid Username and Password", MsgBoxStyle.Information, "Login Validation Information") End If End Sub Public Function check() ds.Tables.Add(dt) con.Open() Dim da As New OleDbDataAdapter("select * from User", con) da.Fill(dt) ---->here is the error! For Each DataRow In dt.Rows If txtname.Text = DataRow(1) And txtpass.Text = DataRow(2) Then con.Close() Return True End If Next con.Close() Return False End Function End Class A: User is a reserved word and must be bracketed: "select * from [User]"
{ "language": "en", "url": "https://stackoverflow.com/questions/13543722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHPEXCEL formula calculation issue The problem started in a very complex worksheet but I reduce it to a very simple but still having the same problem. PHPExcel is not calculating the formula, but if I change to a simple one (=B3) it works. The formula returned by getvalue() is =IF(B3="","",IF(C8="N",IF(ISERR(VALUE(B3)),0,VALUE(B3)),T(B3))) My code. require_once dirname(__FILE__) . '/../phpxl/Classes/PHPExcel.php'; set_include_path(get_include_path() . PATH_SEPARATOR . '/../phpxl/Classes/'); $template = "test.xlsx"; $objReader = PHPExcel_IOFactory::createReader('Excel2007'); $objPHPExcel = $objReader->load($template); $objPHPExcel->getActiveSheet()->getCell('B3')->setValue(8); $result = $objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue(); $result1 = $objPHPExcel->getActiveSheet()->getCell('B8')->getValue(); echo $result.'<br>'; echo $result1.'<br>'; I'm setting a value of 8 at the B3 cell, doing this in excel calculates the same value at B8. C8 has an 'N'. But with phpexcel I always get the value it was saved with (2.1) Response: 2.1 =IF(B3="","",IF(C8="N",IF(ISERR(VALUE(B3)),0,VALUE(B3)),T(B3))) Replacing in the excel file the formula at B8 to '=B3' it works perfectly showing the result '8'. Response: 8 =B3 So I must think that is a problem with the formula. The functions are quite simple IF, T, VALUE, ISERR. Change all double quotation and the issue persists. =IF(ISBLANK(B3),NA(),IF(C8="N",IF(ISERR(VALUE(B3)),0,VALUE(B3)),T(B3))) Any idea to get a workaround to this will be welcome. Tks A: That's because (as listed in the documentation) the VALUE() function has not yet been implemented in the PHPExcel calculation engine
{ "language": "en", "url": "https://stackoverflow.com/questions/16449915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Data file handling modify function error c++ class flight //main class flight which the user uses to book tickets { int booking_id; int pnr,p_age; char p_name[25],d_a_name[25],a_a_name[25],gender,departing_date[10],arrival_date[10],b_id; long double price; public: flight() { static int id=0; booking_id=id++; } void modfunction(int n); }; void flight::modfunction(int n) //function for entering new values when the user has chosen to modify { getchar(); cout<<"Enter the passenger's name :"; gets(p_name); cout<<"Enter the passenger age :"; cin>>p_age; getchar(); cout<<"Enter the passenger's gender :"; cin>>gender; getchar(); cout<<"Enter the departing date(dd-mm-yyyy) :"; gets(departing_date); cout<<"Do you want to book return ticket with a 10% discount?(y/n) :"; cin>>return_ticket_input; if(return_ticket_input=='y') { cout<<"Enter the arrival date :"; gets(arrival_date); } cout<<"Choose the airline.\n\n"; flights(departing_date,return_ticket_input,arrival_date); cout<<"\n\nEnter the desired flight number :"; cin>>selected_fno; } void modify_ticket()//function for modifying a ticket { int n; system("clear"); cout<<"Enter the booking id for modification "; cin>>n; flight f; fstream fp("flight.dat",ios::binary); ifstream ifile("flight.dat",ios::binary); int found=0; int count_variable = 0; while(ifile.read((char*)&f,sizeof(f))) { if(n==f.retbid()) { f.output(); f.modfunction(n); // int s=sizeof(f) * (count_variable + 1); fp.seekp(ifile.tellg()); fp.write((char*)&f,sizeof(f)); found = 1; f.output(); getchar(); } count_variable++; } ifile.close(); fp.close(); if(found==0) { cout<<"Passenger not founed!"; } cout<<"Press any key to continue."; getch(); } So this is the minimal version of my problem. The class named flight. a function called modfuction which is used to input data from the user. and another function called modify ticket used by the user to modify the record details. The problem is even though the user enters the booking id(n) and it outputs the record, when the user tries to update it(modify) it stays the same! please help me as this is a part of my school project! thanks in advance! A: Instead of fstream fp("flight.dat",ios::binary); write: fstream fp("flight.dat",ios::binary|ios::in|ios::out); P.S.: Encountered Same Problem A minute ago..
{ "language": "en", "url": "https://stackoverflow.com/questions/26995873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to sort this core data multithreading issue I have an app where I am using core data to store messages and contacts, the app was randomly crashing with error Could not save. Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo={message=attempt to recursively call -save: on the context aborted, stack trace=( 0 CoreData 0x00000001920eb02c + 164 1 Pop 0x0000000100144528 TFC3Pop23PopMainScreenController10savePersonfCSo9CNContactT + 5808 2 Pop 0x0000000100142af8 TFFC3Pop23PopMainScreenController27pullContactsFromAdreessBookFT8purgeOldSb_T_U_FTCSo9CNContactGSpV10ObjectiveC8ObjCBool__T + 88 3 Pop 0x0000000100142b60 TTRXFo_oCSo9CNContactdGSpV10ObjectiveC8ObjCBool___XFdCb_dS_dGSpS1___ + 76 4 Contacts 0x000000019886a898 + 144 5 Contacts 0x0000000198885588 + 96 6 CoreFoundation 0x000000018fce1e24 + 132 7 CoreFoundation 0x000000018fce1cb8 + 208 8 Contacts 0x000000019888545c + 420 9 Contacts 0x000000019886a7fc + 72 10 Pop 0x00000001001426f4 TFC3Pop23PopMainScreenController27pullContactsFromAdreessBookfT8purgeOldSb_T + 1732 11 Pop 0x0000000100134790 TFFC3Pop23PopMainScreenController17reloadAddressBookFT_T_U_FT_T + 60 12 Pop 0x0000000100087f30 TTRXFo___XFdCb__ + 44 13 libdispatch.dylib 0x0000000101bb1a50 _dispatch_call_block_and_release + 24 14 libdispatch.dylib 0x0000000101bb1a10 _dispatch_client_callout + 16 15 libdispatch.dylib 0x0000000101bc17dc _dispatch_root_queue_drain + 980 16 libdispatch.dylib 0x0000000101bc139c _dispatch_worker_thread3 + 140 17 libsystem_pthread.dylib 0x000000018eeb31d0 _pthread_wqthread + 1096 18 libsystem_pthread.dylib 0x000000018eeb2d7c start_wqthread + 4 )}, [AnyHashable("stack trace"): <_NSCallStackArray 0x17464f2d0>( 0 CoreData 0x00000001920eb02c + 164, 1 Pop 0x0000000100144528 TFC3Pop23PopMainScreenController10savePersonfCSo9CNContactT + 5808, 2 Pop 0x0000000100142af8 TFFC3Pop23PopMainScreenController27pullContactsFromAdreessBookFT8purgeOldSb_T_U_FTCSo9CNContactGSpV10ObjectiveC8ObjCBool__T + 88, 3 Pop 0x0000000100142b60 TTRXFo_oCSo9CNContactdGSpV10ObjectiveC8ObjCBool___XFdCb_dS_dGSpS1___ + 76, 4 Contacts 0x000000019886a898 + 144, 5 Contacts 0x0000000198885588 + 96, 6 CoreFoundation 0x000000018fce1e24 + 132, 7 CoreFoundation 0x000000018fce1cb8 + 208, 8 Contacts 0x000000019888545c + 420, 9 Contacts 0x000000019886a7fc + 72, 10 Pop 0x00000001001426f4 TFC3Pop23PopMainScreenController27pullContactsFromAdreessBookfT8purgeOldSb_T + 1732, 11 Pop 0x0000000100134790 TFFC3Pop23PopMainScreenController17reloadAddressBookFT_T_U_FT_T + 60, 12 Pop 0x0000000100087f30 TTRXFo___XFdCb__ + 44, 13 libdispatch.dylib 0x0000000101bb1a50 _dispatch_call_block_and_release + 24, 14 libdispatch.dylib 0x0000000101bb1a10 _dispatch_client_callout + 16, 15 libdispatch.dylib 0x0000000101bc17dc _dispatch_root_queue_drain + 980, 16 libdispatch.dylib 0x0000000101bc139c _dispatch_worker_thread3 + 140, 17 libsystem_pthread.dylib 0x000000018eeb31d0 _pthread_wqthread + 1096, 18 libsystem_pthread.dylib 0x000000018eeb2d7c start_wqthread + 4 ) , AnyHashable("message"): attempt to recursively call -save: on the context aborted] 2017-07-02 22:43:09.192263-0700 Pop[4552:2232120] [error] error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null) CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null) 2017-07-02 22:43:09.192412-0700 Pop[4552:2232120] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil' * First throw call stack: (0x18fdf2fd8 0x18e854538 0x18fdf2f20 0x18fd0f14c 0x1920ed268 0x1920ec230 0x1920e4f24 0x18fda09a0 0x18fd9e628 0x18fd9ea74 0x18fcced94 0x191738074 0x195f87130 0x1001031a0 0x18ecdd59c) libc++abi.dylib: terminating with uncaught exception of type NSException So I enabled assertion to detect access to core data from wrong thread using com.apple.CoreData.ConcurrencyDebug 1 Now its showing assertion to every core data related operation. Most of them I have resolved using newBackgroundContext and performBlockWait block. But my question is why its assessing for every core data related operation ?
{ "language": "en", "url": "https://stackoverflow.com/questions/44890809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: remove first text with shell script Please someone help me with this bash script, lets say I have lots of files with url like below: https://example.com/x/c-ark4TxjU8/mybook.zip https://example.com/x/y9kZvVp1k_Q/myfilename.zip My question is, how to remove all other text and leave only the file name? I've tried to use the command described in this url How to delete first two lines and last four lines from a text file with bash? But since the text is random which means it doesn't have exact numbers the code is not working. A: You can use the sed utility to parse out just the filenames sed 's_.*\/__' A: You can use awk: The easiest way that I find: awk -F/ '{print $NF}' file.txt or awk -F/ '{print $6}' file.txt You can also use sed: sed 's;.*/;;' file.txt You can use cut: cut -d'/' -f6 file.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/36809925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Specify end of token with cin How can you specify the characters that end the reading of a token with cin? Defaults to / t, / n, '' ... But I want to specify some specifics in a similar way to what the std::skipws and std::noskipws or std::ws functions do that allow you to specify whether or not the spaces are ignored, I would like to know if there is something more general for allow read up to some specific character, reads until it finds a string that matches the data type of the variable in which it is to be stored with the >> operator, in order to read and cut the token up to ' ' So that when entering the string A,B,C,D E,F G H,I, J Each letter is a different string something similar to specifying with scanf ("% s,"...) to say that it expects a string followed by a comma that cuts the string but using cin. Could someone help me? Pd: It occurs to me to read the line and to replace ',' by ' ' in such a way that with stringstream I can do the extraction that I want, but this represents crossing the string twice and I look for something clean and efficient that provides the language or it is possible make it simple without much code. A: No you cannot do that. Parse the input and depending on the input, implement your logic with if statements for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/44620277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pick out exactly the right string in my list of utterances? So I am working on a python script using NumPy and Pandas and NLTK to take utterances from the CHILDES Database's Providence Corpus. For reference, the idea of my script is to populate a dataframe for each child in the corpus with their name, utterance containing a linguistic feature I'm looking for (negation types), their age when they said it, and their MLU when they said it. Great. Now the user will be able to go in after the dataframes have been filled with this information and tag each utterance as being of a particular category, and the console will print out the utterance they will tag with a line of context on either side (if they just see that the child said 'no' it's hard to tell what they meant by it without seeing what Mom said right before that or what someone said afterward). So my trick is getting the lines of context. I have it set up with other methods in the program to make this all happen, but I'd like you to look at one segment of one of the methods for populating the dataframes initially, as the line which says: "if line == line_context:", is providing about 91 false positives for me! I know why, because I'm making a temporary copy line by line of each file so that for each utterance that ends up having a negation, that utterance's index in the child's dataframe will be used as the key in a HashMap (or dict in Python) to a list of three Strings (well, lists of strings, since that's how the CHILDESCorpusReader gives me the sentences), the utterance, the utterance before it, and the utterance after it... So I have that buggy line "if line == line_context" to check that as it's iterating through the list of lists of strings (a copy of the file's utterances by line, or 'line_context'), that it lines up with 'line', or the line of the kid's utterance that's being iterated through, so that later I can get the indexes to match up. The problem is that there are many of these 'sentences' that are the same sequence of characters, (['no'] by itself shows up a lot!) so my program will see it as being the same, see it has a negation, and save it to the dataframe, but it'll save it each time it finds an instance of ['no'] in my copy of the file's utterances that's the same as one of the line's of only the child's speech in that file, so I'm getting about 91 extra instances of the same thing! Phew! Anyway, is there any way that I can get something like "if line == line_context" to pick out a single instance of ['no'] in the file, so that I know I'm at the same point in the file on both sides??? I'm using the NLTK CHILDESCorpusReader, which doesn't seem to have resources for this kind of stuff (otherwise I wouldn't have to use this ridiculously roundabout way to get the lines of context!) Maybe there's a way that as I iterate through the utterance_list I'm making for each file, after an utterance has been matched up with the child's utterances I'm also iterating through, I can change and/or delete that item in the utterance_list so as to prevent it from giving me a false positive c. 91 more times?! Thanks. Here is le code (I added some extra comments to hopefully help you understand exactly what each line is supposed to do): for file in value_corpus.fileids(): #iterates through the .xml files in the corpus_map for line_total in value_corpus.sents(fileids=file, speaker='ALL'): #creates a copy of the utterances by all speakers utterance_list.append(line_total) #adds each line from the file to the list for line_context in utterance_list: #iterates through the newly created list for line in value_corpus.sents(fileids=file, speaker='CHI'): #checks through the original file's list of children's utterances if line == line_context: #tries to make sure that for each child's utterance, I'm at the point in the embedded for loop where the utterance in my utterance_list and the utterance in the file of child's sentences is the same exact sentence BUGGY(many lines are the same --> false positives) for type in syntax_types: #iterates through the negation syntactic types if type in line: #if the line contains a negation value_df.iat[i,5] = type #populates the "Syntactic Type" column value_df.iat[i,3] = line #populates the "Utterance" column MLU = str(value_corpus.MLU(fileids=file, speaker='CHI')) MLU = "".join(MLU) value_df.iat[i,2] = MLU #populates the "MLU" column value_df.iat[i,1] = value_corpus.age(fileids=file, speaker='CHI',month=True) #populates the "Ages" column utterance_index = utterance_list.index(line_context) try: before_line = utterance_list[utterance_index - 1] except IndexError: #if no line before, doesn't look for context before_line = utterance_list[utterance_index] try: after_line = utterance_list[utterance_index + 1] except IndexError: #if no line after, doesn't look for context after_line = utterance_list[utterance_index] value_dict[i] = [before_line, line, after_line] i = i + 1 #iterates to next row in "Utterance" column of df
{ "language": "en", "url": "https://stackoverflow.com/questions/17435991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I run UnitTests on all devices and UITests only on iOS 9.x devices in Xcode Server? So I spent some time on implementing the first UITests in Xcode 7 to automatically test the main workflows in our app. And everything went fine locally. However, when I pushed the UITests to the C.I. (Xcode Server) the build broke with the following log message: xcodebuild: error: Failed to build workspace mycoolapp with scheme mycoolapp. Reason: UI Testing is not supported on “iPad 2” because it is running iOS Simulator 8.1 and UI Testing requires iOS Simulator 9.0 or later. 4.684 (4.687) seconds Test Suite 'mycoolappUITests.xctest' failed at 2015-10-14 11:21:45.242. Executed 2 tests, with 2 failures (0 unexpected) in 12.217 (12.229) seconds So what I understand is that UITests are only supported by iOS 9.x devices (which is reasonable). What I don't understand is that I can't seem to configure the Xcode Bot to only run UITests on certain devices and UnitTests on all devices. Am I right about this or is there a configuration option I'm missing? Did anybody run into the same problem? A: I reckon you should be able to create a new scheme to run your UI Tests and uncheck unit tests from the Test action in Edit Scheme. Later you can configure your new bot settings be specifying the UI Test scheme, selecting the "Perform test action" and select the iOS9 devices connected to your server. You can continue to run unit tests with existing bot on all iOS devices and simulators.
{ "language": "en", "url": "https://stackoverflow.com/questions/33121926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Erroneous element error with mapstruct and OpenAPI While trying to convert the java model generated by openapi-generator with MapStruct getting the following exception error: No implementation was created for EmployeeMapper due to having a problem in the erroneous element org.openapitools.jackson.nullable.JsonNullable. Hint: this often means that some other annotation processor was supposed to process the erroneous element. You can also enable MapStruct verbose mode by setting -Amapstruct.verbose=true as a compilation argument. A: The problem was the generated java files having the unused import org.openapitools.jackson.nullable.JsonNullable So while generating the code using openapi-generator passed the following config to ignore the JsonNullable import. "openApiNullable": false
{ "language": "en", "url": "https://stackoverflow.com/questions/72024208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is scalebase nosql database or not? I have read about scalebase but did not understand is it NoSQL database or not? Or they just well horizontal scaled SQL database? A: Per wikipedia (https://en.wikipedia.org/wiki/ScaleBase) it is a distributed MySQL implementation. It supports SQL. So, by definition, it doesn't qualify as "NoSQL"
{ "language": "en", "url": "https://stackoverflow.com/questions/31669013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mixed Content: The page at 'https://example.com' was loaded over HTTPS, but requested an insecure stylesheet error in Wordpress site Instead of genuine Mixed Content issue this seemed like more of a Wordpress issue hence posting here to find a resolution. I have everything setup to work with https, though there is no valid certificate yet. here is the home page url https://tourpoule.nl. The home page loads but with Mixed content errors which seem to be generated by core Wordpress or theme functions. Attaching image: Database does not have any url which would start with http://. I already have replaced them using search and replace script. There is nothing in htaccess file except basic Wordpress setup code. I tried renaming it as well. I cleared all types of cache but still it does not work. The site is using twentytwenty theme and if I comment out css and javascript enque lines, some of the errors disappear but styles and scripts do not load(that is normal I know). In the view source of page it shows mixed urls, some with https and style and javascript urls without https. see below: Interestingly if I click a stylesheet url i.e. http://new.tourpoules.nl/wp-content/themes/twentytwenty/style.css?ver=1.0 it redirects to https://new.tourpoules.nl/wp-content/themes/twentytwenty/style.css?ver=1.0 I am not sure what is going on and have got struck. I am not able to reach the client so that we can discuss turning ssl redirection off in nginx for this domain where it is redirecting everything to https if it is not https. Not sure if that is causing issue (I believe it is not as it has nothing to do with Wordpress mechanism to generate urls). Any help or direction is greatly appreciated. A: I can see your website is still unsecured, for what it's worth, get yourself letsencrypt ssl. Back to you question, go to your database, open the wp_options table, change the siteurl item to https://tourpoules.nl and also change the home item to https://tourpoules.nl. A: If you have used search and replace DB master script or plugin it will not update inside meta files as well as and check for the function file have you Enqueue with https:// So will be better if you download SQL file and replace with below: From: http://new.tourpoules.nl To https://new.tourpoules.nl and re-upload again
{ "language": "en", "url": "https://stackoverflow.com/questions/59370893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Placing SVG element at onClick event I am currently attempting to have an onClick event in which clicking inside of a box places an SVG circle at the coordinates of the mouse pointer. While it is very basic, I have managed to get the onClick event working though I cannot seem to get the circle to summon at the mouse coordinates. Instead, it is brought up in the top left of the box as if it has been given different coordinates. Any assistance (with as much explanation as possible) would be appreciated. I am still new. The code I have been working with is as follows: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>TEST CODE</title> <script> var svgNS = "http://www.w3.org/2000/svg"; function showCoords() { var cX = event.clientX; var sX = event.screenX; var cY = event.clientY; var sY = event.screenY; var svgX = cX; var svgY = cY; } function createCircle() { var myCircle = document.createElementNS(svgNS,"circle"); myCircle.setAttributeNS(null,"id","mycircle"); myCircle.setAttributeNS(null,"cx","svgX"); myCircle.setAttributeNS(null,"cy","svgY"); myCircle.setAttributeNS(null,"r",20); myCircle.setAttributeNS(null,"fill","black"); myCircle.setAttributeNS(null,"stroke","none"); document.getElementById("mySVG").appendChild(myCircle); } </script> </head> <body> <div onClick="createCircle()"> <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="200" style="border:1px solid #000000;"> </svg> <br> <p id="demo"></p> </div> </body> </html> A: The lines that set your circle centre are wrong. They should read: myCircle.setAttributeNS(null,"cx", svgX); myCircle.setAttributeNS(null,"cy", svgY); Ie. remove the quotes on the variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/29909612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel VBA loop not moving to next row I'm so stuck. I can't figure why I can't get this simple loop to work and I still need to expand once I've got part 1 complete. My loop won't move to next i to continue search. Sub TryThis() Dim Purch As String Dim Sales As String Dim finalrow As Integer Dim i As Integer Purch = "PURCHASES" Sales = "SALES" finalrow = Sheets("Sheet1").Range("A12000").End(xlUp).Row For i = 6 To finalrow If Cells(i, 1) = Purch Then Range(Cells(i, 1), Cells(i, 7)).Copy Sheets("Sheet2").Activate Range("A300").End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues Sheets("Sheet1").Activate End If Next i Range("A1").Select End Sub I'm running on empty so I know I'm missing something simple. In the end, what I'm trying to do is loop through rows and if the row, column A has "Purchases", or "Sales", copy that row to sheet 2. Ideally, I'd like to have sales show in column C in sheet 2 and purchases in column b, but I'll deal with that later, just trying to get going and must be thinking so hard I'm missing the simple answer. Thanks A: Check the value being assigned to finalrow. Without having your file available, this is difficult to diagnose. I'm unable to find any obvious errors in your code, so I'll go based on experience. There are quite a few ways to determine what the final row of a spreadsheet is. You're using my favorite, but it has a couple pitfalls: * *Column A could be blank. I usually encounter this when using data pasted from another sheet or an SQL query, but this would be project specific. *Column A could extend beyond 12000 rows. I usually encounter this when I've populated column A with a formula and "autofilled" too far down. "End(xlUp)" would then go to "A1". To (usually) get around either of these issues, I always use the max possible row as a starting point; A65563 for Office 2010 or earlier, or A1048576 for anything after that. It doesn't take any longer to process, and gets more consistent results.
{ "language": "en", "url": "https://stackoverflow.com/questions/58088275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force PowerShell to use .NET CLR Version 2 I am running PowerShell 2 on a Windows Server 2008 R2 Standard Server (German). I want to use the SharePoint 2010 Management Console but am getting the following Errors: The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered. and Microsoft SharePoint is not supported with version 4.0.30319.1 of the Microsoft .Net Runtime. when calling get-spfarm. I get the following when I try to identify the Version: It uses the CLR Version 4.0.30319.1: This seems to not be supported by SharePoint. I than tried to run PowerShell as follows: PowerShell.exe -Version 2.0 But somehow PoweShell still uses the CLR version 4.0.30319.1: A lot of people on the internet have stated that they had this problem when the windows update KB2506143 was installed. This is not installed on my machine. How can I force PowerShell to use the 2.0 Version of the .NET CRL? A: Seems like the file on Server 2008 is Powershell.exe.activation_config. It's located at C:\Program Files(x86)\Common Files\NetApp. Hope this helps! A: Check out your powershell.exe.config file. Do you see the /configuration/startup/requiredRuntime XML element? http://msdn.microsoft.com/en-us/library/a5dzwzc9(v=vs.110).aspx A: Either undo any changes you made to your system that forced PowerShell or other .Net applications to use CLR 4. See here. Or install .Net 3.5 (or 3.0 or 2.0), which will install CLR 2. If you run Windows 8 or 2012 you need do that by changing the Windows features. See here. A: We have now found a solution to the problem: We uninstalled the .NET Framework 4 (since we did not need this on the SharePoint Server). After this we could use the PowerShell for SharePoint again.
{ "language": "en", "url": "https://stackoverflow.com/questions/21237177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP: Adding time to current time? I am trying to add 15minutes to the current time. I am using the following code: $curtime = date('H:i'); $newtime = $curtime + strtotime('+15 minutes'); But this still only prints the current time and not the current time + 15. I want it to add 15mins like so e.g. If the time is 12:30 the time after addition will be 12:45 Thanks. A: You could do: echo date('H:i', (time() + (15 * 60))); A: try this: $curtime = date('H:i'); $newtime = strtotime($curtime) + (15 * 60); echo date('H:i', $newtime); A: Close, you want: $new_time = date('H:i', strtotime('+15 minutes')); A: you can try this - strtotime("+15 minutes") A: In case anyone wants to make it work in Object-oriented way, here is the solution: $currentTime = new DateTime(); $currentTime->add(new TimeInterval('PT15M')); // print the time echo $currentTime->format('H:i'); Requires PHP >= 5.3
{ "language": "en", "url": "https://stackoverflow.com/questions/8161138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CSS animation lurching on startup I'd like to know how to smooth my animation when it first starts. At the moment each bubble lurches forward before transitioning into a smooth animation, but I don't want any noticeable lurching on startup. I've tried the following: * *Adding a transition property to the bubble class *Changing the animation-timing-function to ease-in *Changing the duration of the animation to be longer None of that worked and I'm not sure how to achieve this effect. $(document).ready(function() { var bubbles = $('.bubble') function animate_bubbles() { bubbles.each(function(index) { $(this).css( 'animation-delay', `${index * 0.3}s` ) $(this).addClass('bubble-active') }) } animate_bubbles() }); html, body { height: 100%; } #page-wrapper { box-sizing: border-box; padding: 10%; background: black; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center; flex-wrap: wrap; } .bubble { background: skyblue; border-radius: 50%; width: 5%; margin-right: 5%; } .bubble:before { content: ''; display: block; padding-top: 100%; } .bubble-active { animation: bubble-animation 3s infinite linear; } @keyframes bubble-animation { from { transform: rotate(0deg) translateX(25%) rotate(0deg); } to { transform: rotate(360deg) translateX(25%) rotate(-360deg); } } <!doctype html> <html lang='en'> <head> <meta charset='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet"/> <link rel='stylesheet' href='test.css'> </head> <body> <div id='page-wrapper'> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> </div> <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script> <script src='test.js'></script> </body> </html> A: What you need to do is start and end the keyframes at a translateX of 0%, add in extra keyframes to handle the actual animation. In the following example, I've added an extra keyframe point at 50% that goes to a translateX offset of 25%. This results in a 'smooth' transition, but does cause the bubbles to stop briefly once returning to their original position. You may want to consider adding extra points in the keyframe animation, each with their own unique translateX offsets :) $(document).ready(function() { var bubbles = $('.bubble') function animate_bubbles() { bubbles.each(function(index) { $(this).css('animation-delay', `${index * 0.3}s`) $(this).addClass('bubble-active') }) } animate_bubbles() }); html, body { height: 100%; } #page-wrapper { box-sizing: border-box; padding: 10%; background: black; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center; flex-wrap: wrap; } .bubble { background: skyblue; border-radius: 50%; width: 5%; margin-right: 5%; } .bubble:before { content: ''; display: block; padding-top: 100%; } .bubble-active { animation: bubble-animation 3s infinite linear; } @keyframes bubble-animation { 0% { transform: rotate(0deg) translateX(0%) rotate(0deg); } 50% { transform: rotate(360deg) translateX(25%) rotate(-360deg); } 100% { transform: rotate(360deg) translateX(0%) rotate(-360deg); } } <!doctype html> <html lang='en'> <head> <meta charset='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet" /> <link rel='stylesheet' href='test.css'> </head> <body> <div id='page-wrapper'> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> </div> <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script> <script src='test.js'></script> </body> </html> Hope this helps! :) A: They are moving to the right like that because the start of the animation immediately tells the bubbles to translateX(25%). If you load the page with the transform already applied, it works like you'd want. See the updated snippet below with just one extra line of CSS. $(document).ready(function() { var bubbles = $('.bubble') function animate_bubbles() { bubbles.each(function(index) { $(this).css( 'animation-delay', `${index * 0.3}s` ) $(this).addClass('bubble-active') }) } animate_bubbles() }); html, body { height: 100%; } #page-wrapper { box-sizing: border-box; padding: 10%; background: black; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center; flex-wrap: wrap; } .bubble { background: skyblue; border-radius: 50%; width: 5%; margin-right: 5%; transform: rotate(0deg) translateX(25%) rotate(0deg); } .bubble:before { content: ''; display: block; padding-top: 100%; } .bubble-active { animation: bubble-animation 3s infinite linear; } @keyframes bubble-animation { from { transform: rotate(0deg) translateX(25%) rotate(0deg); } to { transform: rotate(360deg) translateX(25%) rotate(-360deg); } } <!doctype html> <html lang='en'> <head> <meta charset='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet"/> <link rel='stylesheet' href='test.css'> </head> <body> <div id='page-wrapper'> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> </div> <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script> <script src='test.js'></script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/46554439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Export html content to Excel in IE8 using javascript /Jquery I am having below sample code to export the html content to excel. it is working fine in chrome browser. but it is not working in any IE browser 8/9 version. please refer below code. <html> <head> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> $(document).ready(function() { $("[id$=excellink]").click(function(e) { alert("$('div[id$=dvData]').html()"); window.open('data:application/vnd.xls,' + encodeURIComponent( $('div[id$=dvData]').html())); e.preventDefault(); }); }); </script> <body> <br/> <div id="dvData"> <table> <tr> <th>Billing System</th> <th>Market Code</th> <th>Payment Amount</th> </tr> <tr> <td>RED</td> <td>222</td> <td>$103.00</td> </tr> <tr> <td>BLUE</td> <td>111</td> <td>$13.00</td> </tr> <tr> <td>GREEN</td> <td>555</td> <td>$143.00</td> </tr> </table> </div> <br/> <input type="button" id="excellink" value="Excel" /> </body> </head> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/34262675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.Net Validaterequest False I'm creating an Asp.Net program UI where users can browse and change information in a database. For this reason, they need to be able to use all forms of chars, but I still need to keep the program HTML and SQL itself secure. For that reason, I'm using a self-built method that replaces dangerous chars such as '<' etc with their html-codes while they're being handled outside of a textbox (issued on page-load so they have no functionality in there). Now my dilemma: To be able to do this, I have to disable the Validaterequest parameter as per the topic, the program will issue a complaint. What are the possible consequences of setting it to False? The SQL query is parametirized already, and I filter out the following marks only: & # < > " ’ % @ = Question: am I leaving the program open for threats even if I handle the chars above? Basically this is an intranet application where only a few people will be able to access the program. Nevertheless, the information it accesses is fairly important so even unintentional mishaps should be prevented. I literally have no idea what the Validaterequest thing even does. Edit: Alright, thx for the answers. I'll just go with this then as initially planned. A: The main things Validate Request is looking for are < and > characters, to stop you opening your site up to malicious users posting script and or HTML to your site. If you're happy with the code you've got stripping out HTML mark-up, or you are not displaying the saved data back to the website without processing, then you should be ok. A: Basically validating user input by replacing special characters usually cause more trouble and doesn't really solve the problem. It all depends what the user will input, sometimes they need the special characters like & # < > " ’ % @ = think about savvy users could still use xp_ command or even use CONVERT() function to do a ASCII/binary automated attack. As long as you parametrized all input, it should be ok. A: i think that the problem is not only about SQL injection attacks, but about Cross Site Scripting and JS execution attacks. To prevent this you cannot rely on parametrized queries alone, you should do a "sanitization" of the html the user sends! maybe a tool like html tidy could help.
{ "language": "en", "url": "https://stackoverflow.com/questions/713007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Connect via PHP to SQL Server 2012 My problem has a couple things: * *I got a website constructed in joomla, hosted on linux server (that means that sqlsrv doesn't work because it's made for windows only, and the host administrator already informed me that they can't install any php extension). *I got a C# program, and my database is hosted on Amazon (SQL Server 2012). To resume, i need to connect my website to my SQL database program to show data, and modify it, etc etc, on web. So, if you guys have any ideia how can i make it, i really appreciate that. Best regards, Hélder Lopes A: I recommend to install the php module : source : http://technet.microsoft.com/en-us/library/cc793139(v=sql.90).aspx source : http://www.php.net/manual/en/book.mssql.php If there is no way, move your database to your website's hosting (converting db to mysql), and make your C# program use mysql and point it to the website database. good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/24036038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSL error when installing Gradle during react-native run-android I am following react-native official steps how to install and run app (https://facebook.github.io/react-native/docs/getting-started.html). Everything is fine (install react-native and other libraries, run ios version), but react-native run-android fails with following error. What comes to my mind is problem with OSX El Capitan and OpenSSL, but I tried to fix it few months ago and solved all issues. But i did not find anything for this specific error. I tried to install gradle via brew install gradle, but react-native still try to install it again. Maybe there is a way how to tell react-native not to install it again? Thanks for any help 22:23 $ react-native run-android Starting JS server... Building and installing the app on the device (cd android && ./gradlew installDebug)... Downloading https://services.gradle.org/distributions/gradle-2.4-all.zip Exception in thread "main" java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext) at javax.net.ssl.DefaultSSLSocketFactory.throwException(SSLSocketFactory.java:248) at javax.net.ssl.DefaultSSLSocketFactory.createSocket(SSLSocketFactory.java:255) at sun.net.www.protocol.https.HttpsClient.createSocket(HttpsClient.java:405) at sun.net.NetworkClient.doConnect(NetworkClient.java:162) at sun.net.www.http.HttpClient.openServer(HttpClient.java:432) at sun.net.www.http.HttpClient.openServer(HttpClient.java:527) at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264) at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1105) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:999) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at org.gradle.wrapper.Download.downloadInternal(Download.java:58) at org.gradle.wrapper.Download.download(Download.java:44) at org.gradle.wrapper.Install$1.call(Install.java:59) at org.gradle.wrapper.Install$1.call(Install.java:46) at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) at org.gradle.wrapper.Install.createDist(Install.java:46) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:126) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext) at java.security.Provider$Service.newInstance(Provider.java:1617) at sun.security.jca.GetInstance.getInstance(GetInstance.java:236) at sun.security.jca.GetInstance.getInstance(GetInstance.java:164) at javax.net.ssl.SSLContext.getInstance(SSLContext.java:156) at javax.net.ssl.SSLContext.getDefault(SSLContext.java:96) at javax.net.ssl.SSLSocketFactory.getDefault(SSLSocketFactory.java:122) at javax.net.ssl.HttpsURLConnection.getDefaultSSLSocketFactory(HttpsURLConnection.java:332) at javax.net.ssl.HttpsURLConnection.<init>(HttpsURLConnection.java:289) at sun.net.www.protocol.https.HttpsURLConnectionImpl.<init>(HttpsURLConnectionImpl.java:85) at sun.net.www.protocol.https.Handler.openConnection(Handler.java:62) at sun.net.www.protocol.https.Handler.openConnection(Handler.java:57) at java.net.URL.openConnection(URL.java:979) at org.gradle.wrapper.Download.downloadInternal(Download.java:55) ... 7 more Caused by: java.io.IOException: Invalid keystore format at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:658) at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56) at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224) at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70) at java.security.KeyStore.load(KeyStore.java:1445) at sun.security.ssl.TrustManagerFactoryImpl.getCacertsKeyStore(TrustManagerFactoryImpl.java:226) at sun.security.ssl.SSLContextImpl$DefaultSSLContext.getDefaultTrustManager(SSLContextImpl.java:767) at sun.security.ssl.SSLContextImpl$DefaultSSLContext.<init>(SSLContextImpl.java:733) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at java.security.Provider$Service.newInstance(Provider.java:1595) ... 19 more Could not install the app on the device, read the error above for details. Make sure you have an Android emulator running or a device connected and have set up your Android development environment: https://facebook.github.io/react-native/docs/android-setup.html A: I had the same issue on El Capitan, after I messed with OpenSSL. This means your Java certificate is screwed up. In the end, I fixed the problem by reinstalling the JDK. You can do this by first removing the current JDK under: /Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk Then run: sudo rm -rf jdk1.X.X_XX.jdk Install your version of JDK again, and everything should be working! Aside Other symptoms of this problem includes not being able to run any SSL-related 'fetch' functions. For instance, running the Android package manager will give you errors saying it couldn't fetch xml files from https servers.
{ "language": "en", "url": "https://stackoverflow.com/questions/36378468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing ui-router state params from an attribute-type directive (NOT a component) We're upgrading from a very old version of UI Router to v1.0.5, and I'm having an issue trying to replace our deprecated $stateParams uses. To use a simplified example, we have a unique-name attribute-type directive we use on a form field to do a validation check to make sure the text in the field is a unique name. The idea is we're either adding a new doohickey or changing the name of an existing doohickey, and we want to ensure that no other doohickey has the same name. In our old code, we could get the doohickeyId value from the $stateParams like this: function uniqueName(doohickeySearchService, $stateParams, $q) { return { restrict: 'A', require: 'ngModel', link: function (scope, elm, attrs, ctrl) { ctrl.$asyncValidators.uniqueName = function (modelValue) { // use doohickeySearchService to look up foundDoohickey by name // then... return foundDoohickey.id !== $stateParams.doohickeyId; }; } }; } Probably way over-simplified, but the core of the problem is there: how do we get access to the doohickeyId value without using the deprecated $stateParams? There's a parent state that's getting it from the url , which is something like /doohickey/{doohickeyId:int}/edit, as specified in the state definition. I can use $state to get the $current state, and an array of states from the path property, and I can even see the doohickeyId param in one of the states in the path. Unfortunately, if I take the value() of the param, it comes back undefined, even though $stateParams has the correct doohickeyId value. I've also tried adding doohickeyId as a resolve on the parent state, but unfortunately that doesn't give me any data on the attribute-type directive where I need it. Reading the docs and googling is turning up references to accessing parent data from child states, or a component, but I'm trying to get access from an attribute-type directive, not a state/component. Is there a way to do this without giving our code base a major overhaul? A: Have you tried this solution from the UI-Router documentation? Instead of using the global $stateParams service object, inject $uiRouterGlobals and use UIRouterGlobals.params MyService.$inject = ['$uiRouterGlobals']; function MyService($uiRouterGlobals) { return { paramValues: function () { return $uiRouterGlobals.params; } } } Instead of using the per-transition $stateParams object, inject the current Transition (as $transition$) and use Transition.params MyController.$inject = ['$transition$']; function MyController($transition$) { var username = $transition$.params().username; // .. do something with username } https://ui-router.github.io/ng1/docs/latest/modules/injectables.html#_stateparams A: Pass data as the value of your attribute-type directive. Then retrieve it via the attrs argument in the link function. Then eval it against scope. <input unique-name="{doohickeyId: doohickeyIdFromStateParams}" /> link: function (scope, elm, attrs) { var data = scope.$eval(attrs.uniqueName)); console.log('My doohickey ID is: ', data.doohickeyId); } A: I found an answer offline, but I wanted to post it here for future reference. The approach we decided to take was to set up our own custom global state service to hold the state params. So in app/app.js we've got something like this in app.run(): $transitions.onFinish({}, function ($transition$) { customStateService.setCurrentStateParams($transition$); }); Then we can inject our customStateService wherever we need it, and call a getCurrentStateParams() function to retrieve whatever params were available in the most recent successful state transition, similar to how we were previously using $stateParams.
{ "language": "en", "url": "https://stackoverflow.com/questions/46206382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Iterating through a particular column values in dataframes using pyspark in azure databricks Hi is it possible to iterate through the values in the dataframe using pyspark code in databricks notebook? A: Yes You can , You can find lot of options here rows = df3.select('columnname').collect() final_list = [] for i in rows: final_list.append(i[0]) print(final_list)
{ "language": "en", "url": "https://stackoverflow.com/questions/70278233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create connection object for PreparedStatement in SpringBoot try (Connection connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root"); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) { preparedStatement.setString(1, "Ram"); preparedStatement.setInt(2, 1); // Step 3: Execute the query or update query preparedStatement.executeUpdate(); Creating connection object for each query and closing it is expensive, is there any other way to use prepared statement with spring boot and secondly How do I create connection object, I have database information in application.yml file A: Creating connection object for each query and closing it is expensive That's exactly the reason to use connection pools, like c3p0, dbcp, or more modern Hikari connection pool with which spring boot 2 ecosystem integrates perfectly. To access the data you probably may want to use a thin wrapper over raw JDBC API which is fairly cumbersome. Spring provides a wrapper like this, its called JdbcTemplate (It much less "advanced" than hibernate, it doesn't do any automatical mapping, doesn't generate crazy and not-so-crazy queries), it acts pretty much like jdbc but saves you from creating Prepared Statements, iterating over result sets, etc. I won't really explain here how to use JdbcTemplate, I'll just state that you may get a connection from it but I don't think you'll ever need it. Of course under the hood it will be integrated with Hikari connection pool, so that the actual connection will be taken from the pool. Here you can find an example of such a facility with full DAO implementation (its called repository) and JdbcTemplate object configuration
{ "language": "en", "url": "https://stackoverflow.com/questions/66854413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manage files with scheme in XCode I am new to IOS development and I am looking for a way to manage a file called hku.plist (NOT info.plist) with schemes. What I want to do is use hku.plist in production scheme and hku.dev.plist in development scheme. If this is not possible with schemes. What do you guy's recommend?
{ "language": "en", "url": "https://stackoverflow.com/questions/68585932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I know if an object is inside the view frustum of a camera in blender (bpy)? I have a sphere object and I need to know if it is inside the view frustum of my camera. I use blender version 2.8 and I am looking for a scripting solution with bpy. Is there a function similar to insideFrustum(object, camera)? For blender 2.79 there was a function sphereInsideFrustum(..) for controller.owner objects of the logic class. A: The sphereInsideFrustum was part of the game engine which is no longer a part of blender. If you are looking for a real-time solution you will need to look at alternative game engines. If you search blender.stackexchange for pixel+scene you will find several answers about associating geometry with the final rendered image.
{ "language": "en", "url": "https://stackoverflow.com/questions/57463072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: where do i put woocommerce image gallery enable code Woocommerce took out the option for enabling a lightbox feature for your image gallery earlier this year. They have in their documentation to add code if you want to enable the gallery features but don’t actually say where. https://woocommerce.wordpress.com/2017/02/28/adding-support-for-woocommerce-2-7s-new-gallery-feature-to-your-theme/ This is a significant frontend change that can be broken down in to three separate new features; • Image zoom / magnification • Lightbox • Slider To enable each of these features in your theme you must declare support using add_theme_support() like so: add_action( 'after_setup_theme', 'yourtheme_setup' ); function yourtheme_setup() { add_theme_support( 'wc-product-gallery-zoom' ); add_theme_support( 'wc-product-gallery-lightbox' ); add_theme_support( 'wc-product-gallery-slider' ); } This allows you the flexibility to pick and choose exactly which features you want to include/exclude in your theme or at your store. I am not a developer, I don’t have a developer (and shame on WC for not making this an option that end users can opt for or not without having to add code!) I need to know where to put this code. I am using a child theme called mystile1. I have files called “Theme Functions (function.php)” and one called “custom.css” that’s says it is specifically for adding code to modify my child theme styles. I don’t know which file I should put the above coding in and where. Nowhere does each of these files have a line called “after_setup_theme” So would I be safe in just adding the code as follows in one of those files (which one?) replacing “yourtheme” with the name of my theme: add_action( 'after_setup_theme', 'mystile1_setup' ); function mystile1_setup() { add_theme_support( 'wc-product-gallery-zoom' ); add_theme_support( 'wc-product-gallery-lightbox' ); add_theme_support( 'wc-product-gallery-slider' ); } Or any other suggestions are greatly appreciated. Thank you. IN RESPONSE: Below is what is in my functions.php file. would I put the code at the top in between new brackets or down in the section that says: /-----------------------------------------------------------------------------------/ /* You can add custom functions below / /-----------------------------------------------------------------------------------*/ function mystile1_setup() { add_theme_support( 'wc-product-gallery-zoom' ); add_theme_support( 'wc-product-gallery-lightbox' ); add_theme_support( 'wc-product-gallery-slider' ); } ?> "MY FUNCTIONS.PHP FILE" INCLUDES <?php // File Security Check if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) && basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) { die ( 'You do not have sufficient permissions to access this page!' ); } ?> <?php /-----------------------------------------------------------------------------------/ /* Start WooThemes Functions - Please refrain from editing this section / /-----------------------------------------------------------------------------------*/ // Define the theme-specific key to be sent to PressTrends. define( 'WOO_PRESSTRENDS_THEMEKEY', 'zdmv5lp26tfbp7jcwiw51ix9sj389e712' ); // WooFramework init require_once ( get_template_directory() . '/functions/admin-init.php' ); /-----------------------------------------------------------------------------------/ /* Load the theme-specific files, with support for overriding via a child theme. /-----------------------------------------------------------------------------------/ $includes = array( 'includes/theme-options.php', // Options panel settings and custom settings 'includes/theme-functions.php', // Custom theme functions 'includes/theme-actions.php', // Theme actions & user defined hooks 'includes/theme-comments.php', // Custom comments/pingback loop 'includes/theme-js.php', // Load JavaScript via wp_enqueue_script 'includes/sidebar-init.php', // Initialize widgetized areas 'includes/theme-widgets.php', // Theme widgets 'includes/theme-install.php', // Theme installation 'includes/theme-woocommerce.php' // WooCommerce options ); // Allow child themes/plugins to add widgets to be loaded. $includes = apply_filters( 'woo_includes', $includes ); foreach ( $includes as $i ) { locate_template( $i, true ); } /-----------------------------------------------------------------------------------/ /* You can add custom functions below / /-----------------------------------------------------------------------------------*/ // CUSTOM FUNCTION ADDED TO ADDRESS LACK OF ADD-TO-CART BUTTONS ON VARIABLE ITEMS // AS DOCUMENTED AT: http://wordpress.org/support/topic/plugin-woocommerce-excelling-ecommerce-checkout-button-not-showing-on-woo-commerce-product/page/2?replies=36#post-3263097 function mv_my_theme_scripts() { wp_enqueue_script('add-to-cart-variation', get_template_directory_uri() . '/js/add-to-cart-variation.js',array('jquery'),'1.0',true); } add_action('wp_enqueue_scripts','mv_my_theme_scripts'); /-----------------------------------------------------------------------------------/ /* Don't add any code below here or the sky will fall down / /-----------------------------------------------------------------------------------*/ ?>` A: You have to put the code in your function.php between <?php and ?> tags. As additional note: you can put all of these gallery' effects or only few of them on your site. For example if performance of your site is degrading you can delete or put // to add_theme_support( 'wc-product-gallery-zoom' ); or to other effects.
{ "language": "en", "url": "https://stackoverflow.com/questions/47078281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making a rest call with Apache Camel Hi I want to invoke a rest service whose URL is http://ex.abc.com/orders/resources/{var1}/{var2}/details?orderNumber=XXXXX where var1 and var2 are dynamic values. Based on the input they will change. I also want to set 2 headers say key1:value1 , key2:value2. How can I make a rest call to the given url with given headers and then see the response using Apache Camel? (The response will always be JSON). A: You can make use of a dynamic uri in your route block. See http://camel.apache.org/how-do-i-use-dynamic-uri-in-to.html Note that this can be done in both from() and to(). Example: [From (previous application endpoint)] -> [To (perform rest with dynamic values from the exchange)] -> [To (process the returned json)] A: If you're making a rest call you can use the CXFRS component. At the very bottom of the page you'll see an example of a processor that's setting up a message as a rest call. With regards to your question, you can use inMessage.setHeader(Exchange.HTTP_PATH, "/resources/{var1}/{var2}/details?orderNumber=XXXXX"); to set up any path parameters that you might need. A: Please Try to use camel servlet. < from uri="servlet:///orders/resources/{$var1}/{$var2}/details?orderNumber=XXXXX" /> in web.xml, < url-pattern>/ * < /url-pattern> Reference: http://camel.apache.org/servlet.html A: Below is the example where you can find a Rest call with Apache Camel. package camelinaction; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import org.apache.camel.spring.boot.FatJarRouter; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class OrderRoute extends FatJarRouter { @Bean(name = "jsonProvider") public JacksonJsonProvider jsonProvider() { return new JacksonJsonProvider(); } @Override public void configure() throws Exception { // use CXF-RS to setup the REST web service using the resource class // and use the simple binding style which is recommended to use from("cxfrs:http://localhost:8080?resourceClasses=camelinaction.RestOrderService&bindingStyle=SimpleConsumer&providers=#jsonProvider") // call the route based on the operation invoked on the REST web service .toD("direct:${header.operationName}"); // routes that implement the REST services from("direct:createOrder") .bean("orderService", "createOrder"); from("direct:getOrder") .bean("orderService", "getOrder(${header.id})"); from("direct:updateOrder") .bean("orderService", "updateOrder"); from("direct:cancelOrder") .bean("orderService", "cancelOrder(${header.id})"); } } Source code link : https://github.com/camelinaction/camelinaction2/tree/master/chapter10/camel-cxf-rest-spring-boot. I highly encourage to refer camelinaction2 as it covers many advance topics and it is written by @Claus Ibsen.
{ "language": "en", "url": "https://stackoverflow.com/questions/34875732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Outlook and Powershell can you please help my by my Outlook Powershell Problem? > $olSaveType = "Microsoft.Office.Interop.Outlook.OlSaveAsType" -as > [type] > > Add-Type -Assembly "Microsoft.Office.Interop.Outlook" $Outlook = > New-Object -ComObject Outlook.Application $Namespace = > $Outlook.GetNameSpace("MAPI") > > $EmailsInFolder= $NameSpace.GetDefaultFolder(6).Folders.Items > $EmailsInFolder | ft SentOn, Subject, Sensitivity -AutoSize -Wrap > > foreach ($EmailInFolder in $EmailsInFolder) { > $EmailInFolder.Subject = "Test" } When I run the script it works fine. But when I start later on outlook and close outlook it comes an message for each mail where the subject will change. The property of an email „” has changed. Would you like to save the changes in your message? Yes / No How I get rid of the outlook message? If the email in a special folder I like to change the email subject with the PowerShell script. Without any interaction with the user or messages from outlook. Regards Stefan
{ "language": "en", "url": "https://stackoverflow.com/questions/58468098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to get selected row index of gridview in javascript I have got a gridview with certain rows/columns and an edit button for each row. When the edit button is clicked, it opens a popup window with a textbox and a button. I want to know the index of the selected row on click of the button inside the popup. I added code like so var table = document.getElementById('<%= gvTimeSlots.ClientID%>'); var Row; for (var i = 1; i < table.rows.length; i++) { Row = table.rows[i]; alert(Row); } But the alert gives me "Undefined". What am I missing here? A: This is my fix.. function GetSelectedRow(lnk) { var row = lnk.parentNode.parentNode; var rowIndex = row.rowIndex - 1; alert("RowIndex: " + rowIndex); return false; } I am calling this function in Onclientclick event of the link button. <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%" Visible="true"> <ItemTemplate> <asp:LinkButton ID="lnkViewTimeSlots" runat="server" Text="Edit" ForeColor="Blue" OnClick="lnkViewTimeSlots_click" OnClientClick="return GetSelectedRow(this); javascript:shouldsubmit=true;" CausesValidation="false" Style="padding: 0px; margin: 0px;"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> A: Simply you can get the row index like function GetSelectedRow(lnk) { alert("RowIndex: " + lnk.$index;);//This lnk.$index will get the index return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/16643524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the difference between these two inheritance ways in JavaScript Today I wasted hours in a weird bug while developing ember I confidently ignored the Ember extend way App.SomeModel = DS.Model.extend() and somehow turned into my prefer way class App.SomeModel extends DS.Model() My second way just didn't work. So I want to know what's the difference between these two and why the second way didn't work in Ember(Cuz' both ways work in Backbone) A: Look at EmberScript http://emberscript.com/ The key difference is that the Class and extends compile directly to the Ember equivalents, rather than trying to make the Coffeescript ideas fit with Ember. class SomeModel extends Ember.Object becomes var SomeModel; var get$ = Ember.get; var set$ = Ember.set; SomeModel = Ember.Object.extend(); A: App.SomeModel = DS.Model.extend() This calls Ember.js's own Object extend method, which adds observers, reopens a class and so on. class App.SomeModel extends DS.Model() Doesn't rely on a framework, In plain javascript, It's assigning "Somemodel" the properties of the "DS.Model()" object. It's not expected to work inside the framework for extending Ember.Object's
{ "language": "en", "url": "https://stackoverflow.com/questions/18646527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I register a onblur hook for a select_tag? Currently I have this, a multi select tag, which calls the function every time something is selected/deselected. But I want the function to be called when a user clicks out of the dropdown select_tag, any ideas? <%= select_tag ... :onchange => 'handleChange()' %> A: There are a couple ways. The best way to accomplish this is with some unobtrusive JavaScript. Add an event listener like this: # <%= select_tag 'state' ... ' %> => <select name="state" id="state" multiple> <option value="MN">Minnesota</option> <option value="IA">Iowa</option> <option value="WI">Wisconsin</option> <option value="SD">South Dakota</option> </select> <script> let element = document.getElementById('state'); element.addEventListener('blur', event => console.log("blur, baby, blur")); </script> If you prefer to use jQuery and it's already imported, you can use its event handlers. The jQuery version would go something like this: $(document).on('blur', '#state', event => console.log('blur, baby, blur')); Note that passing the event to your function is optional. I'm adding the event handler directly to the document which means that it would work even if the select element is dynamically added to the page after page load. You can alternatively use this more classic jQuery approach if you are not dynamically loading the element. $('#element-id').on('blur', function() { // do stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/62817983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert ddmmyyyy HH:mm to dd-mm-yyyy HH:mm in Angular6 The date format which I am getting from the Api response is like this. "startDate" : "07112018 00:00". I want to convert this to in dd-mm-yyyy HH:mm format. that is like this 07-11-2018 00:00. Can anyone please tell me how to do this using Angular 6. A: You can use DatePipe API for this: https://angular.io/api/common/DatePipe @Component({ selector: 'date-pipe', template: `<div> <p>Today is {{today | date}}</p> <p>Or if you prefer, {{today | date:'fullDate'}}</p> <p>The time is {{today | date:'h:mm a z'}}</p> //format in this line </div>` }) // Get the current date and time as a date-time value. export class DatePipeComponent { today: number = Date.now(); } and this is what actually you want: {{myDate | date: 'dd-MM-yyyy'}} Edit: Using built-in pipe in component, import { DatePipe } from '@angular/common'; class MyService { constructor(private datePipe: DatePipe) {} transformDate(date) { return this.datePipe.transform(date, 'yyyy-MM-dd'); } } Please read this topic, I took example from there: https://stackoverflow.com/a/35152297/5955138 Edit2: As I described in comment, you can substring your date using this. var str = '07112018' var d = new Date(str.substring(0, 2)+'.'+str.substring(2, 4)+'.'+str.substring(4, 8)); Output: Wed Jul 11 2018 00:00:00 GMT+0300 A: try this function to convert time format as you require timeFormetChange(){ var date =new Date(); var newDate = date.getDate(); var newMonth = date.getMonth(); var newYear =date.getFullYear(); var Hour = data.getHours(); var Minutes = data.getMinuets(); return `${newDate}-${newMonth }-${newYear} ${Hour}:${Minutes }` }
{ "language": "en", "url": "https://stackoverflow.com/questions/54255584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with searching multiple keywords using google custom search API I am trying to search for multiple keywords (in the list of filteredList) and get a list of each search result. This is the code I have tried below: from googleapiclient.discovery import build import csv import pprint my_api_key = "xxx" my_cse_id = "xxx" def google_search(search_term, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute() return res['items'] filteredList = ['Optimal Elektronika', 'Evrascon', ] words = [ 'vakansiya' ] newDictList = [] # this is the htmlSnippets, link and also htmlTitle for filtering over the list of the dictionaries keyValList = ['link', 'htmlTitle', 'htmlSnippet'] for word in filteredList: results = google_search(word, my_api_key, my_cse_id, num=5) # print(results) newDict = dict() for result in results: for (key, value) in result.items(): if key in keyValList: if word in newDict['htmlSnippet']: pass newDict[key] = pprint.pprint(value) newDictList.append(newDict) print(newDictList) Running the answer script The error code I got (Running the answer script): Traceback (most recent call last): File "/Users/valizadavali/PycharmProjects/webScrape/GCS.py", line 39, in <module> items = google_search(word, API_KEY, CSE_ID, num=5) File "/Users/valizadavali/PycharmProjects/webScrape/GCS.py", line 11, in google_search return res['items'] KeyError: 'items' A: I don't have API keys to run this code but I see few mistakes: When you use for items in filteredList: then you get word from list, not its index so you can't compare it with number. To get number you would use for items in range(len(filteredList)): But instead of this version better use first version but then use items instead of filterd[items] in results = google_search(items, my_api_key, my_cse_id, num=5) If you choose version with range(len(filteredList)): then don't add 1 to items - because then you get numbers 1..6 instead of 0..5 so you skip first element filteredList[0] and it doesn't search first word. And later you try to get filteredList[6] which doesn't exist on list and you get your error message. for word in filteredList: results = google_search(word, my_api_key, my_cse_id, num=5) print(results) newDict = dict() for result in results: for (key, value) in result.items(): if key in keyValList: newDict[key] = value newDictList.append(newDict) print(newDictList) BTW: you have to create newDict = dict() in every loop. BTW: standard print() and pprint.pprint() is used only to sends text on screen and always returns None so you can't assign displayed text to variable. If you have to format text then use string formatting for this. EDIT: version with range(len(...)) which is not preferred in Python. for index in range(len(filteredList)): results = google_search(filteredList[index], my_api_key, my_cse_id, num=5) print(results) newDict = dict() for result in results: for (key, value) in result.items(): if key in keyValList: newDict[key] = value newDictList.append(newDict) print(newDictList) EDIT: from googleapiclient.discovery import build import requests API_KEY = "AIzXXX" CSE_ID = "013XXX" def google_search(search_term, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute() return res['items'] words = [ 'Semkir sistem', 'Evrascon', 'Baku Electronics', 'Optimal Elektroniks', 'Avtostar', 'Improtex', # 'Wayback Machine' ] filtered_results = list() keys = ['cacheId', 'link', 'htmlTitle', 'htmlSnippet', ] for word in words: items = google_search(word, API_KEY, CSE_ID, num=5) for item in items: #print(item.keys()) # to check if every item has the same keys. It seems some items don't have 'cacheId' row = dict() # row of data in final list with results for key in keys: row[key] = item.get(key) # None if there is no `key` in `item` #row[key] = item[key] # ERROR if there is no `key` in `item` # generate link to cached page if row['cacheId']: row['link_cache'] = 'https://webcache.googleusercontent.com/search?q=cache:{}:{}'.format(row['cacheId'], row['link']) # TODO: read HTML from `link_cache` and get full text. # Maybe module `newpaper` can be useful for some pages. # For other pages module `urllib.request` or `requests` can be needed. row['html'] = requests.get(row['link_cache']).text else: row['link_cache'] = None row['html'] = '' # check word in title and snippet. Word may use upper and lower case chars so I convert to lower case to skip this problem. # It doesn't work if text use native chars - ie. cyrylica lower_word = word.lower() if (lower_word in row['htmlTitle'].lower()) or (lower_word in row['htmlSnippet'].lower()) or (lower_word in row['html'].lower()): filtered_results.append(row) else: print('SKIP:', word) print(' :', row['link']) print(' :', row['htmlTitle']) print(' :', row['htmlSnippet']) print('-----') for item in filtered_results: print('htmlTitle:', item['htmlTitle']) print('link:', item['link']) print('cacheId:', item['cacheId']) print('link_cache:', item['link_cache']) print('part of html:', item['html'][:300]) print('---')
{ "language": "en", "url": "https://stackoverflow.com/questions/58547746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: aggregate array of objects based on certain properties typescript I have an array Order[], where Order is: interface Order { orderId: number; productName: string; color: string; quantity: number; price: number; link: string; } I want to create a mapping where: * *key is (productName, color) *values are quantity, price, link. Quantity and price are a sum of matching properties of original objects. link is the same for all so can just keep one of them. I know how to create a single item using filter and reduce, similar to this question: How to sum values in typescript array based on array items property? I tried to use a Map object, but got stuck because I couldn't compare the keys properly - always got false A: There's probably a more elegant way, but you could use a string template to represent the product/color combination. Playground Link interface Order { orderId: number; productName: string; color: string; quantity: number; price: number; link: string; } interface Summary { productName: string; color: string; quantity: number; price: number; } const makeKey = (order: Order) => { return `${order.productName}_${order.color}`; } type AggregatedOrders = { [key: string]: Summary; }; const orders: Order[] = [ { color: "blue", link: "https://savantly.net", orderId: 123, price: 999, productName: "hello", quantity: 1 }, { color: "green", link: "https://savantly.net", orderId: 345, price: 999, productName: "hello", quantity: 1 }, { color: "green", link: "https://savantly.net", orderId: 234, price: 999, productName: "hello", quantity: 1 } ]; const groups: AggregatedOrders = {}; orders.forEach(o => { const key = makeKey(o); if(!groups[key]) { groups[key] = o; } else { groups[key].price += o.price; groups[key].quantity + o.quantity } }); // grouped by product and color console.log(groups);
{ "language": "en", "url": "https://stackoverflow.com/questions/71693462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to schedule the uploading of videos to a YouTube Channel? I was trying to automate uploading to my YT channel with Python. The story goes like this: I had a channel and I upload multiple times a day. But now I'm about to join college and I don't have the time to do the uploading except at weekends. The editing isn't the problem, it's the uploading I would like to get done. But I don't want to upload all (say) 50 videos on Sunday and none for the rest of the week. and that inconsistency is bad for YT growth. So my plan was to bunch-edit and produce all those videos on weekend and let a script upload those ready-made videos over the whole week, with an equally spaced interval, periodic and recurring without me telling it every time I want to (for eg. twice a day or five times a day). The workflow I needed is as follows * *The Script uploads a video from a specified folder *post the video to YT with pre-set data (title, desc., tag...) *(Then only if the upload was successful) move that video to another folder to avoid re uploading and to keep track (I don't want to delete them in case they're needed later) *repeat the process every certain hours I’ve been thinking about ways to create the workflow above, but I couldn't. A: i have the right script for you but can't upload here lol. import schedule you can use this library for scheduling a function(the upload function), but you will can to keep your program run all the time. or using the microsoft scheduler , which will schedule your whole program.
{ "language": "en", "url": "https://stackoverflow.com/questions/71141664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular changeable form according to inputs I'm using a reactive form. I need to add/remove an input that appears in it according to some other input. Here's a simplified scenario of the issue: Asking the user to select an option from a list. If their desired option is not there, there is an open input where they can write. If they do choose an option from the select, the input must disappear. If they do not select an option, the input must be there and it must be required. Here's the code I made which 1) doesn't work 2) feels like it's fairly ugly and could be made in some other way. Template: <form [formGroup]="whateverForm" (ngSubmit)="onSubmit()"> Choose an option: <select formControlName="option" (change)="verifySelection($event)"> <option value=''>None</option> <option value='a'>Something A</option> <option value='b'>Something B</option> </select> <br> <div *ngIf="!optionSelected"> None of the above? Specify: <input type="text" formControlName="aditional"> </div> <br> <br> Form current status: {‌{formStatus}} </form> Code: export class AppComponent { whateverForm: FormGroup; formStatus: string; optionSelected = false; ngOnInit() { this.whateverForm = new FormGroup({ 'option': new FormControl(null, [Validators.required]), 'aditional': new FormControl(null, [Validators.required]) }); this.whateverForm.statusChanges.subscribe( (status) => { this.formStatus = status; } ); } verifySelection(event: any) { if (event.target.value !== '') { this.optionSelected = true; this.whateverForm.get('aditional').clearValidators(); this.whateverForm.get('option').setValidators( [Validators.required]); } else { this.optionSelected = false; this.whateverForm.get('option').clearValidators(); this.whateverForm.get('aditional').setValidators( [Validators.required]); } } } A: Instead of using an event, I used an observable in one of the fields. The exact solution to the problem I proposed is here. And I solved it using what I found here (they are basically the same thing, but I included mine for completion).
{ "language": "en", "url": "https://stackoverflow.com/questions/56877087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what are the last digits in javascript new Date() object when I execute the following line in Node > let x = new Date() > x i get something like 2020-06-04T21:51:08.059Z what is .059Z and how would it translate to GMT timezone? A: "Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 DateTime standard for UTC times. let x = new Date(); let gmtZone = x.toGMTString(); console.log(gmtZone)
{ "language": "en", "url": "https://stackoverflow.com/questions/62204838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Showing/Hiding a DIV based on one or more checkbox/radiobox selections? I asked a similar question previously, but it was so vague that I couldn't possibly have gotten the answer I wanted. Basically, I want a user to be able to select from multiple options and have various bits of information appear based on the selections. For example: "How old is your computer?" Options: [x]One Year [ ] Two Years [ ] Three Years Output: "Your computer is One year old" I want that functionality to expand over multiple separate checkboxes and radioboxes...? Is this possible? EDIT: Its for a hardware upgrade recommendation system that takes in to account your current system. "Based on your current system, you need to replace your graphics card and purchase additional RAM" Which could use factors like "How old is your computer?", "How much RAM does your computer have", "What directX version is your graphics card" or something like that. A: I would set up a parsing function that reacts to every change in any of the form elements, and "compiles" the string containing the bits of information. You could set this function to the "onchange" event of each element. How the parsing function will have to look like is really up to what you want to achieve. It could be something like this: (intentionally leaving out framework specific functions) function parse_form() { var age_string = "Your computer is" var age = document.getElementById("age").value; if (age == 1) age_string+= "one year old"; if (age > 1) age_string+= "more than one year old"; ... and so on. } A: A regular jQuery click listener will do. Making some assumptions about your HTML code (that you're using radio input buttons with label tags whose for attributes correspond to the IDs of the radio buttons): $("#options input").click(function(){ var optionID= $(this).attr(id); var outputText= $("label[for="+optionID+"]"); $("#output").text(outputText); }); This code will accomplish pretty much exactly what you want. If you want separate DIVs for each particular output message, just create divs each with class output with let's say a rel attribute corresponding to the ID of the input button, then: $("#options input").click(function(){ var optionID= $(this).attr(id); $("div.output[rel!="+optionID+"]").slideUp(function(){ var outputDiv= $("div[rel="+optionID+"]"); }); }); This code can be improved by better handling situations in which an already selected option is reclicked (try it... weird things may happen), or if clicks occur very quickly. Alternately, you can just use the regular onclick attribute for the input radio buttons if you just want to stick to native Javascript. If you're interested in the appropriate code for that, post a comment, and someone will surely be able to help you out. A: Here is an example with jQuery that will fit your needs. // no tricks here this function will run as soon as the document is ready. $(document).ready(function() { // select all three check boxes and subscribe to the click event. $("input[name=ComputerAge]").click(function(event) { var display = $("#ComputerAgeTextDisplay"); // # means the ID of the element switch (parseInt(this.value)) // 'this' is the checkbox they clicked. { case 1: display.html("Your computer is one year old."); break; case 2: display.html("Your computer is two years old."); break; case 3: display.html("Your computer is three years old."); break; default: display.html("Please select the age of your computer."); break; } }); }); A: <span id='#options'> Options: <input type='radio' name='options' value='one'>One Year</input> <input type='radio' name='options' value='two'>Two Years</input> <input type='radio' name='options' value='three'>Three Years</input> </span> Output: "<span id='#output'></span>" ... var labels = { one: "Your computer is One Year Old", two: "Your computer is Two Years Old", three: "Your computer is Three Years Old" }; $('#options :radio').click(function() { $('#output).html(labels[$(this).val()]); }); A: You'd need a way to associate each checkbox with the information you wanted to show. You could for example combine the name and value to get an ID to show, assuming the values are characters that are valid in an ID: <input type="radio" name="age" value="1" /> One year <input type="radio" name="age" value="2" /> Two years <input type="radio" name="age" value="3" /> Three years <div id="age-1"> Your computer is awesome!! </div> <div id="age-2"> Your computer is so-so </div> <div id="age-3"> Your computer sucks </div> Now you just need a bit of script to tie them together: function showElementsForInputs(inputs) { // Set the visibility of each element according to whether the corresponding // input is checked or not // function update() { for (var i= inputs.length; i-->0;) { var input= inputs[i]; var element= document.getElementById(inputs[i].name+'-'+inputs[i].value); element.style.display= input.checked? 'block' : 'none'; } } // Set the visibility at the beginning and also when any of the inputs are // clicked. (nb. use onclick not onchanged for better responsiveness in IE) // for (var i= inputs.length; i-->0;) inputs[i].onclick= update; update(); } showElementsForInputs(document.getElementById('formid').elements.age);
{ "language": "en", "url": "https://stackoverflow.com/questions/1750606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lerna and webpack aliases issue Imagine two projects (ex. my-app and my-ui) using webpack aliases to resolve 'components' as './src/components'. I use Lerna to locally "link" this projects and simplify development, my-ui is a dependency of my-app (set in it's package.json) and imported like : MyApp /src/main.js : import UI from 'my-ui'; MyUI /src/main.js import Button from 'components/button'; export default Button; /src/components/button/main.js export default class Button... When MyApp start, MyUI try to resolve Button in "MyApp/src/components/" instead of "MyApp/node_modules/my-ui/src/components" or "MyApp/node_modules/my-ui/lib/app.js". I dont find how to resolve this issue ! The resolve section from my Webpack config : resolve: { mainFiles: ['index', 'main'], extensions: ['.js', '.jsx'], alias: { lib: helpers.getPath('src/lib/'), components: helpers.getPath('src/components/'), }, modules: [ helpers.getPath('src'), helpers.getPath('node_modules'), ], }, Where the getPath method is : const path = require('path'); const projectPath = path.resolve(__dirname, '..'); const getPath = path.join.bind(path, projectPath); A: add webpack loader to Change MyUI alias path. module.exports = function(content) { let prefix = "MyUI/"; if (this.context.includes("/src") && this.context.includes(prefix)) { let relativePath = this.context .slice(this.context.indexOf(prefix)) .replace(prefix, ""); let pkgName = `${prefix}${relativePath.slice( 0, relativePath.indexOf("/") )}`; content = content.replace(/@\//g, `${pkgName}/src/`); } return content; };
{ "language": "en", "url": "https://stackoverflow.com/questions/43764728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to draw lines parallel to the width of minimum area rectangle joing opposite contour points using OpenCV python I am trying to draw lines parallel to the width of minimum area rectangle drawn on a contour which connect the opposite points of the contour. What I intend to do with this is to find the real width of the contour. To find the real width of the objects, I currently use a reference object inside the images and to find pixel per cm value which is used to convert the width value obtained in pixel to cm.To find the width I am using Minimum Area Rectangle method present in OpenCV, I have also tried finding the leftmost and rightmost contour points and then joining them to find there length but the values are always over predicted. Following is the code that I am using to find the values. commodity_mask = copy.deepcopy(r['masks'][i]).astype(np.uint8) im, contours_m, hierarchy  = cv2.findContours(commodity_mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) contours = max(contours_m, key=cv2.contourArea)leftmost = tuple(contours[contours[:,:,0].argmin()][0]) rightmost = tuple(contours[contours[:,:,0].argmax()][0]) topmost = tuple(contours[contours[:,:,1].argmin()][0]) bottommost = tuple(contours[contours[:,:,1].argmax()][0]) cv2.circle(minrect, leftmost, 8, (0, 50, 255), -1) cv2.circle(minrect, rightmost, 8, (0, 50, 255), -1) cv2.line(minrect, leftmost, rightmost, (0,0,255),2) dist = np.sqrt((leftmost[0]-rightmost[0])**2 + (leftmost[1]-rightmost[1])**2) dist = dist*ratio #finding distance b/w leftmost and rightmost contour point and converting them to pixels. commodity_rect = cv2.minAreaRect(commodity_contour)  # (top-left corner(x,y), (width, height), angle of rotation) cv2.drawContours(minrect, [np.int0(cv2.boxPoints(commodity_rect))], 0, (0, 255, 0), 2) (xrect, yrect), (wrect, hrect), alpha = commodity_rect print('Width: ', wrect * ratio, 'Height: ', hrect * ratio) The r['masks'][i] value is the ith contour obtained in from the image. So far I have achieved is the following image. The green boxes are the minimum area rectangle drawn on the contour and the red line joins the leftmost and rightmost points of the contour. What I want to do is the following. Draw lines parallel to the width of the rectangle(yellow ones) which join the opposite points of the contour, then I can find their lengths and use them to find the width of the contour. This is the original image, without the rectangles drawn. A: In solution one, I misunderstood something and find a horizontal line on the bounding box, this is your desired line cordinates. import numpy as np import cv2 def get_order_points(pts): # first - top-left, # second - top-right # third - bottom-right # fourth - bottom-left rect = np.zeros((4, 2), dtype="int") # top-left point will have the smallest sum # bottom-right point will have the largest sum s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] # top-right point will have the smallest difference # bottom-left will have the largest difference diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect image = cv2.imread('image.png') image = cv2.resize(image, (800, 800)) output_image = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) low = np.array([33, 91, 21]) high = np.array([253, 255, 255]) mask = cv2.inRange(HSV, low, high) contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) sorted_contour = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True) # As I know there is 6 max contour we want I'm selecting 6 contour only to creating perfact mask selected_contour = sorted_contour[:6] blank_mask = np.zeros_like(mask) mask = cv2.drawContours(blank_mask, selected_contour, -1, 255, -1) cv2.imshow("mask", mask) cv2.imwrite("mask.png", mask) for i, cnt in enumerate(selected_contour): # find min enclosing rect commodity_rect = cv2.minAreaRect(cnt) bounding_rect_points = np.array(cv2.boxPoints(commodity_rect), dtype=np.int) cv2.drawContours(output_image, [bounding_rect_points], 0, (0, 255, 0), 2) tl, tr, br, bl = get_order_points(bounding_rect_points) left_point = (tl + bl) // 2 right_point = (tr + br) // 2 print(f"\nfor {i}th contour : ") print("left_point : ", left_point) print("right_point : ", right_point) cv2.circle(output_image, tuple(left_point), 3, (255, 0, 0), -1) cv2.circle(output_image, tuple(right_point), 3, (255, 0, 0), -1) cv2.line(output_image, tuple(left_point), tuple(right_point), (0, 0, 255), 1) cv2.imshow("output_image", output_image) cv2.imwrite("output_image.png", output_image) cv2.waitKey(0) cv2.destroyAllWindows() Output: for 0th contour : left_point : [606 597] right_point : [785 622] for 1th contour : left_point : [ 64 236] right_point : [214 236] for 2th contour : left_point : [325 201] right_point : [507 295] for 3th contour : left_point : [ 56 638] right_point : [244 619] for 4th contour : left_point : [359 574] right_point : [504 625] for 5th contour : left_point : [605 241] right_point : [753 241] Output_Image: A: This will help you to find your desired line coordinates. I have used the cv2.pointPolygonTest on contours point to find your desired points. more about cv2.pointPolygonTest here import numpy as np import cv2 image = cv2.imread('image.png') image = cv2.resize(image, (800, 800)) output_image = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) low = np.array([33, 91, 21]) high = np.array([253, 255, 255]) mask = cv2.inRange(HSV, low, high) contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) sorted_contour = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True) # As I know there is 6 max contour we want I'm selecting 6 contour only to creating perfact mask selected_contour = sorted_contour[:6] blank_mask = np.zeros_like(mask) mask = cv2.drawContours(blank_mask, selected_contour, -1, 255, -1) cv2.imshow("mask", mask) for i, cnt in enumerate(selected_contour): # find min enclosing rect commodity_rect = cv2.minAreaRect(cnt) cv2.drawContours(output_image, [np.int0(cv2.boxPoints(commodity_rect))], 0, (0, 255, 0), 2) # find center point of rect M = cv2.moments(cnt) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) cv2.circle(output_image, (cX, cY), 5, (0, 255, 255), -1) selceted_points = [[px, cY] for [[px, py]] in cnt if cv2.pointPolygonTest(cnt, (px, cY), measureDist=False) == 0] left_point = min(selceted_points, key=lambda x: x[0]) right_point = max(selceted_points, key=lambda x: x[0]) print(f"\nfor {i}th contour : ") print("left_point : ", left_point) print("right_point : ", right_point) cv2.circle(output_image, tuple(left_point), 3, (255, 0, 0), -1) cv2.circle(output_image, tuple(right_point), 3, (255, 0, 0), -1) cv2.line(output_image, tuple(left_point), tuple(right_point), (0, 0, 255), 1) cv2.imshow("output_image", output_image) cv2.waitKey(0) cv2.destroyAllWindows() Output: for 0th contour : left_point : [606, 613] right_point : [786, 613] for 1th contour : left_point : [73, 233] right_point : [211, 233] for 2th contour : left_point : [329, 248] right_point : [501, 248] for 3th contour : left_point : [58, 637] right_point : [246, 637] for 4th contour : left_point : [364, 600] right_point : [508, 600] for 5th contour : left_point : [605, 237] right_point : [753, 237] Mask Image: Output Image: A: have you tried something like this: commodity_rect = cv2.minAreaRect(commodity_contour) #Find the minAreaRect for each contour minAxis = round(min(commodity_rect[1])) #Find minor axis size maxAxis = round(max(commodity_rect[1])) #Find major axis size but instead of minAreaRect, what I think you're looking for is the rotating caliper algorithm. Take a look at the link below: https://chadrick-kwag.net/python-implementation-of-rotating-caliper-algorithm/#:~:text=Rotating%20caliper%20algorithm%20is%20used,all%20possible%20rotating%20caliper%20rectangles.
{ "language": "en", "url": "https://stackoverflow.com/questions/66669298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do single quote( ' ) and double quote( " ) get different results in python's json module? I have such piece of python code: import json single_quote = '{"key": "value"}' double_quote = "{'key': 'value'}" data = json.loads(single_quote) # get a dict: {'key': 'value'} data = json.loads(double_quote) # get a ValueError: Expecting property name: line 1 column 2 (char 1) In python, single_quote and double_quote make no technical differences, don't they? Then why single_quote works and double_quote doesn't? A: It's not the outside quotes that matter, it's the literal quotes in the JSON string (must be ") ie. This is ok (but cumbersome) double_quote = "{\"key\": \"value\"}" You can also use triple quotes '''{"key": "value"}''' """{"key": "value"}""" The choices of quotes are there so you hardly ever need to use the ugly/cumbersome versions A: That's because only the first example is valid JSON. JSON data have keys and values surrounded by "..." and not '...'. There are other "rules" that you may not be expecting. There's a great list on this wikipedia page here. For example, booleans should be lowercase (true and false) and not True and False. JSON != Python. A: JSON is a language-free format for exchanging data. Although single_quote and double_quote make no difference in Python, they're different in JSON cause a JSON object will be processed by other languages as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/19827383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Comparing datetime variables in Rails Rails 3 Ruby 1.92 - i have a helper method comparing a datetime attribute on an object to the current date & time. module StoreHelper def initial_time(product) if product.time_type == "Min" initial_time = (product.time * 60) elsif product.time_type == "Hrs" initial_time = (product.time * 3600) else initial_time = 0 end end def time_based_price(product) start_time = product.start_time current_time = Time.now expire_time = start_time + initial_time(product) if (current_time <= expire_time) && (unit_sales(product)>= product.volume) time_based_price = (product.price - product.boost_savings) else time_based_price = product.price end end end when i call it from my view i get error "undefined method `to_datetime' for 0:Fixnum". if i change the comparison line (current_time <= expire_time)to (expire_time >= current_time) i get error"comparison of Fixnum with Time failed" I've tried using .now, .current, .zone.now for both Time and DateTime with no luck. When i call the Time.zone.now and expire_time values from my view they have the same format: 2013-11-17 20:48:07 UTC - Time.zone.now 2013-11-17 16:15:00 UTC - expire_time A: Are you calling this method for each product item in a list? In that case, looks like for one of the product, no values have been set for start_time, and time_type. You would get this error when expire_time is 0. But since you have tried the value of expire_time, I believe it must be happening for more product instances and it fails for one of those.
{ "language": "en", "url": "https://stackoverflow.com/questions/20036048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sizing iAd Banner Views This seems like it should be simple, but the documentation is very unclear. In the introduction of the ADBannerView class, Apple says this: A banner view must always use one of the standard sizes defined in Content Size Identifiers. This is to ensure that the advertisement is drawn correctly. You configure the banner view’s requiredContentSizeIdentifiers property with the set of possible sizes your view is allowed to use in your application. To change the size of the banner view, do not set the bounds directly; instead set the currentContentSizeIdentifier property to one of the size identifiers included in that set. You can retrieve the actual dimensions that a particular identifier equates to on a specific device by calling the sizeFromBannerContentSizeIdentifier: class method. However, these methods are all marked in the documentation as deprecated since iOS 6: Deprecation Statement: Banner views no longer use content size identifiers. See Content Size Identifiers for details. If you go to "Content Size Identifiers", nothing can be found except the documentation for these constants, all marked as depricated since iOS 6. The rest of the documentation doesn't seem to be any help either. If these methods are deprecated, and nothing seems to have taken their place, how are you supposed to resize and get the size of iAd banners? A: There's no need to set the ADBannerView's size. Your ADBannerView will know which device it is on and set the dimensions of itself correctly. All you need to do is set the ADBannerView's position. Check this implementation for an example. If you're using Auto Layout and wanted the ADBannerView to be at the bottom of the screen then pin it to the bottom of the screen with Bottom Space to: Bottom Layout Guide and align it to Align Center X to: Superview. Be sure you do not set any height, width, trailing, or leading constraints A: OK. I still have no idea about resizing, but I figured out initial sizing. Since iOS 6, ADBannerViews have an adType property. This property can be either ADAdTypeBanner or ADAdTypeMediumRectangle. The documentation gives the sizes for both kinds: The banner height varies with device type and orientation as follows: UI Idiom and Orientation | Ad Height -------------------------------------- phone, portrait | 50 points phone, landscape | 32 points pad, portrait or landscape | 66 points As for resizing, I can only assume that the banner view automatically takes the width of the screen by observing orientation change notifications.
{ "language": "en", "url": "https://stackoverflow.com/questions/34619140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why table size doesn't change after vacuum full? Here is then code. Lets create table with 10000 rows of data. DB version is PostgreSQL 9.5.3 on x86_64-suse-linux-gnu drop table if exists test; create table test as select gs as id, md5(gs::text) as value from generate_series(1,10000) gs; create unique index test_id_pkey on test using btree(id); alter table test add primary key using index test_id_pkey; analyze test; select pg, pg_size_pretty(pg) pz from pg_relation_size('test') pg; Results of last query: 672kb Now delete from test where id > 1000; size of table was reduced like 10 times. Now lets vacuum it. According documentation vacuum full make of copy of table on disk and write into it only alive rows, those are only 10% of original. vacuum full test; select pg, pg_size_pretty(pg) pz from pg_relation_size('test') pg; Still size of table is 672kb Let's try trick with alter table statement which will do the same. Create a new copy of table on disk and write into it only alive rows alter table jenkins.test alter column id type int; select pg, pg_size_pretty(pg) pz from pg_relation_size('test') pg; Still size of table is 672kb; Now let's create a new table copy of current table sized 672kb drop table if exists test1; create table test1 as select * from test; create unique index test1_id_pkey on test1 using btree(id); alter table test1 add primary key using index test1_id_pkey; analyze test1; select pg, pg_size_pretty(pg) pz from pg_relation_size('test1') pg Surprisingly size of this table is just 72kb. Vacuuming throw warning messages INFO: "test": found 0 removable, 10000 nonremovable row versions in 84 pages DETAIL: 9000 dead row versions cannot be removed yet. It is just an example. I tried to add more row up to 1_000_000 still the same. When table row become removable? How to deal with such situations or to be ready to? A: Your problem is this message from VACUUM (VERBOSE): INFO: "test": found 0 removable, 10000 nonremovable row versions in 84 pages DETAIL: 9000 dead row versions cannot be removed yet. That probably means that there ia a long running concurrent transaction that might still need the old row versions from before you issued the DELETE. Terminate all log running transactions and it will work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/41823584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to put video on Website I am new to working with videos and what i'm trying to accomplish is putting a video on my site. I have been researching and havent found to much, any help would be very much appreciated. Here is what I have so far. <embed "images/K36U21TR.wmv" width="300" height="300" /> A: My preffered method is to upload the video to YouTube and place it on your site using their embed code which is an iframe tag. This provides the benefit of your users using YouTube's bandwidth when they are watching the video rather than yours. Alternatively you could look at using the HTML5 VIDEO tag. http://www.w3schools.com/tags/tag_video.asp A: <video width="300" height="300" controls> <source src="images/K36U21TR.wmv" type="video/wmv"> </video> A: video tag : (Supprot : IE, Firefox, Chrome, Opera, Safari) <video width="320" height="240" controls="controls"> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> <source src="movie.webm" type="video/webm"> </video> embed tag : (Supprot : IE, Firefox, Chrome, Opera, Safari) <embed src="helloworld.swf">
{ "language": "en", "url": "https://stackoverflow.com/questions/13882726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Getting a cookie after a successful login? So I have an Angular App that has user login and authentication. When they login they go to a separate url and service, that's not a part of the angular template (not my choice, not my design, don't have freedom to change it). So we have our app url at https://my.app.com/appname And the login url (Which redirects to another URL that has the Spring CAS stuff) https://my.app.com:8082/api/applications/appname/user/login Which redirects to https://yours.app.com/CAS/login. After a successful login, we go back to the original app page. However, I need to somehow get the Cookie that has the username of the user logging in to the app. That cookie is a response cookie tied to https://my.app.com:8082/api/applications/appname/user/login but not the main url of the app. So how do I retrieve this cookie, preferably using ngCookie? For reference here's the backend code that handles this. @RequestMapping(method = RequestMethod.GET, value = "/login", headers = "Accept=application/json") public @ResponseBody HttpServletResponse login(HttpServletRequest request, HttpServletResponse response) { // toLog(Level.INFO, "Logging user in."); String referingURL = request.getHeader("referer"); _LOG.debug("Referer: " + referingURL); try { String user = "123456789"; user = SecurityUtils.getCurrentUsername(); Cookie userCookie = new Cookie("USERNAME", user); userCookie.setSecure(true); response.addCookie(userCookie); response.sendRedirect(referingURL); return response; } catch (Exception e) { // toLog(Level.ERROR, "Error logging user in", e); throw new ResourceNotFoundException(e); } } Where that Cookie userCookie line is.. that's the cookie I want to get. In even simpler terms. The url https://my.app.com:8082/api/applications/appname/user/login Has a response Cookie with a key called USERNAME, with the value of username I want. The app lives on https://my.app.com/appname, and I need to access the previously mentioned cookie. A: CAS does not set a cookie with the user login. It will set a cookie for your SSO session called a Ticket Granting Cookie (TGC). This token does not provide any information on the logged user. To retrieve the identity of the user logged you have to validate a Service Ticket. This ticket is appended to the url of your service when CAS/login redirect you back to you application. Then a CAS Client must validate that ticket against CAS/serviceValidate. That client should be in your backend and the username set in the session. Up to you to send it to your frontend the way you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/32745690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I write tests for file upload in PHP? I'm using simpleTest to write my PHP tests. I'm writing a file upload plugin and was wondering how I may be testing it. I would like to check that the file is correctly uploaded, in the right folder, that error are correctly returned when needed, etc. How do I emulate a file upload (through the $_FILES variable) ? Are there any issues I should be aware of ? A: According to the Docs, SimpleTest has support for FileUpload testing baked in since version 1.0.1: File upload testing Can simulate the input type file tag 1.0.1 I've looked over the examples at their site and would assume you'd use something along the lines of $this->get('http://www.example.com/'); $this->setField('filename', 'local path'); $this->click('Go'); to submit the file and then use the regular assertions to check the upload worked as wanted. But that's really just a wild guess, since I am not familiar with SimpleTest and I couldnt find an example at their homepage. You might want to ask in their support forum though. But basically, there is not much use testing that a form uploads a file. This is tried and tested browser behavior. Testing the code that handles the upload makes more sense. I dont know how you implemented your FileUpload code, but if I had to implement this, I would get rid of the dependency on the $_FILES array as the first thing. Create a FileRequest class that you can pass the $_FILES array to. Then you can handle the upload from the class. This would allow you to test the functionality without actually uploading a file. Just setup your FileRequest instance accordingly. You could even mock the filesystem with vfsStreamWrapper, so you dont even need actual files. A: You can generate a file upload in a programmatic manner with e.g. the curl extension. Since this requires PHP running under a web server, it's not much of a unit test. Consequently, the best way would be to to use PHPT tests and fill the --POST_RAW-- section with the data. If you don't know what to put in the --POST_RAW--, try to install the TamperData Firefox extension, do a file submission from Firefox, and copy-paste the data from the right side. A: I've found an alternate solution. I've spoofed the $_FILES array with test data, created dummy test files in the tmp/ folder (the folder is irrelevant, but I tried to stick with the default). The problem was that is_uploaded_file and move_uploaded_file could not work with this spoofed items, because they are not really uploaded through POST. First thing I did was to wrap those functions inside my own moveUploadedFile and isUploadedFile in my plugin so I can mock them and change their return value. The last thing was to extends the class when testing it and overwriting moveUploadedFile to use rename instead of move_uploaded_file and isUploadedFile to use file_exists instead of is_uploaded_file. A: For unit testing (as opposed to functional testing) try uploading a file (a short text file) to a test page, and var_dump($_FILES) and var_dump($_POST). Then you know what to populate them (or your mocks) with.
{ "language": "en", "url": "https://stackoverflow.com/questions/3402765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Best way to create generic/method consistency for sort.data.frame? I've finally decided to put the sort.data.frame method that's floating around the internet into an R package. It just gets requested too much to be left to an ad hoc method of distribution. However, it's written with arguments that make it incompatible with the generic sort function: sort(x,decreasing,...) sort.data.frame(form,dat) If I change sort.data.frame to take decreasing as an argument as in sort.data.frame(form,decreasing,dat) and discard decreasing, then it loses its simplicity because you'll always have to specify dat= and can't really use positional arguments. If I add it to the end as in sort.data.frame(form,dat,decreasing), then the order doesn't match with the generic function. If I hope that decreasing gets caught up in the dots `sort.data.frame(form,dat,...), then when using position-based matching I believe the generic function will assign the second position to decreasing and it will get discarded. What's the best way to harmonize these two functions? The full function is: # Sort a data frame sort.data.frame <- function(form,dat){ # Author: Kevin Wright # http://tolstoy.newcastle.edu.au/R/help/04/09/4300.html # Some ideas from Andy Liaw # http://tolstoy.newcastle.edu.au/R/help/04/07/1076.html # Use + for ascending, - for decending. # Sorting is left to right in the formula # Useage is either of the following: # sort.data.frame(~Block-Variety,Oats) # sort.data.frame(Oats,~-Variety+Block) # If dat is the formula, then switch form and dat if(inherits(dat,"formula")){ f=dat dat=form form=f } if(form[[1]] != "~") { stop("Formula must be one-sided.") } # Make the formula into character and remove spaces formc <- as.character(form[2]) formc <- gsub(" ","",formc) # If the first character is not + or -, add + if(!is.element(substring(formc,1,1),c("+","-"))) { formc <- paste("+",formc,sep="") } # Extract the variables from the formula vars <- unlist(strsplit(formc, "[\\+\\-]")) vars <- vars[vars!=""] # Remove spurious "" terms # Build a list of arguments to pass to "order" function calllist <- list() pos=1 # Position of + or - for(i in 1:length(vars)){ varsign <- substring(formc,pos,pos) pos <- pos+1+nchar(vars[i]) if(is.factor(dat[,vars[i]])){ if(varsign=="-") calllist[[i]] <- -rank(dat[,vars[i]]) else calllist[[i]] <- rank(dat[,vars[i]]) } else { if(varsign=="-") calllist[[i]] <- -dat[,vars[i]] else calllist[[i]] <- dat[,vars[i]] } } dat[do.call("order",calllist),] } Example: library(datasets) sort.data.frame(~len+dose,ToothGrowth) A: Use the arrange function in plyr. It allows you to individually pick which variables should be in ascending and descending order: arrange(ToothGrowth, len, dose) arrange(ToothGrowth, desc(len), dose) arrange(ToothGrowth, len, desc(dose)) arrange(ToothGrowth, desc(len), desc(dose)) It also has an elegant implementation: arrange <- function (df, ...) { ord <- eval(substitute(order(...)), df, parent.frame()) unrowname(df[ord, ]) } And desc is just an ordinary function: desc <- function (x) -xtfrm(x) Reading the help for xtfrm is highly recommended if you're writing this sort of function. A: There are a few problems there. sort.data.frame needs to have the same arguments as the generic, so at a minimum it needs to be sort.data.frame(x, decreasing = FALSE, ...) { .... } To have dispatch work, the first argument needs to be the object dispatched on. So I would start with: sort.data.frame(x, decreasing = FALSE, formula = ~ ., ...) { .... } where x is your dat, formula is your form, and we provide a default for formula to include everything. (I haven't studied your code in detail to see exactly what form represents.) Of course, you don't need to specify decreasing in the call, so: sort(ToothGrowth, formula = ~ len + dose) would be how to call the function using the above specifications. Otherwise, if you don't want sort.data.frame to be an S3 generic, call it something else and then you are free to have whatever arguments you want. A: I agree with @Gavin that x must come first. I'd put the decreasing parameter after the formula though - since it probably isn't used that much, and hardly ever as a positional argument. The formula argument would be used much more and therefore should be the second argument. I also strongly agree with @Gavin that it should be called formula, and not form. sort.data.frame(x, formula = ~ ., decreasing = FALSE, ...) { ... } You might want to extend the decreasing argument to allow a logical vector where each TRUE/FALSE value corresponds to one column in the formula: d <- data.frame(A=1:10, B=10:1) sort(d, ~ A+B, decreasing=c(A=TRUE, B=FALSE)) # sort by decreasing A, increasing B
{ "language": "en", "url": "https://stackoverflow.com/questions/6836963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Composer ErrorException when installing libraries I'm working on installing a codebase from github (which is still in Pre-release stages). I am able to clone, from GitHub, to my working WAMP server. When I try to run "composer install" it eventually runs into an exception and I'm not entirely sure how to fix it? Am I missing local libraries in PEAR / php? Writing lock file Generating autoload files exception 'ErrorException' with message 'call_user_func() expects parameter 1 to be a valid callback, function 'mb_strto lower' not found or invalid function name' in C:\Apache24\htdocs\streams\vendor\laravel\framework\src\Illuminate\Support \Pluralizer.php:258 The exception as a gist with stack trace and more: https://gist.github.com/markbratanov/386be4c492dc16b8b43f Any help / comments / advice would be appreciated A: You need to install / enable the mbstring extension. Further information can be found on php.net
{ "language": "en", "url": "https://stackoverflow.com/questions/27714486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mixed Content - Trying to call http api over https I deployed my app to Netlify when it broke and gave the following error. Mixed Content: The page at 'https://example.netlify.app/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://ip-api.com/json/'. This request has been blocked; the content must be served over HTTPS. I tried to call the api with https with no luck. Here's how I'm calling it: useEffect(() => { axios.get('http://ip-api.com/json/') .then(res => setSearch(prev => ({...prev, ip: res.data.query, city: res.data.city, country: res.data.country, timezone: res.data.timezone, isp: res.data.isp, lat: res.data.lat, lon: res.data.lon, region: res.data.region}))) .catch(err => console.log(err)); }, []);
{ "language": "en", "url": "https://stackoverflow.com/questions/66251493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }