jQuery / Datatables, make ajax request upon click event whilst still handling DT events Posted: 29 Jun 2021 08:59 AM PDT I am looking to delay a particually heavy Datatables AJAX request until a specific part of the navigation has been clicked, whilst still retaining the event handlers it offers. Here is my code so far: $(document).ready(function() { ... var traineesTable = $("#traineesTableId").DataTable({ pageLength: 12, ordering: false, searching: false, processing: true, serverSide: true, lengthChange: false, select: 'multi', ajax: { url: '', dataType: "json", type: "post", data: function(d) { var formdata = $("#traineesSearchFormId :input").serializeArray(); var data = {}; $(formdata).each(function(index, obj) { data[obj.name] = obj.value; }); d = $.extend(d, data); return d; } }, ... }); // Navigation handler $('a[data-target="#trainees"]').click(function () { traineesTable.ajax.url = window.ajax_get_trainees_url; traineesTable.ajax.reload(); }); $("#trainee-search-button").click(function(e) { this.value = gettext("Please Wait"); this.disabled = true; traineesTable.clear(); traineesTable.ajax.reload(); traineesTable.draw(); this.value = gettext("Search"); this.disabled = false; }); // Additional DT functionality I want to keep traineesTable.on('select', function (e, dt, type, indexes) { if (type === 'row') { var row = traineesTable[type](indexes).nodes().to$(); $("#trainees_ids").val($("#trainees_ids").val() + row.children().first().html() + ','); row.find('.checkbox-box').addClass('checked'); } }); }); This obviously causes issues in that DataTables expects a valid url and throws up an alert as it isn't defined. I've tried moving the traineesTable creation to within the click() handler but then I get errors that traineesTable isn't defined. I feel this should be so simple... |
YoutubeSearchPython error: Could not make request Posted: 29 Jun 2021 08:58 AM PDT I made an application in Windows using the library youtubesearchpython and using the following code, it worked perfectly: from youtubesearchpython import Search searchString = "any song here" search = Search(searchString, limit=1) print(search.result()) But, when I changed to macOS, the same code did not work and returned: Exception: Could not make request. I tried uninstalling and reinstalling the library, but nothing happens. Does anyone have any ideia as to why this is happening? |
How to create a poster using data from form? Posted: 29 Jun 2021 08:58 AM PDT I want to let my users enter few details in a form and when they submit a image is generated using these details. How can i do this. |
Javascript HTML DOM is not working in Browser but html, css and js files work Posted: 29 Jun 2021 08:58 AM PDT I am learning JS from one YT tutorial - I followed the exact same code, taught in the tutorial, but I didn't get proper output. Output showed in Tutorial after entering the Input in prompt: Output I got after entering the input in prompt(Entering year of birth): Code: index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="css/style.css"> <title>Javascript on Steroids</title> </head> <body> <div class="container-1"> <h2>Challenge 1: Your Age in Days</h2> <div class="flex-box-container-1"> <div> <button class="btn btn-primary" onclick="ageInDays()">Click me</button> </div> <div> <button class="btn btn-danger" onclick="reset()">Reset</button> </div> </div> <div class="flex-box-container-1"> <div id="flex-box-result"> </div> </div> </div> <script src = "js/script.js"></script> </body> </html> script.js //challenge 1: your age in days function ageInDays() { var birthyear = prompt("What year where you born "); var age = (2021 - birthyear) * 360; let h1 = document.createElement('h1'); let textAnswer = document.createTextNode("You are "+ age + " days old"); h1.setAttribute('id', 'ageInDays'); h1.appendChild(textAnswer); document.getElementsById("flex-box-result").appendChild(h1); } function reset() { document.getElementById("ageInDays").remove(); style.css .container-1 { border: 1px solid black; } .flex-box-container-1{ display: flex; border : 1px solid black; padding: 10px; flex-wrap: wrap; flex-direction: row; justify-content: space-around; } .flex-box-container-1 div{ display: flex; padding: 10px; border: 1px solid black; align-items: center; } |
I am un able to solve the below problem can you please provide assistnace Posted: 29 Jun 2021 08:58 AM PDT Create a trigger named trgBeforeInsert on the t_order_details table to validate the quantity. If the quantity entered is less than 0 while inserting data to the table, then insert the exception message and log_date into the t_log_err table. Trigger name: trgBeforeInsert Exception Message: "ORA-20000: Quantity should be greater than 0". Design rules: Trigger name MUST NOT be changed Exception message MUST NOT be changed |
Use userform with Checkboxes to create an array in a single cell VBA Posted: 29 Jun 2021 08:58 AM PDT I trying to use checkboxes in a userform to create an array in a single cell and then use that cell to filter a table with an Array as the Creteria. My code works if one value is input into the cell but once I have more than one value in the cell the filter does not work. I could use some help. This is the code I am using to input the values into cell A2 in my TestSettings workbook `Private Sub SubmitSettings_Click() 'DECLARE VARIABLES Dim contr As Control Dim arrType As String 'ACTIVATE SETTINGS WORKSHEET AND FIND FIRST CELL IN COLUMN A Workbooks("TestSettings.xlsm").Activate 'LOOP THROUGH CHECKBOXES For Each contr In SettingsForm.Controls 'CHECKS IF CONTROL TYPE IS A CHECKBOXS If TypeName(contr) = "CheckBox" Then 'CHECKS IF VALUE IS TRUE If contr.Value = True Then 'COMBINE VALUES INTO SINGLE STRING SEPERATED BY , If arrType = "" Then arrType = contr.Caption Else arrType = arrType & "," & contr.Caption End If Else Debug.Print "False" End If End If Next contr ActiveSheet.Range("A2").Value = Array(arrType) End Sub ` This is the code I am using to filter the table i want to filter in my TestProject workbook `Sub FilterTypes() 'DECLARE VARIABLES Dim arType As Variant 'ACTIVATE SETTINGS WORKBOOK Workbooks("TestSettings.xlsm").Activate 'SET VALUES arType = ActiveSheet.Range("A2").Value 'ACTIVATE TESTPROJECT WORKBOOK Workbooks("TestProject.xlsm").Sheets("Project").Activate 'FILTER BY TYPE ActiveSheet.ListObjects("ProjectTestTable1").Range.AutoFilter Field:=1, _ Criteria1:=Array(arType), Operator:=xlFilterValues End Sub ` If cell A2 = A the filter works If cell A2 = A,B the filter does not work. |
Flagging a row according to the various amount of neighbour values in a pandas dataframe Posted: 29 Jun 2021 08:58 AM PDT I got a transactional operation that produces a feed like below: df = pd.DataFrame({'action':['transacted','transacted','transacted','transacted','undo','transacted','transacted','transacted','transacted','transacted','undo','undo','undo','transacted'], 'transaction_count':[1,2,3,4,4,4,5,6,7,8,8,7,6,5]}) | action | transaction_count | 0 | transacted | 10 | 1 | transacted | 20 | 2 | transacted | 35 | 3 | transacted | 60 | 4 | undo | 60 | 5 | transacted | 60 | 6 | transacted | 80 | 7 | transacted | 90 | 8 | transacted | 100 | 9 | transacted | 10 | 10 | undo | 10 | 11 | undo | 100 | 12 | undo | 90 | 13 | transacted | 90 | The counts are in a pattern but not in a linear way. (10-20-35-60-80-90-100-10-20...) undo states which transaction count is cancelled. There can be multiple undo's for multiple cancellations. # This is an initial apply, to set it up df['is_undone']=df.apply(lambda x: 1 if x['action']=='undo' else 0, axis=1).shift(-1) df=df.fillna(0) # For shift df=df.loc[df['is_undone']==0] df=df.fillna(0) df=df.loc[df['action']!='undo'] df.reset_index(drop=True,inplace=True) Unfortunately, it only works for single undo but not for multiple in a row. Apply does not let accessing neighbour row values and I can't think of any else solution. It should also need to calculate 300k rows, so, performance is also an issue. Expected result is: | action | transaction_count | 0 | transacted | 10 | 1 | transacted | 20 | 2 | transacted | 35 | 3 | transacted | 60 | 4 | transacted | 80 | 5 | transacted | 90 | Thanks in advance! |
MySQL Creating Stored Procedure Posted: 29 Jun 2021 08:58 AM PDT I tried creating a stored procedure from the question below but when I test it using the values from my tables in my database, it is not giving me the correct output. Meaning if it should output 1, it outputs 2 instead. Please help me figure what I did wrong. Question and my sql statement is below. Question: Create a stored procedure to compare the actual incomes of two employees. If the former is higher than the latter, output 1; otherwise, output 2. Delimiter $$ CREATE PROCEDURE real_income(in employeeID_1 varchar(6), in employeeID_2 varchar(6), out c int) BEGIN IF (SELECT income-outcome FROM salary WHERE employeeID=employeeID_1)> (SELECT income-outcome FROM salary WHERE employeeID=employeeID_2) THEN SET c = 1; ELSE SET c = 2; END IF; END $$ |
loop gives me error. If i have error i wana go for next cell Posted: 29 Jun 2021 08:58 AM PDT i have this code. I need a help. When in pivot tabel3 vba couldnt find this: Sheets("EXO").Range("N" & y).Value i wana go for next cell until vba do not find this this Sheets("EXO").Range("N" & y).Value and after then vba should do copy and paste part of loop Could u please help me ? Sub FILL_vALUES_EXO() i = 1 y = 9 rng = Application.WorksheetFunction.CountA(Worksheets("EXO").Range("N9:N67")) Do While i < rng Application.CutCopyMode = False Sheets("EXO").Range("N" & y).copy ActiveSheet.PivotTables("PivotTable3").PivotFields("RootCause").ClearAllFilters ActiveSheet.PivotTables("PivotTable3").PivotFields("RootCause").CurrentPage = _ Sheets("EXO").Range("N" & y).Value Range("B6").Select Selection.End(xlDown).Select Range(Selection, Selection.End(xlToRight)).Select Selection.copy Range("O" & y).Select ActiveSheet.Paste Range("O4").Select Application.CutCopyMode = False Selection.copy Range("O" & y & ":R" & y).Select Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False Application.CutCopyMode = False y = y + 1 i = i + 1 end sub |
Download files to user device using php Posted: 29 Jun 2021 08:58 AM PDT I have a website where user can click on the download button and the file in my drive will get downloaded in the user device. I made a code and it works file when I am doing it on laptop, then for testing I used KSWEB (for localhost server on my android). when I download the file in android it gets downloaded but in htdocs folder which is a folder of the web server KSWEB just same as the htdocs of XAMPP in computer. Now I am worried what will happen when user will download the file, where will it get stored? or will it give any other like path does not exist? How can I download the file in all of the devices. this the code which I have tried and which works in laptop $dir = getenv("HOMEDRIVE") . getenv("HOMEPATH").'\Downloads\\'; $filelink="https://drive.google.com/uc?id=1Tvoj7JFUaL3RKWOHiLjsJZHUIEgVqriu&export=media"; $file=file_get_contents($filelink); $s=file_put_contents($dir."file3.doc",$file); |
Campo Minado em C Posted: 29 Jun 2021 08:58 AM PDT Tenho que desenvolver uma versão de campo minado onde o usuário entra com a dimensão e as posições que são bombas (b) ou estão livres (x), em seguida esse mesmo usuário seleciona as coordenadas x e y do campo, estou com dificuldade para fazer com que quando uma posição seja revelada as adjacentes também sejam e verificar depois do número de tentativas terminar o jogo. No código que escrevi quando b (bomba) é encontrado o jogo termina, como desejado, se não as tentativas continuam, mas quando deveriam acabar cai no if que deveria verificar se todas as coordenadas foram escolhidas. Link do exercício: https://docs.google.com/document/d/1aF2_p4jpKiO2GEX7fAseWxo1axzk7Kp-WxE7n2gr1pY/edit?usp=sharing int x, y, jogada, aux = 0; printf("numero de jogada: "); scanf("%d", &jogada); while (1) { printf("posicoes x e y de cada jogada: "); scanf("%d %d", &x, &y); if (matriz[x][y] == 'x') /* Celula sem bomba */ { aux++; if (aux == jogada) { for (int i = 0; i < TAM; i++) { for (int j = 0; j < TAM; j++) { if (matriz[i][j] == 'x') { printf("GANHOU\n"); return 0; } } } return 1; } if (aux >= jogada) { return 0; } } else if (matriz[x][y] == 'b') /* Celula com bomba */ { printf("\nPERDEU\n"); return 0; /* Fim de Jogo! */ } } |
How to change decimal separator in ExecuteReader c# Posted: 29 Jun 2021 08:58 AM PDT How to change decimal separator in string, e.g. in mnoz_obj item the returned value is 24,000 and I need to have 24.000. The values are from database to JSON. I tried ToString(new CultureInfo etc.) but this doesn't work. I expect that myString.Replace(",",".") is not correct way to do it. public static string getDoklad() { var dbCon = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString; string[] fileArguments = Environment.GetCommandLineArgs(); List<ZebraPolozky> zebraPolozky = new List<ZebraPolozky>(); using (var cn = new OdbcConnection(dbCon)) { OdbcCommand cmd = cn.CreateCommand(); cmd.CommandText = "SELECT * FROM cis06zebrap"; cn.Open(); using (var reader = cmd.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { ZebraPolozky zebraPolozka = new ZebraPolozky { doklad = reader["doklad"].ToString(), sklad = reader["sklad"].ToString(), reg = reader["reg"].ToString(), mnoz_obj = reader["mnoz_obj"].ToString(), mnoz_vyd = reader["mnoz_vyd"].ToString(), kc_pce = reader["kc_pce"].ToString(), sarze = reader["sarze"].ToString(), datspo = reader["datspo"].ToString(), veb = reader["veb"].ToString(), poc2 = reader["poc2"].ToString(), pvp06pk = reader["pvp06pk"].ToString(), znacky = reader["znacky"].ToString(), stav = reader["stav"].ToString(), //prac = reader["prac"].ToString(), //exp = reader["exp"].ToString() }; zebraPolozky.Add(zebraPolozka); } } } cn.Close(); } //var collw = new { polozky = zebraPolozky }; var jsonString = JsonConvert.SerializeObject(zebraPolozky); return jsonString; } { "doklad": "568375", "sklad": "901", "reg": "185121", "mnoz_obj": "24,000", "mnoz_vyd": "0,000", "kc_pce": "240,72", "sarze": "", "datspo": "", "veb": "24,00", "poc2": "1", "pvp06pk": "116783437", "znacky": "R1902", "stav": "0" } |
SCSS: Can I only @include in response to a successful @media? Posted: 29 Jun 2021 08:58 AM PDT With SCSS files, I am attempting to make a responsive layout by setting variables in response to an @media query. I currently have two @media queries, and I was hoping that only one of them would proceed to call the @mixin, with the map defined for the specific situation: mobile or desktop. My code is : $page-header-height : 45px; // some dummy defaults $page-subheader-height: 45px; $page-footer-height : 50px; $mobile-varmap : ( "page-header-height" : 50px, "page-subheader-height": 50px ); $desktop-varmap : ( "page-header-height" : 90px, "page-subheader-height": 120px ); @mixin setvariables($map) { $page-header-height: map-get($map, "page-header-height") !global; $page-subheader-height: map-get($map, "page-subheader-height") !global; $page-footer-height: 50px; } $screen-size-mobile: 360px; $screen-size-tablet: 600px; @media screen and (min-width:$screen-size-mobile) { body { @include setvariables($mobile-varmap); } } @media screen and (min-width:$screen-size-tablet) { body { @include setvariables($desktop-varmap); } } div.page-wrapper { display: grid; grid-template-areas: 'page-header''page-subheader''page-content''page-footer'; grid-template-columns: auto; grid-template-rows: $page-header-height $page-subheader-height 1fr $page-footer-height; max-height: calc(100vh - 55px); // TODO: use variables to calc these min-height: calc(100vh - 50px); overflow: none; } I had expected that this would lead to $page-header-height, etc, being set according to the matching @media query, but the result is that whichever call to setvariables() is make last, determines the values which are produced. What would I need to do in order to call setvariables() with the varmap that corresponds to the screen size? |
Check two conditions in line Posted: 29 Jun 2021 08:58 AM PDT I have the following lines and I want to match the first one based one the condition that it starts with a '%' and contains a '=' sign: % This comment is = True % This comment is equal true I want to use python's 're' module to be able to extract the first sentence on the basis that it starts with a '%' and contains a '=' So far, I have gathered that I need something like: ... if re.match('^%' ,line): ... but cannot figure out the rest. Thank you! |
Got the JWT Token by calling the external corejwtapi in asp.net mvc5 application Posted: 29 Jun 2021 08:58 AM PDT After getting the JWT Token from external jwtcoreapi, how will I use the JWT token with mvc existing authentication and authorization, I have also got username and password and token from the external API. I am using this functionality on mvc application to logon with api database credentials. got the token by calling external api var token = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.JwtTokenViewModel> (response.Content); I have a question here,how to to call the token with existing mvc default web application authentication and authorization.please help me. here is code : - var client = new RestClient(ConfigurationManager.AppSettings["baseApiUrl"]) { Timeout = -1 }; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); var body = new { model.username, model.password }; request.AddParameter("application/json", Newtonsoft.Json.JsonConvert.SerializeObject(body), ParameterType.RequestBody); var response = await client.ExecuteAsync(request); if (!response.IsSuccessful) { ModelState.AddModelError("", $"{AppConstants.ErrorMessage}"); return View(model); } if (response.StatusCode == System.Net.HttpStatusCode.OK) { var token = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.JwtTokenViewModel>(response.Content); if (token != null && !string.IsNullOrWhiteSpace(token.Token)) { model.SuccessMessage = $"{AppConstants.SuccessMessage}"; return View(model); } } |
How to count and populate values from two different dataframe columns? Posted: 29 Jun 2021 08:58 AM PDT df1['col1']=['aa_1','aa_1','aa_1','aa_2','aa_2','bb_2','bb_2','bb_3','bb_3','bb_3','cc_1','cc_1', 'cc_3','cc_3'] df2['col2']=['aa_3','aa_3','aa_3','bb_1','bb_1','bb_1','cc_2','cc_2', 'cc_2'] I want to add the column values from df2['col2'] to df1['col1'] depending on the value count in df1. For example - if value count of 'aa_2' < value count of 'aa_1' in df1 then all of 'aa_3' in df2 should be added in 'aa_2' in df1 also changing their name to 'aa_2' as well and
- same logic as described above for 'bb'
- 'cc_2' in df2 should be added into 'cc_1' in df1 if count of cc_1 and cc_3 is equal
conditions must be checked in df1 and if a condition is met then values from df2 should be added to the df1['col1'] output be like this df1['col1']=['aa_1','aa_1','aa_1','aa_2','aa_2','bb_2','bb_2','bb_3','bb_3','bb_3','cc_1','cc_1', 'cc_3','cc_3','aa_2','aa_2','aa_2','bb_2','bb_2','bb_2','cc_1','cc_1', 'cc_1'] Is there is a way to do this in pandas DataFrame? I have 100,000 rows like this to add from df2 to df1. |
Detect key presses only when window in focus - Python keyboard module Posted: 29 Jun 2021 08:58 AM PDT I am using the keyboard module in python to detect key presses. I am making a console application. It detects key presses even when the console window is not in focus. Is there a way to only detect key presses when the console window is in focus? I am using keyboard.is_pressed() inside a while loop to detect the key presses. Please help. Thank you! |
Next lines of code executes before getting API response in Angular 11 Posted: 29 Jun 2021 08:58 AM PDT In my form there are some Checkboxes. Checkboxes are dynamically generated based on the values getting from API response. If the API response is not null and there is some value then I want to make the checkbox required. But the API response returns null value then the checkbox is not required. This I want in my form. So I have written the below code. Roles: RoleInfo[] = []; ngOnInit(): void { this.createForm(); this.accountSubscription = this.regService.getRoles().subscribe(data => { if (data) { this.Roles = data; } }); if (this.Roles.length > 0) { this.arrayInput.setValidators(Validators.required); } else { this.arrayInput.setValidators(null); } this.arrayInput.updateValueAndValidity(); } But the problem is it does not wait for API response and executes the next lines of code. So the Checkboxes are always set to NOT Required. How can I solve the problem? |
to find the highest number entered among three in c Posted: 29 Jun 2021 08:58 AM PDT how to find the highest number among three input?? anyone help me to find out the solution this is simple mistake but it is hard to find out the mistake for me so asking for your help #include<stdio.h> int main(){ int a,b,c,d; printf("enter first number"); scanf("%d",&a); printf("enter second number"); scanf("%d",&b); printf("enter third number"); scanf("%d",&c); if(a<=b>=c){ printf("higest number is b %d",b); } else if(b<=c>=a){ printf("higest number is c %d",c); } else if(c<=a>=b){ printf("higest number isd %d",a); } return 0; } |
Error when loading or refreshing Ionic app, but works when when navigating back to it Posted: 29 Jun 2021 08:58 AM PDT I have very little experience with Vue and I'm also new to Ionic, so I'm not sure what is going on here. I'm trying to add IonSlides to my app, but I always get errors when loading or refreshing the page, however it works as expected if I navigate to some other site then hit back button in browser. Just to be clear, I run the project with ionic serve , open it at http://localhost:8100/ it's not working, then navigate to let's say google.com, hit back button in browser to navigate back to http://localhost:8100/ and it's working as expected, then if I refresh the page I got the same errors again. Errors: runtime-core.esm-bundler.js?5c40:38 [Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next at <Anonymous key=1075 > at <IonSlides pager="true" > at <Slides pack_id="180" > at <Anonymous> at <IonPage isInOutlet=true registerIonPage=fn<registerIonPage> > at <BaseLayout page-title="Pack 180" back-link="/month/6" isInOutlet=true ... > at <Pack ref=Ref< Proxy {…} > key="/pack/180" isInOutlet=true ... > at <IonRouterOutlet id="main-content" > at <IonApp> at <App> Uncaught (in promise) DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. at insert (webpack-internal:///./node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js:222:16) at mountElement (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:3958:9) at processElement (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:3899:13) at patch (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:3819:21) at componentEffect (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:4312:21) at reactiveEffect (webpack-internal:///./node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js:71:24) at effect (webpack-internal:///./node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js:46:9) at setupRenderEffect (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:4277:89) at mountComponent (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:4235:9) at processComponent (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:4195:17) insert @ runtime-dom.esm-bundler.js?830f:11 mountElement @ runtime-core.esm-bundler.js?5c40:3857 processElement @ runtime-core.esm-bundler.js?5c40:3789 patch @ runtime-core.esm-bundler.js?5c40:3709 componentEffect @ runtime-core.esm-bundler.js?5c40:4211 reactiveEffect @ reactivity.esm-bundler.js?a1e9:42 effect @ reactivity.esm-bundler.js?a1e9:17 setupRenderEffect @ runtime-core.esm-bundler.js?5c40:4176 mountComponent @ runtime-core.esm-bundler.js?5c40:4134 processComponent @ runtime-core.esm-bundler.js?5c40:4094 patch @ runtime-core.esm-bundler.js?5c40:3712 patchKeyedChildren @ runtime-core.esm-bundler.js?5c40:4450 patchChildren @ runtime-core.esm-bundler.js?5c40:4333 processFragment @ runtime-core.esm-bundler.js?5c40:4084 patch @ runtime-core.esm-bundler.js?5c40:3705 patchKeyedChildren @ runtime-core.esm-bundler.js?5c40:4414 patchChildren @ runtime-core.esm-bundler.js?5c40:4357 patchElement @ runtime-core.esm-bundler.js?5c40:3981 processElement @ runtime-core.esm-bundler.js?5c40:3792 patch @ runtime-core.esm-bundler.js?5c40:3709 componentEffect @ runtime-core.esm-bundler.js?5c40:4278 reactiveEffect @ reactivity.esm-bundler.js?a1e9:42 callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:154 flushJobs @ runtime-core.esm-bundler.js?5c40:362 Promise.then (async) queueFlush @ runtime-core.esm-bundler.js?5c40:264 queueJob @ runtime-core.esm-bundler.js?5c40:258 run @ reactivity.esm-bundler.js?a1e9:183 trigger @ reactivity.esm-bundler.js?a1e9:189 scheduler @ reactivity.esm-bundler.js?a1e9:819 run @ reactivity.esm-bundler.js?a1e9:183 trigger @ reactivity.esm-bundler.js?a1e9:189 set @ reactivity.esm-bundler.js?a1e9:291 GET_PACK_CARDS @ index.js?4360:62 wrappedMutationHandler @ vuex.esm-browser.js?5502:808 commitIterator @ vuex.esm-browser.js?5502:438 eval @ vuex.esm-browser.js?5502:437 _withCommit @ vuex.esm-browser.js?5502:596 commit @ vuex.esm-browser.js?5502:436 boundCommit @ vuex.esm-browser.js?5502:376 eval @ index.js?4360:153 Promise.then (async) getPackCards @ index.js?4360:151 wrappedActionHandler @ vuex.esm-browser.js?5502:815 dispatch @ vuex.esm-browser.js?5502:488 boundDispatch @ vuex.esm-browser.js?5502:373 mounted @ Slides.vue?6b1b:41 callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:154 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js?5c40:163 hook.__weh.hook.__weh @ runtime-core.esm-bundler.js?5c40:1910 flushPostFlushCbs @ runtime-core.esm-bundler.js?5c40:333 render @ runtime-core.esm-bundler.js?5c40:4796 mount @ runtime-core.esm-bundler.js?5c40:3019 app.mount @ runtime-dom.esm-bundler.js?830f:1220 eval @ main.js?56d7:38 Promise.then (async) eval @ main.js?56d7:37 ./src/main.js @ app.js:1520 __webpack_require__ @ app.js:854 fn @ app.js:151 1 @ app.js:1892 __webpack_require__ @ app.js:854 checkDeferredModules @ app.js:46 (anonymous) @ app.js:994 (anonymous) @ app.js:997 Code: <template> <base-layout :page-title="`Pack ${pack.id}`" :back-link="`/month/${pack.month_id}`"> <h2 v-if="!pack">Could not find pack...</h2> <slides :pack_id="packId"></slides> </base-layout> </template> <script> import Slides from './Slides.vue'; export default { components: { Slides, }, data() { return { packId: this.$route.params.id } }, watch: { '$route'(currentRoute) { this.packId = currentRoute.params.id; }, }, computed: { pack() { return this.$store.getters.pack; }, }, mounted(){ this.$store.dispatch('getPack', {id: this.packId}); } } </script> Slides.vue <template> <ion-slides pager="true"> <ion-slide v-for="slide in slides" :key="slide.id"> <card :card_id="slide.id"></card> </ion-slide> </ion-slides> </template> <script> import { IonSlides, IonSlide } from '@ionic/vue'; import Card from './Card.vue'; export default { props: ['pack_id'], components: { IonSlides, IonSlide, Card }, data() { return { packId: this.$route.params.packId, } }, setup() { // Optional parameters to pass to the swiper instance. See http://idangero.us/swiper/api/ for valid options. const slideOpts = { initialSlide: 1, speed: 400 }; return { slideOpts } }, computed: { slides() { return [...this.$store.getters.packCards]; } }, mounted(){ this.$store.dispatch('getPackCards', {id: this.pack_id ?? this.packId}); } } </script> I guess I made some trivial mistake somewhere, could anyone help? Thanks. EDIT: I guess, I figured it out what the problem is, but I'm not sure how to solve it. In the Slides.vue: computed: { slides() { return this.$store.getters.packCards } The above code first returns and Proxy with and empty array target or some default values if I set so, but then the mounted(){ this.$store.dispatch('getPackCards', {id: this.pack_id ?? this.packId}); } updates this.$store.getters.packCards and slides fails to re-render. I tried to use created or beforeMount instead of mounted , but it's the same. |
I Run my flutter project in android studio and try to use an IPhone 12 simulator but the Xcode builld fails everytime Posted: 29 Jun 2021 08:58 AM PDT I am working on a Macbook Pro 2019. I want to use Firebase/Auth, Firebase/Firestore, Firebase/Analytics and Firebase/Core. I think there is something wrong with the podfile. Podfile: # Uncomment this line to define a global platform for your project platform :ios, '10.0' # Add the Firebase pod for Google Analytics #pod 'Firebase/Analytics' # For Analytics without IDFA collection capability, use this pod instead # pod 'Firebase/AnalyticsWithoutAdIdSupport' # Add the pods for any other Firebase products you want to use in your app # For example, to use Firebase Authentication and Cloud Firestore #pod 'Firebase/Auth' #pod 'Firebase/Firestore' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' project 'Runner', { 'Debug' => :debug, 'Profile' => :release, 'Release' => :release, } def flutter_root generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) unless File.exist?(generated_xcode_build_settings_path) raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end File.foreach(generated_xcode_build_settings_path) do |line| matches = line.match(/FLUTTER_ROOT\=(.*)/) return matches[1].strip if matches end raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" end require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) flutter_ios_podfile_setup target 'Runner' do pod 'Firebase/Analytics' pod 'Firebase/Auth' pod 'Firebase/Core' pod 'Firebase/Firestore' use_frameworks! use_modular_headers! flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0' end end end Flutter doctor: [✓] Flutter (Channel stable, 2.2.1, on macOS 11.2.3 20D91 darwin-x64, locale en-GB) [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3) [✓] Xcode - develop for iOS and macOS [✓] Chrome - develop for the web [✓] Android Studio (version 4.1) [✓] Connected device (2 available) • No issues found! AppDelegate.swift: import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() return true } } Error: Running "flutter pub get" in ProjectZeus... Launching lib/main.dart on iPhone 12 Pro Max in debug mode... Running pod install... Running Xcode build... Xcode build done. 10.8s Failed to build iOS app Error output from Xcode build: ↳ ** BUILD FAILED ** Xcode's output: ↳ 1 error generated. note: Using new build system note: Building targets in parallel note: Planning build note: Analyzing workspace note: Constructing build description note: Build preparation complete warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from project 'Runner') Could not build the application for the simulator. Error launching application on iPhone 12 Pro Max. Thank you in Advance |
R: divide a given Box into X amount of new boxes with given diagonal Posted: 29 Jun 2021 08:58 AM PDT I have a BBOX of Germany with coordinates (lon,lat): g_bbox<-c(xmin=5.98865807458, ymin=47.3024876979, xmax=15.0169958839, ymax=54.983104153) I would like to divide the bbox in (x) amount of bboxes with a diagonal of 50 km each. The length of diagonal can vary a little (+/-10km). The Resulting BBoxes should not overlap. The amount of BBoxes (x) should be the maximum number of BBoxes that fit into the g_bbox The result I would like to have is in best case a data frame with xmin,ymin,xmax,ymax columns. How would I go about it? |
discord.ext.commands.errors.MissingRequiredArgument: bot is a required argument that is missing Posted: 29 Jun 2021 08:58 AM PDT main.py import os import discord from discord.ext import commands, tasks bot = commands.Bot(command_prefix=commands.when_mentioned_or('moon '), case_insensitive=True) my_secret = os.environ['token'] for file in os.listdir("./cogs"): if file.endswith(".py"): name = file[:-3] bot.load_extension(f"cogs.{name}") for utility in os.listdir("./cogs/utility"): if utility.endswith(".py"): name = utility[:-3] bot.load_extension(f"cogs.utility.{name}") @bot.event async def on_ready(): print('🌙 {} está online!'.format(bot.user.name)) bot.run(my_secret) ping.py import discord from discord.ext import commands class Utility(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def ping(self, ctx, bot): await ctx.send('A Lua está com {}ms'.format(bot.latency * 100)) def setup(bot): bot.add_cog(Utility(bot)) when I use the ping command, I get this error: discord.ext.commands.errors.MissingRequiredArgument: bot is a required argument that is missing. |
The pager property doesn't function once the rowNum property is set Posted: 29 Jun 2021 08:58 AM PDT I am new to using jqGrid! When displaying the data in form of a table, I set the rowNum property to display 5 rows but when I do so the pagination{pager: true} stops working. Here is the jqGrid function and the data that is being displayed along with the incorrect table that is being displayed. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/css/ui.jqgrid.min.css"> @*<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />*@ <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/jquery.jqgrid.min.js"></script> <script> $(function () { "use strict"; $("#table").jqGrid({ url: '@Url.Action("Data","Cart")', mtype: "GET", datatype: "json", colModel: [ { name:"ID", label:"ID", width: 150 }, { name:"Name", label:"Product", width:150 }, { name:"Description", label:"Description", width: 150 }, { name:"Price", label:"Price", width: 150 } ], guiStyle: "bootstrap4", viewrecords: true, toppager: true, pager: true, rowNum: 5, rowList: [10, 20, 30], rownumbers: true, caption: "Products Table", }); /*jQuery("#table").setGridParam({ rowNum: 10 }).trigger("reloadGrid");*/ $("#table").jqGrid('navGrid', { edit: true, add: true, delete: true }); }); </script> This is the displayed table with pagination not working! This is the Data to be Displayed Json Data: {"rows":[{"ID":1,"Name":"watch","Description":"A piece of wearable on hands","Price":500},{"ID":2,"Name":"clothes","Description":"a peice to show colorful you","Price":1000},{"ID":3,"Name":"shoes","Description":"a wearble for your feet","Price":20000},{"ID":6,"Name":"xyz","Description":"xxgxvb","Price":0},{"ID":12,"Name":"V-Neck T-Shirt","Description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.","Price":5326},{"ID":16,"Name":"hoodie","Description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.","Price":3234},{"ID":21,"Name":"Beanie","Description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.","Price":200},{"ID":22,"Name":"Belt","Description":"A classic Wear to stay in your Limits","Price":345},{"ID":23,"Name":"Cap","Description":"Getting A HAir Loss, Save Your Dignity","Price":243},{"ID":24,"Name":"Sunglassess","Description":"Increse Your Style","Price":100},{"ID":25,"Name":"Long Sleeve tee","Description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.","Price":243},{"ID":26,"Name":"Single ","Description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.","Price":243},{"ID":27,"Name":"thongs","Description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.","Price":2342},{"ID":28,"Name":"Red Shirts","Description":" Oooo LAlala ","Price":3242},{"ID":29,"Name":"Logo Collection","Description":"best Thing to Have ","Price":325333},{"ID":30,"Name":"pushkar","Description":"worth Buying","Price":20000},{"ID":31,"Name":"yam","Description":"A piece of wearable on hands","Price":10}]} |
iOS Xcode Autolayout won't set view container to edge of superview Posted: 29 Jun 2021 08:58 AM PDT I am using autolayout in Xcode 12.4. I have 3 container views (blue, orange and brown) The third (brown) which contains a table is acting strangely on iPhone 12 and is getting cut off by the 2nd view (orange) despite setting constraints to the orange view above it to 0. It does not get cut off on the other iPhone sizes. The only work around I have been able to come up with us to add space between brown and orange and add a colored block behind to hide the fact there is space. Is there a better way to fix this problem so that it has 0 space between the containers and works well on all devices? NOTE: The scrolling text is text that is shown across the bottom and is not always used so the constraints are turned on or off at certain times.Please ignore as they are turned off for now |
How To Convert Pandas Data Frame To Dictionaries For Each Row? [closed] Posted: 29 Jun 2021 08:59 AM PDT I have this data frame with the following columns and i want to make a list and inside dictionaries. 0 DWT SIZE YOB 1 23000 supra 2010 2 25000 afra 2011 3 26000 suez 2020 I want to make a list and inside i want for each row a dictionary with key the name of the column and values the row. I want the following outpout: [{"DWT":23000, 'SIZE':'supra','YOB':2010}, {"DWT":25000 , 'SIZE':'afra','YOB':2011}, {"DWT":26000, 'SIZE':'suez','YOB':2020}] |
React-native-game-engine + matter.js dynamic scale of bodies Posted: 29 Jun 2021 08:58 AM PDT I'm trying to build a screen with circular bodies (bubbles). The bubbles should be able to change the scale with some interval, e.g. every 3 seconds and random value (from 1 to 3). The scale should change the size of a bubble and its mass. Calling Matter.Body.scale doesn't make any effect. Bubbles keep staying the same. Maybe because I'm not using sprites with textures, but the Game-Engine entities with renderer as React.PureComponent instead. Not sure Bubble node: export interface BubbleProps { body: Matter.Body; item: Item; } class BubbleNode extends React.Component<BubbleProps> { render() { const {body, item} = this.props; const x = body.position.x - body.circleRadius; const y = body.position.y - body.circleRadius; const style: ViewStyle = { position: 'absolute', left: x, top: y, width: body.circleRadius * 2, height: body.circleRadius * 2, backgroundColor: item.color, borderRadius: body.circleRadius, alignItems: 'center', justifyContent: 'center', overflow: 'hidden', padding: 3, }; return <View style={style}>{item.content}</View>; } } Bubble Entity: const body = Matter.Bodies.circle( randomX, randomY, RADIUS, //default radius 25 { mass: 30, } ); return { body, item, renderer: BubbleNode, }; Update method: // find out if the entity was already added to the world if (Object.prototype.hasOwnProperty.call(entities, id)) { //update scale const scale = bubble.item.scale Matter.Body.scale(bubble.body, scale, scale) } else { //add new entity entities[id] = bubble; Matter.World.add(physics.world, [bubble.body]); } Also, I need to make this scaling smooth Edit: Interesting thing. I was able to scale the bubbles using Matter.Body.scale but right before adding to the world. I wonder if there is a method to update the bodies after adding to the world. Final edit this is the method I'm using to set up the world and specify entities for the GameEngine framework private setupWorld = (layout: LayoutRectangle) => { const engine = Matter.Engine.create({enableSleeping: false}); const world = engine.world; world.gravity.x = 0; world.gravity.y = 0; //center gravity body Matter.use(MatterAttractors); var attractiveBody = Matter.Bodies.circle( layout.width / 2, layout.height / 2, 1, { isSensor: true, plugin: { attractors: [centerGravity], }, }, ); Matter.World.add(world, attractiveBody); //walls const wallThickness = 5; let floor = Matter.Bodies.rectangle( layout.width / 2, layout.height - wallThickness / 2, layout.width, wallThickness, {isStatic: true}, ); let ceiling = Matter.Bodies.rectangle( layout.width / 2, wallThickness / 2, layout.width, wallThickness, {isStatic: true}, ); let left = Matter.Bodies.rectangle( wallThickness / 2, layout.height / 2, wallThickness, layout.height, {isStatic: true}, ); let right = Matter.Bodies.rectangle( layout.width - wallThickness / 2, layout.height / 2, wallThickness, layout.height, {isStatic: true}, ); Matter.World.add(world, [floor, ceiling, left, right]); //basic entitites this.entities = { physics: {engine, world}, floor: {body: floor, color: 'green', renderer: Wall}, ceiling: {body: ceiling, color: 'green', renderer: Wall}, left: {body: left, color: 'green', renderer: Wall}, right: {body: right, color: 'green', renderer: Wall}, }; }; And here is the method that will be triggered by a parent Component with some interval public updateNodes = (items: Item[]) => { if (!this.state.mounted || !this.entities || !this.entities.physics || !this.layout) { console.log('Missiing required data'); return; } const layout = this.layout const entities = this.entities const bubbles: BubbleEntity[] = items.map((item) => { const randomX = randomPositionValue(layout.width); const randomY = randomPositionValue(layout.height); const body = Matter.Bodies.circle( randomX, randomY, RADIUS, { mass: 30, } ); body.label = item.id return { body, item, renderer: BubbleNode, }; }); const physics = this.entities.physics as PhysicsEntity; const allBodies = Matter.Composite.allBodies(physics.world) bubbles.forEach((bubble) => { //update existing or add new const id = `bubble#${bubble.item.id}`; if (Object.prototype.hasOwnProperty.call(entities, id)) { //do physical node update here //update scale and mass const scale = bubble.item.scale console.log('Updating item', id, scale); //right her there used to be an issue because I used **bubble.body** which was not a correct reference to the world's body. //so when I started to use allBodies array to find a proper reference of the body, everything started to work let body = allBodies.find(item => item.label === bubble.item.id) if (!!body) { const scaledRadius = RADIUS*scale const current = body.circleRadius || RADIUS const scaleValue = scaledRadius/current Matter.Body.scale(body, scaleValue, scaleValue) }else{ console.warn('Physycal body not found, while the entity does exist'); } } else { console.log('Adding entity to the world'); entities[id] = bubble; Matter.World.add(physics.world, [bubble.body]); } }); this.entities = entities }; In the future, I'm going to improve that code, I will use some variables for the body and will create a matter.js plugin that will allow me to scale the body smoothly and not instant as it works right now. Also, the method above requires some clean, short implementation instead of that garbage I made attempting to make it work |
Purpose of `n` field added to tables by `table.pack`? Heck, why does `table.pack` even exist? Posted: 29 Jun 2021 08:58 AM PDT Title says it all. I want to know why Lua adds an n field to tables when using table.pack() . Literally this is how you can implement this: function pack(...) return { n = select("#", ...), ... } end -- pretty useless I don't see a point as you can use {} to construct a table and #tbl to get how many elements there are in a table. local tbl = table.pack('a', 'b', 'c', 'd') print(tbl.n, #{ 'a', 'b', 'c', 'd' }) -- 4 4 -- Same thing If you use next to traverse a table constructed with table.pack , it really ruins iteration. Ofc you can use ipairs but for those who don't? Oh and length operator won't count that n . |
React error when using audio.play() function Posted: 29 Jun 2021 08:58 AM PDT I'm trying to play a sound by triggering the function with onClick event in React and I'm getting the following error: Uncaught Error: The error you provided does not contain a stack trace. at B (index.js:1582) at G (index.js:1899) at eval (index.js:1914) at eval (index.js:1933) at eval (index.js:1414)
import React from "react"; import firebase from "../../firebase"; import classes from "./Sidenav.module.sass"; const Sidenav = props => { const logout = () => { firebase.auth().signOut(); window.location.href = ".."; }; const playAudio = () => { let audio = new Audio("../../assets/bellNotification.mp3"); audio.play(); }; return ( <div style={props.styles.sideNavDiv} className={classes.sidenavDiv}> <i /> <div style={props.styles.iconDiv} className={classes.iconDiv}> <i className={"material-icons " + classes.navIcon}>account_box</i> <p className={classes.iconText}>Account</p> </div> <div style={props.styles.iconDiv} className={classes.iconDiv}> <i className={"material-icons " + classes.navIcon}>settings</i> <p className={classes.iconText}>Settings</p> </div> <div style={props.styles.iconDiv} className={classes.iconDiv}> <i className={"material-icons " + classes.navIcon}>trending_up</i> <p className={classes.iconText}>Check Progress</p> </div> <div style={props.styles.iconDiv} className={classes.iconDiv}> <i className={"material-icons " + classes.navIcon}>looks_one</i> <p className={classes.iconText}>1RM calculator</p> </div> <div onClick={props.toggleModal} style={props.styles.iconDiv} className={classes.iconDiv} > <i className={"material-icons " + classes.navIcon}>alarm</i> <p className={classes.iconText}>Edit timers</p> </div> <div onClick={playAudio} style={props.styles.iconDiv} className={classes.iconDiv} > <i className={"material-icons " + classes.navIcon}>help</i> <p className={classes.iconText}>Help</p> </div> <div onClick={logout} style={props.styles.iconDiv} className={classes.iconDiv} > <i className={"material-icons " + classes.navIcon}> power_settings_new </i> <p className={classes.iconText}>Logout</p> </div> </div> ); }; export default Sidenav; |
Angular 2 different components with same route Posted: 29 Jun 2021 08:58 AM PDT I have an application, which need to separate authenticated and guest users components. But I need, that both components will be loaded by '/' route. I wrote { path: 'desktop', loadChildren: 'app/member/member.module#MemberModule', canActivate: [LoggedInGuard], }, { path: '', loadChildren: 'app/guest/guest.module#GuestModule', canActivate: [GuestGuard], }, And it works. But how to make, that both component load by same url? I had tried to write path: '' for Member's module route, but the second router rule is not performed. Here are guards code: LoggedInGuard: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if(this.sessionService.isLoggedIn()) { return true; } else { return false; } } GuestGuard: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if(!this.sessionService.isLoggedIn()) { return true; } else { return false; } } Here is a plunker: http://embed.plnkr.co/VaiibEVGE79QU8toWSg6/ How should I do it properly? Thank you |
No comments:
Post a Comment