instruction
stringlengths
0
30k
I have an Enum that I already use for multiple other purposes, however in those cases I use the Enum like a public variable of the class meaning I can access it like `EntityManager.FAll`. However, in the new use case I have for it I want to use the Enum in that class as a function parameter of another class's function like `CEntityManager::EBroadcastTypes`. But no matter what I try, when I try to compile the code this always fails telling me that either when using the scope operator I need to be using a Class or Namespace even though this is a class (error code: C2653), or that `EBroadcastTypes` isnt a known identifier (error code: 2061). Just to further 'visualize' this, as an example. I want to use this Enum for 'filtering channels' when Ray Casting, so that I can either only check for specific Wanted Entities. ``` EntityManager.h class CEntityManager { public: enum EBroadcastTypes { FAll, FVehicle, FProjectile, FDynamic, // Any Entity that can movement on update (ie. Vehicle and Shells) FStatic, // Any Entity that never moves (ie. Scenery) }; struct BroadcastFilter { EBroadcastTypes type; vector<string> channels; }; vector<BroadcastFilter> m_BroadcastFilters; vector<string> GetChannelsOfFilter(EBroadcastTypes Type) { for (const auto& BroadcastFilter : m_BroadcastFilters) { if (BroadcastFilter.type == Type) { return BroadcastFilter.channels; } } } } ``` ``` Main.h // Primary Update(tick) function Update() { if()// On Some condition { TFloat32 range = 400.0f HitResult Hit = RayCast(ray, EntityManager.FAll, range); // Do something with Hit ... } } ``` RayCast file doesn't contain a class, simply functions that fall under the same category that would be used across multiple points/classes throughout the code. ``` CRayCast.h #include "EntityManager.h" struct CRay { CVector3 m_Origin; CVector3 m_Direction; }; HitResult RayCast(CRay ray, CEntityManager::EBroadcastType Type, TFloat32 Range); ``` ``` CRayCast.cpp #include "CRayCast.cpp" // Actually using EntityManager here, other than for getting the Enum. extern CEntityManager EntityManager; HitResult RayCast(CRay, CEntityManager::EBroadcastTypes Type, TFloat32 Range) { // Do the raycasting here // ... } ``` So is there any way to actually use the Enum like this? Tried including the header as well as forward declaring both the class and enum (the compiler then told me it didn't know what those forwards are).
How to omit SecurityTokenReference from KeyInfo using wss4j?
|java|wss4j|
null
I tried this script but didn't go well. ``` def generate_grid(): grid = np.zeros((10, 8), dtype=int) # Fill the first row with black and the last row with white grid[0] = 1 grid[-1] = 0 # Generate random grid until all conditions are met while True: grid[1:-1, :] = np.random.choice([0, 1], size=(8, 8), p=[0.5, 0.5]) if check_conditions(grid): break return grid def check_conditions(grid): # Condition 2: Check connectivity of black cells visited_black = np.zeros(grid.shape, dtype=bool) visited_gray = np.zeros(grid.shape, dtype=bool) # Find black and gray cells black_cells = np.argwhere(grid == 1) gray_cells = np.argwhere(grid == 0) # Check connectivity for black cells if len(black_cells) > 0: start_black_cell = black_cells[0] dfs(visited_black, grid, start_black_cell) if not np.all(visited_black[grid == 1]): return False # Check connectivity for gray cells if len(gray_cells) > 0: start_gray_cell = gray_cells[0] dfs(visited_gray, grid, start_gray_cell) if not np.all(visited_gray[grid == 0]): return False # Condition 3: Check sum of black cells total_cells = grid.size black_sum = np.sum(grid == 1) if black_sum < 0.4 * total_cells or black_sum > 0.6 * total_cells: return False return True def dfs(visited, grid, cell): i, j = cell if i < 0 or i >= grid.shape[0] or j < 0 or j >= grid.shape[1] or visited[i, j] or grid[i, j] == 0: return visited[i, j] = True dfs(visited, grid, (i+1, j)) dfs(visited, grid, (i-1, j)) dfs(visited, grid, (i, j+1)) dfs(visited, grid, (i, j-1)) def plot_grid(grid): plt.imshow(grid, cmap='binary', interpolation='nearest') plt.xticks([]) plt.yticks([]) plt.show() grid = generate_grid() plot_grid(grid) ``` ``` def check_conditions(grid): # Condition 1: Check connectivity of black cells visited = np.zeros(grid.shape, dtype=bool) black_cells = np.argwhere(grid == 1) if len(black_cells) == 0: return False start_cell = black_cells[0] dfs(visited, grid, start_cell) if not np.all(visited[grid == 1]): return False # Condition 2: Check sum of black cells total_cells = grid.size black_sum = np.sum(grid == 1) if black_sum < 0.4 * total_cells or black_sum > 0.6 * total_cells: return False return True ``` when I tried this instead of the upper part, the script worked quite well as I wanted (black blocks are all connected). [enter image description here](https://i.stack.imgur.com/4tFMP.png) However, I wanted the white part also be connected so that there is no isolated part without the connection with other clusters. So modified the script as the top, but doesn't work. Can somebody help me?
2D interlocking puzzle script not working
|grid|2d|connectivity|
null
|excel|excel-formula|
|excel|indexing|excel-formula|match|approximate|
I have created a database that has one table that keeps track of employee skills and another which displays projects that these employees can be assigned to. I need to have multiple employees asigned to the same project but i do not know how i would do this and when i try to use query to fill in this space with anything that meets these requirements, i get an error for returning multiple rows. here is the query code UPDATE projects SET POOL_ID = ( SELECT skills.POOL_ID FROM skills WHERE skills.Skill_Name = 'JavaScript' AND skills.POOL_ID IS NOT NULL ) WHERE PROJECT_ID = 1; Thanks for any help, I am new to SQL and as such dont know if this is even possible but ive googled it and cannot find any help there and ive also tried adjusting the query etc
How to assign multiple Foreign keys to one box in an sql table with PHPmyadmin
|php|sql|database|phpmyadmin|
null
|json|powerbi|powerquery|
|prometheus|grafana|offline|grafana-loki|
I recently fine-tuned a model to recognize if a sentence was inside the context i choose, and in doing so, preparing a well-structured dataset made it all. You could cross-use another model that accepts all the answers you wish after using the one you're fine tuning to get the masked word. Dataset Sample: ... 1 added to 6 is equal to 7, True 1 added to 6 gives 7, True 1 added to 6 greater than 7, False ... Hope I've at least given you a hint for a better idea!
There are two errors in your code. ## 1. Files on the web are case-sensitive You load the file `searchbar.js`, but your file is called `searchBar.js`. Small/Big letters might not be important on a Windows PC, but they are important on the web. ## 2. You are loading a named export, but you want the default When things aren't working as expected, the first thing you want to do is to check the console. You'll see this error: ``` Uncaught SyntaxError: The requested module './map.js' does not provide an export named 'addStops' (at searchBar.js:1:10) ``` This is because when you use the curly braces in `import {addStops} from "./map.js";` it expects you to export a const, or a function, but you have `export default function addStops(stops)`. This is an easy fix. Either you change that line to ```export function addStops(stops)``` ...or you change the import to ```import addStops from "./map.js";``` (without the curly braces).
Try this selector to get every div element whose id attribute contains the sub-string "tippy-" div[id*="tippy-"] {display: none !important;} **NB:** Since you’re hacking someone else’s script (video embeds) you’d better use a FLEXIBLE solution like this (use an asterisk not a carat) or you’ll be back to scratching your head again in the very near future.
I have an Azure function project within a [GitHub repository][1] (AnkiSentenceCardBuilder being the Azure function project) and I want to pull the backend code out into a new sub repository, so I can reuse it with other presentation layers, such as a WinForm. In order to keep the Git history, I planned on updating the current repository to add a Class Library project, move all the backend code into that new project, clone the repository, and delete the Azure function project. My issue with that is after creating the Class Library project, I get the error `Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]`. I'm assuming this is because the Azure function is trying to treat the Class Library as an Azure function. Since it's not suppose to be an Azure function, I can't fix this by calling `func init` on the new project. How would I go about doing this? For extra context, I'm pretty new to both Git and Azure and am working on this within VS with C#. [1]: https://github.com/TMason11095/anki-japanese-flashcard-manager
Pi4J minimal example's LED doesn't blink
|raspberry-pi|pi4j|
null
I'm trying to write a xUnit test for `HomeController`, and some important configuration information is put into `Nacos`. The problem now is that I can't get the configuration information in nacos. Here is my test class for `HomeController`: ``` using Xunit; namespace ApiTestProject public class HomeControllerTest { public HomeControllerTest() { Init(); // using DI to mock register services controller = new HomeController(); } // in this method, I can not access the nacos config strings private void Init() { var builder = WebApplication.CreateBuilder(); // add appsettings.json builder.Host.ConfigureAppConfiguration(cbuilder => { cbuilder.AddJsonFile("appsettings.Test.json", optional: false, reloadOnChange: true); }); // get nacosconfig in appsettings var nacosconfig = builder.Configuration.GetSection("NacosConfig"); builder.Host.ConfigureAppConfiguration((context, builder) => { // add nacos builder.AddNacosV2Configuration(nacosconfig); }); // try to get the "DbConn" in nacos, but connstr is null string connstr = builder.Configuration["DbConn"]; // other register logic... } } ``` And this is the `appsettings.Test.json` file: ``` { "NacosConfig": { "Listeners": [ { "Optional": false, "DataId": "global.dbconn", "Group": "DEFAULT_GROUP" }, { "Optional": false, "DataId": "global.redisconfig", "Group": "DEFAULT_GROUP" }, { "Optional": false, "DataId": "global.baseurlandkey", "Group": "DEFAULT_GROUP" } ], "Namespace": "my-dev", "ServerAddresses": [ "http://mynacos.url.address/" ], "UserName": "dotnetcore", "Password": "123456", "AccessKey": "", "SecretKey": "", "EndPoint": "", "ConfigUseRpc": false, "NamingUseRpc": false } } ``` **Update:** I've checked in detail to make sure there aren't any spelling mistakes, case sensitivity issues. And the code in `Init()` function works well in the `Program.cs` file in the tested API project, but in this xUnit project, it's not working at all.
how to configure the IDE settings to recognize.story files (or any other file extension you're using for JBehave stories) and associate them with a text editor that supports syntax highlighting. I tried running my .story files . All code is in black and cannot move to next function on click+enter .
To enable syntax highlighting with color for JBehave stories in Eclipse
|eclipse|selenium-webdriver|testing|syntax-highlighting|jbehave|
null
I want to set up a conditional reverse proxy feature with Envoyproxy, based on an OAuth access token, between my users and my application. I have already present a keycloack instance generating access tokens, and inside the generated access token there is a already a custom attribute "mygroups" with a list of business groups. I have the following constraints : - Users must get the access token from my keycloack instance; no valid access token means no access (which is pretty usual, I can do that without any problem) - Reverse proxying must be finer according to access token custom attribute list "mygroups" : - Every user must be able to access /myapp/all/* - Only users with the group "admins" present in the access token custom attribute list "mygroups" can access /myapp/admin/* - Only users with the group "sales" present in the access token custom attribut list "my groups" can access to /myapp/sales/* I am not able to find information on how to configure that more fine level "proxification". Can someone propose an efficient way to configure Envoyproxy in my use case ? Or is that a very bad idea to try to use Envoy like that, and another pattern should be considered (sadly I have very few possibility to modify the existing access token generation). Many thanks to all ! The best thing I was able to find so far is to use JWT_filter and ext_authz_filter as done by ***juanvasquezreyes*** here [JWT_filter and ext_authz_filter](https://github.com/envoyproxy/envoy/issues/14153) But it needs to be tuned to my specific access token and more important seems a little bit hacky / perhaps not very simple and fit for production.
I am trying to analyse execution time of a query. I used the following statement to check CPU and elapsed time: SET STATISTICS IO, TIME ON; For a single query, I can understand the CPU and elapsed time. But when it comes to a complex query, say as follows (Pretty big and for the time being, not sharing any sample data): DECLARE @userID BIGINT = 100, @type bit =0 DECLARE @fetchDate DATETIME; SET @fetchDate = DATEADD(yy,-2,datediff(d,0,getdate())) DECLARE @subuserId BIGINT; SELECT @subuserId = dbo.fn_getSubstituteForUser(@userID) DECLARE @userGradeLevelCode NVARCHAR(20); SELECT @userGradeLevelCode = GradeLevelCode FROM Tbl_UserPost pst LEFT JOIN Tbl_MasterGradeLevel gd ON pst.GradeLevel_ID = gd.GradeLevel_ID WHERE pst.IsActive = 1 AND pst.User_ID = @userID SELECT RANK() OVER (PARTITION BY MemoForAllID ORDER BY MemoForAllDetailID DESC) r, SenderID, MemoForAllID, ReceiverIndividualIDs, MemoForAllDetailID, Status, IsUpdated, IsTransfered, CreatedBy INTO #temp_VW_Tbl_MemoForAllDetail FROM VW_Tbl_MemoForAllDetail WHERE IsActive = 1 AND CreatedOn > @fetchDate SELECT header.MemoForAllID, detail.MemoForAllDetailID, header.Subject, header.Code, header.DocumentNumber, detail.SenderID, CASE WHEN (dd.GradeLevelCode = 'DEL') THEN dd.DepartmentName WHEN @type = 0 OR detail.Status IN ('REVIEW', 'DRAFT', 'CORRECTION') THEN dd.EmployeeName else CASE WHEN (@userID IN (SELECT dlg1.DelegateID FROM Tbl_MemoForAllDelegateDetail dlg1 WHERE dlg1.MemoForAllID = header.MemoForAllID AND dlg1.IsActive = 1 ) AND detail.Status NOT IN ('REVIEW', 'CORRECTION')) THEN (SELECT DirectorateName FROM tbl_MasterDirectorate msd inner join tbl_UserPost pst on pst.Directorate_ID = msd.Directorate_ID WHERE pst.IsActive =1 and pst.User_ID = (SELECT top 1 dlg1.SenderID FROM Tbl_MemoForAllDelegateDetail dlg1 WHERE dlg1.MemoForAllID = header.MemoForAllID and dlg1.DelegateID = @userID AND dlg1.IsActive = 1 )) ELSE (SELECT DirectorateName FROM tbl_MasterDirectorate msd inner join tbl_UserPost pst on pst.Directorate_ID = msd.Directorate_ID WHERE pst.IsActive =1 and pst.User_ID = header.SenderID) END end AS SenderName, header.MemoForAllDate, header.Priority AS PriorityName, detail.Status, CASE WHEN (@userID IN (SELECT dlg1.DelegateID FROM Tbl_MemoForAllDelegateDetail dlg1 WHERE dlg1.MemoForAllID = header.MemoForAllID AND dlg1.IsActive = 1 ) AND detail.Status NOT IN ('REVIEW', 'CORRECTION')) THEN (SELECT top 1 dlg1.CreatedOn FROM Tbl_MemoForAllDelegateDetail dlg1 WHERE dlg1.MemoForAllID = header.MemoForAllID and dlg1.DelegateID = @userID AND dlg1.IsActive = 1 ) ELSE header.MemoForAllDate END AS SentOn, CASE WHEN (@userID IN(SELECT value FROM STRING_SPLIT(header.CCIDs, ','))) THEN CAST(1 AS BIT) WHEN (@userID IN(SELECT value FROM STRING_SPLIT(header.CCSubIDs, ','))) THEN CAST(1 AS BIT) WHEN (@userID IN(SELECT value FROM STRING_SPLIT(dlgt.CCDelegateIDs, ','))) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS IsCCUser, CASE WHEN (@subuserId <> 0) THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END AS CanTakeAction, detail.IsUpdated, CASE WHEN (@userID IN (SELECT a.SenderID FROM Tbl_MemoForAllDelegateDetail a WHERE a.MemoForAllID = header.MemoForAllID AND a.IsActive = 1 )) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS HasAssignedDelegate, CASE WHEN (@userID IN (SELECT value FROM STRING_SPLIT(header.RecipientIDs, ',')) AND detail.Status NOT IN ('REVIEW', 'CORRECTION')) THEN CAST(1 AS BIT) WHEN (@userID IN (SELECT value FROM STRING_SPLIT(header.RecipientSubIDs, ',')) AND detail.Status NOT IN ('REVIEW', 'CORRECTION')) THEN CAST(1 AS BIT) WHEN (@userID IN (SELECT dlg.DelegateID FROM Tbl_MemoForAllDelegateDetail dlg WHERE dlg.MemoForAllID = header.MemoForAllID AND dlg.IsActive = 1 ) AND detail.Status NOT IN ('REVIEW', 'CORRECTION')) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS CanFreeze, CASE WHEN (@userID IN (SELECT a.User_ID FROM Tbl_MemoForAllFreezeDetail a WHERE a.MemoForAllID = header.MemoForAllID AND a.IsActive = 1 )) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS HasFreezed, CASE WHEN ( header.MemoForAllID IN (SELECT DISTINCT a.MemoForAllRefID FROM Tbl_MemoForAllHeader a WHERE a.CreatedBy = @userID and CreatedOn > @fetchDate) AND @userID IN (SELECT a.User_ID FROM Tbl_MemoForAllFreezeDetail a WHERE a.MemoForAllID = header.MemoForAllID AND a.IsActive = 1 ) ) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS IsReffered, 'MemoForAll' MemoType, CAST(0 AS BIT) IsMemoClosed, CAST(0 AS BIT) IsFinalSent, CASE WHEN (@userID IN (SELECT dlg.DelegateID FROM Tbl_MemoForAllDelegateDetail dlg WHERE dlg.MemoForAllID = header.MemoForAllID AND dlg.IsActive = 1 ) AND detail.Status NOT IN ('REVIEW', 'CORRECTION')) THEN CAST(1 AS bigint) ELSE CAST(0 AS bigint) END AS RecipientDelegate_ID, CAST(0 AS BIT) IsForwarded, CASE WHEN (header.Status NOT IN ('DRAFT','REVIEW') AND @userGradeLevelCode IN ('DIR')) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS CanTransfer, detail.IsTransfered, detail.CreatedBy FROM Tbl_MemoForAllHeader header LEFT JOIN Tbl_MemoForAllDelegateDetail dlgt ON header.MemoForAllID = dlgt.MemoForAllID AND dlgt.ID = ( SELECT TOP 1 ID FROM Tbl_MemoForAllDelegateDetail WHERE MemoForAllID = header.MemoForAllID AND IsActive = 1 ) INNER JOIN #temp_VW_Tbl_MemoForAllDetail detail ON (header.MemoForAllID = detail.MemoForAllID) inner join VW_UserInfo dd on dd.User_ID=detail.SenderID WHERE detail.r =1 and header.CreatedOn > @fetchDate and header.IsActive = 1 AND header.IsForAllDirectors = 0 AND ( (header.IsForAllDirectors = 0 AND header.Status IN ('ADD_DELEGATE') AND @userID IN(SELECT value FROM STRING_SPLIT(header.RecipientIDs,',')) ) OR @userID IN(SELECT value FROM STRING_SPLIT(header.CCSecretaryIDs,',')) OR (header.Status IN ('REVIEW') AND (header.OriginatorID = @userID OR header.OriginatorSubID = @userID)) ) AND header.Status NOT IN ('DRAFT') DROP TABLE #temp_VW_Tbl_MemoForAllDetail The performance degrades in production, in my understanding it could be due to no. of `CAST()` and subqueries (As I didn't write the actual query) with `CASE` statement. If any suggestion provided on assumption, would be glad to know more about optimizing. Now my actual query is something different that I am unable to figure out. When I run the query on production, I get the following: **Image 1**: [![Query Execution 1][1]][1] For 4970 rows, it takes around **00:01:20**. In local, it's pretty fast. When I use this statement `SET STATISTICS IO, TIME ON;`, got the below: **Image 2**: [![Query Execution 2][2]][2] My question is, the execution time I get in the first image would be the same with the second image. I am willing to know like how the calculation done in the second image for execution time of the query. I can see no. of elapsed time for each scan, to sum up and to get the actual execution time should I calculate all the elapsed time in the second image? Any brief explanation would be great. **N.B**: I am pretty novice in analysing `SQL` queries, please pardon if I missed anything or suggest anything that can improve the post. [1]: https://i.stack.imgur.com/glbhE.png [2]: https://i.stack.imgur.com/7Ih2Z.png
Found a number of issues here: First, range in line 25 is calling a sheet, not a range of cells. I have changed it to `e.range` to call on the event object. Also, I believe you have to use an installable onEdit trigger to utilize the mail service. I changed the name of your function from `onEdit` to `onMyEdit` and set up an onEdit trigger. [![Screenshot1][1]][1] [![Screenshot2][2]][2] [![Screenshot3][3]][3] Second there are some misspellings: First, `senEmail()` in line 4 and line 23. Doesn't matter if you don't call that function but you do in the last line of your code. Second, `getRagne()` in line 37 and line 38. Additionally, I got the following error after these corrections had been made: > Exception: The parameters (String,String,String,String,String) don't > match the method signature for MailApp.sendEmail. I combined messageBody, messageBody2, and respondent to bring it in line with the method signature. Lines 34 through Lines 39 need to have `getValue()` to get the cell values displayed in your HTML. Finally, you have name and email calling on the same cell. I changed the name to Column 3, but if this assumption is incorrect it can easily be modified. These changes are reflected in the code below: function onMyEdit(e) { addTimeStamp(e); sendEmail(e); } function addTimeStamp(e){ var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet5") ; var range = e.range; var row = range.getRow(); var col = range.getColumn(); var cellValue = range.getValue(); if (col == 9 && cellValue === true){ sheet.getRange(row,10).setValue(new Date()); } } function sendEmail(e){ var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet5") ; var range = e.range; var row = range.getRow(); var col = range.getColumn(); let cellValue = range.getValue(); // The value of the edited cell // Check if the edit occurred in column 5 and the value is true if (col == 9 && cellValue === true) { let email = sheet.getRange(row, 2).getValue(); let name = sheet.getRange(row, 3).getValue(); let orderID = sheet.getRange(row, 5).getValue(); let orderDate =sheet.getRange(row, 1).getValue(); let methodOfPayment = sheet.getRange(row, 4).getValue(); let numberOfTickets = sheet.getRange(row, 6).getValue(); let payableTotal = sheet.getRange(row, 7).getValue(); let html_link ="https://checkout.payableplugins.com/order/"+orderID; const subject = "PHLL Raffle Fundraiser Follow-Up on Order ID #" + orderID ; const messageBody = 'Dear ' + name + ',' + "\n\n" + 'We hope this message finds you well. We wanted to remind you that we have received your order information for the raffle ticket. According to our records, you have selected the cash method for payment, but we have not yet received the payment.' + "\n\n" + 'If you have already provided the payment to the player, please let us know as soon as possible. This will allow us to coordinate with them to ensure that your payment is collected and your raffle ticket is processed accordingly.' + "\n\n" + 'However, if you have not yet provided the payment to the player, we kindly ask you to do so at your earliest convenience. Once the payment is received, we will promptly send you your raffle ticket.' + "\n\n" + 'Please note that if payment is not received within the specified timeframe, we will have to remove your name from the drawing.' + "\n\n" + 'If you wish to change your method of payment, you may do so by following this link: ' + html_link + ' Should you have any further questions or concerns, please do not hesitate to reach out to us. We are here to assist you in any way we can.' + "\n\n" + 'Best of luck in the raffle drawing!' + "\n\n" + 'Warm regards,' + "\n\n" + 'Treasurer' + "\n\n" + 'EmailAddress' + "\n\n" + 'Paradise Hills Little League' + "\n\n" + 'ORDER DETAILS:' + "\n\n" + 'ORDER DATE:' + orderDate +"\n\n" + 'ORDER ID #' + orderID +"\n\n" + 'METHOD OF PAYMENT:' + methodOfPayment + "\n\n" + 'NUMBER OF TICKETS:' + numberOfTickets +"\n\n" +'PAYABLE TOTAL:' + payableTotal; MailApp.sendEmail(email,subject,messageBody); console.log(sendEmail) } } Note: you cannot run this code from the script editor. There needs to be an event object for the script to run. You will need to test it from the spreadsheet itself. If this is not working for you, let me know. [1]: https://i.stack.imgur.com/uv2Fy.png [2]: https://i.stack.imgur.com/F9oaO.png [3]: https://i.stack.imgur.com/eP4uh.png
From the docs > Derives a store from one or more other stores. **The callback runs initially when the first subscriber subscribes** and then whenever the store dependencies change. > ...you may need to retrieve the value of a store to which you're not subscribed. **get** allows you to do so. **This works by creating a subscription**, reading the value, then unsubscribing. In your example the derived values are nowhere used so calling `get` creates the first subscriber. When adding ``` {$derivedA} {$derivedB} ``` the logs will run on component initialization and no more when calling `get`
I have a springboot application which uses Google Cloud Storage Buckets. Now for the local development the default `gcloud auth application-default login` works fine but this app is to be deployed on a cloud. Though I have tried setting up the spring configurations to use the enviroment variable `GOOGLE_APPLICATION_CREDENTIALS` but it keeps falling back on the default ADC (Application Default Credentials) I have setup a token from a service created on gcp, and placed the token directly under the resource folder. setting : `GOOGLE_APPLICATION_CREDENTIALS = token.json` and tried giving the context root part too. I want to use Google Cloud Storage for storing frequently accessible media resources. Is there any better option? or GCS works fine? This is the Storage Bean : ```java import com.google.cloud.storage.Storage.BucketListOption; import com.google.cloud.storage.StorageOptions; import lombok.Getter; import lombok.Setter; import org.springframework.stereotype.Service; import java.util.List; @Service @Getter @Setter public class GcsService { private final Storage storage; public GcsService() { // Initialize Google Cloud Storage client this.storage = StorageOptions.getDefaultInstance().getService(); } } ``` Injecting this where the Storage instance is required. But when I try to print : ```java String googleAppCredentials = System.getenv("GOOGLE_APPLICATION_CREDENTIALS"); if (googleAppCredentials != null) { System.out.println("GOOGLE_APPLICATION_CREDENTIALS is set to: " + googleAppCredentials); } else { System.out.println("GOOGLE_APPLICATION_CREDENTIALS is not set."); } ``` it runs gives the false output.
Deploy Springboot app on heroku which is using google storage services
|spring|spring-boot|google-cloud-platform|heroku|google-cloud-storage|
null
Eventually I used the `isIgnoredFile(file: VirtualFile)` function in the `com.intellij.openapi.vcs.changes.ChangeListManager` class in combination with the [ProjectFileIndex](https://github.com/JetBrains/intellij-community/blob/master/platform/projectModel-api/src/com/intellij/openapi/roots/ProjectFileIndex.java) that I was already using. In the ContentIterator I check for every file if it is an ignored VCS file.
Got it. In Plasma 6, the presence of a shadow under the popup widget depends on the current style. For the Breeze style (which is default for Plasma 6), you need to add a dynamic property `_KDE_NET_WM_FORCE_SHADOW` and set it to `true`: ``` cpp class CustomPopup : public QWidget { Q_OBJECT public: explicit CustomPopup(QWidget *parent = nullptr) : QWidget(parent, Qt::Popup) { setProperty("_KDE_NET_WM_FORCE_SHADOW", true); } }; ``` See [here](https://invent.kde.org/plasma/breeze/-/blob/08ee525469d169eb169ecefbaab90b3564b6126f/kstyle/breezeshadowhelper.cpp#L288) for details.
I think the answer to question may lie [here](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323), but I can't understand the answer. The value of `searchedItem` remains unaltered. The following is my pseudocode. ```lang-js try { let searchedItem = 'literallyAnything' const allCollections; // get all collections from a mongoDB allCollections.foreach(childOfEachCollection => { foreach childOfEachCollection () { foreach childOfPreviousChild () { if (currentChild.id == requestedId) { searchedItem = currentChild // if I do a console.log(searchItem) here I get the desired result } } } }) // but if I do a console.log(searchItem) here I get "literallyAnything"; shouldn't I be getting my desired (and now mutated inside the for loop) result ? res.status(200).json(searchedItem) // I wish to send this to frontend } catch (error) { console.log(error) } ``` So, as mentioned above I read this [answer](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323), but I don't understand it. To tackle the above, I decided to create another method whose sole job would be to send response to the frontend. And I decided to call it from the if statement itself, where I know the value of `searchedItem` still exists, which worked upto an extent. What I mean by that is, I do get the desired output in my browser, but additionally I also get the error `Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client`, and my server crashes. I'm truncating the code for sake of brevity. ```lang-js // The new method that I created const sendResponse = (response, statusCode, data) => response.status(statusCode).json(data) ``` ```lang-js // Including only the modified if statement if (currentChild.id == requestedId) { searchedItem = currentChild sendResponse(res, 200, searchedItem) } ``` What change should I implement in my code? Thank you.
I have a common search bar to search products on every page , so how to search products on the backend using the search words. like in e-commerce sites if we search black shoes , we get all products related to black shoes even if the listed products' names do not have the terms 'black' , 'shoes'?
I have a flutter application thats generate a pdf with flutter pdf package. I want to automate the process of generating the **exact** pdfs every "month" for example. hence, thought of using the same pdf generation function I already wrote in my app in cloud function that will be called with google tasks. how can I define and run dart environment and script with firestore cloud functions
run dart script from firestore cloud functions
|flutter|dart|google-cloud-firestore|google-cloud-functions|
I am trying to crop images to detect faces using dlib but I keep getting this error,[The error](https://i.stack.imgur.com/B3ywF.png) I have downloaded the .dat file in the same directory where the .ipynb file is stored but the issue persists. I downloaded the file from dlib.net.
Unable to open shape_predictor_68_face_landmarks.dat
So i have managed to store my image on firebase storage from my node js backend and storing the link to that image in my database also but when I try to go to the URL where my image is stored I get the error in the image attached so looked it up and tried changing my rules for my storage to allow read from all but still get that error does anyone know why as I want to display this image on the client side of my app but it doesn't work right now as access isn't allowed do you need to give the token to access it or is there anyway that the rules can be modified that any user can view (so read) but only authed can write? storage rules: rules_version = '2'; // Craft rules based on data in your Firestore database // allow write: if firestore.get( // /databases/(default)/documents/users/$(request.auth.uid)).data.isAdmin; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read; } } } server side code to upload the image (this works) async function uploadProfilePicture(path) { console.log("inside profile pciture func path = ", path); const bucket = admin.storage().bucket(); const uploadedFile = await bucket.upload(path); console.log("uploaded file = ", uploadedFile); const [metadata] = await uploadedFile[0].getMetadata(); console.log("upload file metadata = ", metadata); const downloadUrl = uploadedFile[0].getSignedUrl({ action: "read", expires: "01-01-2028", }); console.log("download url = ", downloadUrl[0]); return metadata.selfLink; } client side to view the profile pic: return ( <div className="bg-gray-100 p-4"> {medallionProfile.lastName}</h2> <img style={{height: '300px', width: 'auto'}} src={medallionProfile.profilePicture}></img> </div> );
how to access image stored on firebase cloud storage
|reactjs|node.js|firebase|
Here is a slightly edited version that will work in the expected way: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> $("#selected-cases").on("input",function(){ const ids=this.value.split(",").map(v=>v.trim()); $(".form-check-input").each(function(){this.checked=ids.includes(this.value)}); }) <!-- language: lang-html --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <form> <div class="col-12"> <label for="selected-cases" class="form-label">selected cases<span class="text-muted"> *</span></label> <input type="text" id="selected-cases" name="selected-cases" class="form-control" value="3966382,4168801,4168802,4169839"> </div> <hr class="my-4"><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966382" checked>Save CaseID : 3966382</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4029501">Save CaseID : 4029501</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168818">Save CaseID : 4168818</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168801" checked>Save CaseID : 4168801</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168802" checked>Save CaseID : 4168802</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168822">Save CaseID : 4168822</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966388">Save CaseID : 3966388</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4114087">Save CaseID : 4114087</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966385">Save CaseID : 3966385</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169838">Save CaseID : 4169838</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169843">Save CaseID : 4169843</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168829">Save CaseID : 4168829</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168828">Save CaseID : 4168828</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168835">Save CaseID : 4168835</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169835">Save CaseID : 4169835</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169836">Save CaseID : 4169836</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169837">Save CaseID : 4169837</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169839" checked>Save CaseID : 4169839</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946200">Save CaseID : 3946200</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946201">Save CaseID : 3946201</label> </div> <button class="w-10 btn btn-primary btn-sm" type="submit">Save</button><div class="col-md-5"> <div id="summary"> selected-cases : <br/> </div> </div> </form> <!-- end snippet -->
There is another way to put a click application into a continuous loop. For this solution to work, `click>=3` is required. By tweaking your `main()` function a little bit to look like this: def main(): while True: try: cli.main(standalone_mode=False) except click.exceptions.Abort: break Your app will be always asking for another command when the current one has finished. `Ctrl-C` and `Ctrl-D` can break the loop. When you type the quit command, you must raise `click.exceptions.Abort`. You can read more about in Click's docs: [Exception Handling][1], [Invoking other commands][2]. A complete working code based on your example looks like this: import click @click.group(invoke_without_command=True) @click.option("--command", prompt=">") @click.pass_context def cli(ctx, command): cmd = cli.get_command(ctx, command) ctx.invoke(cmd) @cli.command(name='c') def command1(): username = click.prompt('Username', type=click.STRING) # other commands... @cli.command(name='q') def quitapp(): raise click.exceptions.Abort() def main(): while True: try: cli.main(standalone_mode=False) except click.exceptions.Abort: break if __name__ == '__main__': main() Hope it helps! [1]: https://[https://click.palletsprojects.com/en/8.1.x/exceptions/ [2]: https://click.palletsprojects.com/en/8.1.x/advanced/#invoking-other-commands
|machine-learning|image-processing|computer-vision|face-detection|
null
There is an important difference in assignment. These two assignments are not equivalent: df['j'] = df['j'].astype('uint8') df.loc[:,'j'] = df['j'].astype('uint8') - Indexing with `[...]` replaces the series. The new series comes with its own `dtype`, the existing `dtype` is discarded. - Indexing with `loc[...]` replaces values, but reuses the existing series and its `dtype`, upcasting may occur to fit new values. See how the old `int32` is ignored when using `[...]`: import pandas as pd import numpy.random as npr n = 4 # randint returns an array with dtype int32 df = pd.DataFrame({ 'j': npr.randint(1, 10, n), 'k': npr.randint(1, 10, n)}) print(df.dtypes) # Using [...]: uint8 series replaces uint32 series df2 = df.copy() df2['j'] = df2['j'].astype('uint8') print(df2.dtypes) # Using loc[...]: uint8 data upcasted to existing uint32 df3 = df.copy() df3.loc[:,'j'] = df3['j'].astype('uint8') print(df3.dtypes) ---- j int32 ⇠ original dtype k int32 dtype: object j uint8 ⇠ with [...] k int32 dtype: object j int32 ⇠ with loc[...] k int32 dtype: object
I grabbed an image and added a title (`MUPPETRY`) and description (`PUPPETRY`) in **Adobe Lightroom** using the metadata panel like this and then exported as JPEG: [![enter image description here][1]][1] In case you are wondering, I chose silly names for near certain uniqueness. --- It seems that **Lightroom** puts the title and caption in the IPTC section. You can tell that by using: exiftool -G0 20240330-export.jpg | grep UPPETRY [EXIF] Image Description : PUPPETRY [IPTC] Object Name : MUPPETRY [IPTC] Caption-Abstract : PUPPETRY [XMP] Title : MUPPETRY [XMP] Description : PUPPETRY You can extract them with `exiftool` like this: exiftool -IPTC:Caption-Abstract -IPTC:ObjectName 20240330-export.jpg Caption-Abstract : PUPPETRY Object Name : MUPPETRY Or, more succinctly: exiftool -Title -Description 20240330-export.jpg Title : MUPPETRY Description : PUPPETRY Or, if you just want the value in a `bash` variable, use the `-short` option like this: title=$(exiftool -s3 -Title 20240330-export.jpg) echo $title MUPPETRY --- If you want to see IPTC metadata with **ImageMagick**, use this to discover all the data: magick 20240330-export.jpg IPTCTEXT:- 1#90#City="&#27;%G" 2#0="&#0;&#4;" 2#5#Image Name="MUPPETRY" 2#120#Caption="PUPPETRY" You can then see the field numbers of the ones you want and extract just those: identify -format "%[IPTC:2:5]" 20240330-export.jpg MUPPETRY identify -format "%[IPTC:2:120]" 20240330-export.jpg PUPPETRY [1]: https://i.stack.imgur.com/0mHLK.jpg
I want to create a login system in the react native app using firebase auth. In there a i have used ValidateJS for the frontend validation. But i am stuck with how to implement the confirm password field. I am not able to validate that the Confirm Password field is same the the Password Field. I have pasted the codes below. **Signup.js** ```js export default function Signup({ navigation }) { const [isLoading, setIsLoading] = useState(false); const [formState, dispatchFormState] = useReducer(reducer, initialState); const inputChangedHandler = useCallback( (inputId, inputValue) => { const result = validateInput(inputId, inputValue); dispatchFormState({ inputId, validationResult: result, inputValue }); }, [dispatchFormState] ); const signupHandler = () => { /// code }; return ( <SafeAreaProvider> <View> <Image source={appIcon} /> <Text> Getting Started</Text> <Text> Create an account to continue !</Text> <View> <Inputs id="username" placeholder="Username" errorText={formState.inputValidities["username"]} onInputChanged={inputChangedHandler} /> <Inputs id="email" placeholder="Enter your email" errorText={formState.inputValidities["email"]} onInputChanged={inputChangedHandler} /> <InputsPassword id="password" placeholder="Password" errorText={formState.inputValidities["password"]} onInputChanged={inputChangedHandler} /> </View> <Buttons title="SIGN UP" onPress={signupHandler} isLoading={isLoading} /> <View> <Text>Already have an account?</Text> <TouchableOpacity onPress={() => { navigation.push("Login"); }}> <Text>Log In</Text> </TouchableOpacity> </View> <StatusBar style="auto" /> </View> </SafeAreaProvider> ); } ``` **Validate.js** ```js import { validate } from "validate.js"; export const validateString = (id, value) => { const constraints = { presence: { allowEmpty: false, }, }; if (value !== "") { constraints.format = { pattern: ".+", flags: "i", msg: "Value can't be blank.", }; } const validationResult = validate({ [id]: value }, { [id]: constraints }); return validationResult && validationResult[id]; }; export const validateEmail = (id, value) => { const constraints = { presence: { allowEmpty: false, }, }; if (value !== "") { constraints.email = true; } const validationResult = validate({ [id]: value }, { [id]: constraints }); return validationResult && validationResult[id]; }; export const validatePassword = (id, value) => { const constraints = { presence: { allowEmpty: false, }, }; if (value !== "") { constraints.length = { minimum: 6, msg: "must be atleast 6 characters", }; } const validationResult = validate({ [id]: value }, { [id]: constraints }); return validationResult && validationResult[id]; }; ``` **formActions.js** ```js import { validateConfirmPassword, validateEmail, validatePassword, validateString, } from "../validation.js"; export const validateInput = (inputId, inputValue) => { if (inputId === "username") { return validateString(inputId, inputValue); } if (inputId === "email") { return validateEmail(inputId, inputValue); } if (inputId === "password" || inputId === "confirmPassword") { return validatePassword(inputId, inputValue); } }; ``` **formReducer.js** ```js export const reducer = (state, action) => { const { validationResult, inputId, inputValue } = action; const updatedValues = { ...state.inputValues, [inputId]: inputValue, }; const updatedValidities = { ...state.inputValidities, [inputId]: validationResult, }; let updatedFormIsValid = true; for (const key in updatedValidities) { if (updatedValidities[key] !== undefined) { updatedFormIsValid = false; break; } } return { inputValues: updatedValues, inputValidities: updatedValidities, formIsValid: updatedFormIsValid, }; }; ```
How to validate if Confirm Password is same or not with the Password in React Native using ValidateJS?
How to pull out backend code from an Azure function into a sub repository while keeping git history?
|c#|git|visual-studio|github|azure-functions|
I am trying to perform a brute force attack using Burp Suite on a login page on my localhost and it is giving me a status code 200 for each value it is checking or sometimes it is giving me a status code 411 for each value. This includes the correct value for the username and password as well what do I do? how do I get status code 200 for the correct username and password only? [This is a screenshot of what I'm getting](https://i.stack.imgur.com/kdkio.jpg) I have tried every possible different attack type from sniper to cluster bomb but it is still showing the same thing. I am trying to find a solution to my problem
Brute force attack using burp suite
|security|brute-force|burp|
null
There's no penalty for using two header tags, but make sure it makes sense.
With Rest Assured i'm parcing rest-response and comparing arrays. Response body: { "error": { "errorObjects": [ { "risks": [ { "description": "Risk1", "riskId": 6654152 }, { "description": "Risk2", "riskId": 6654155 } ] } ] } } Arrays with expected data: int[] riskId = {6654152, 6654155} String[] description = {"Risk1", "Risk2"} Rest Assured and Hamcrest Matchers asserts: .body("error.errorObjects[0].risks.description", containsInRelativeOrder(description), "error.errorObjects[0].risks.riskId",containsInRelativeOrder(riskId)); I'm getting an error: java.lang.AssertionError: 1 expectation failed. JSON path error.errorObjects[0].risks.riskId doesn't match. Expected: ((a collection containing [<6654152>, <6654155>])) Actual: <[6654152, 6654155]> So it seems that it's ok with comparing array of strings but with ints it goes mad. Help me out, maybe i need to use there another matcher, not containsInRelativeOrder? I've tried many of them but anyway getting this error
Rest-Assured and Hamcrest matchers not working with comparing arrays of ints
|java|arrays|assert|rest-assured|hamcrest|
Try this selector to get every div element whose id attribute contains the sub-string "tippy-" div[id*="tippy-"] {display: none !important;} **NB:** Since you’re hacking someone else’s script (video embeds) you’d better use a FLEXIBLE solution like this (**use an asterisk not a carat**) or you’ll be back to scratching your head again in the very near future.
|javascript|syntax|comments|
|json|supabase|supabase-database|
I think you should create [ingress Class Trafeik](https://docs.k3s.io/networking#traefik-ingress-controller) based on the documentation. Probably it work easily on AWS or GCP since ingress classes are auto propagated on platform managed clusters. Consider also using [pathType: Prefix](https://kubernetes.io/docs/concepts/services-networking/ingress/#path-types) on your deployment.
I am building a dynamic animation based on user input, I read the input and create corresponding `Animated.timing()` objects that I then pass into `Animated.sequence`, which I set to loop. Simplified code would look like this: ```js let animations = []; for ( /* read user input, use it to define params of the animation parts */ ) { let inhaleAnim = Animated.timing(scaleValue, {/*params*/}); let hold1Anim = Animated.timing(scaleValue, {/*params*/}); let exhaleAnim = Animated.timing(scaleValue, {/*params*/}); let hold2Anim = Animated.timing(scaleValue, {/*params*/}); animations.push(inhaleAnim, hold1Anim, exhaleAnim, hold2Anim); } const animate = (sequence) => { // Starts the sequence and ensures it will be looping. Animated.sequence(sequence).start( () => { animate(sequence); } ); } animate(animations); ``` I need to be able to run code after each "finish" of the `Animated.timing()` that work together to comprise the animation sequence. In more human words, everytime animation of inhaling completes, a sound is player. Everytime animation for holding breath completes, a sound is played and so on. I read through the documentation and initially thought I might be able to simply define callback for completion for each of the timings, but when I tested this, I realized that when I call `.start()` on a timing to be able to provide callback, I end up inadvertly starting the timing animation immediatelly, doesn't do what I want. How?
Run code when `Animated.timing()` in `Animated.sequence()` completes
|javascript|reactjs|react-native|animation|
A=np.arange(4*5).reshape(4,5) T=np.array([1, 1]) R=np.einsum('i,jk->ijk',T,A) B=np.array([1,100]) C=R-np.reshape(B,(2,1,1)) Your answer are C[0],C[1]
You return values from your functions but you don't assign these values to any variables. Here is the corrected code: ```py import numpy as np import pandas as pd def user_input(): while True: weather_type = input( "Which weather type (temperature, humidity, pressure, or rainfall)? " ) if weather_type in ["temperature", "humidity", "pressure", "rainfall"]: break else: print( "Error: Please enter 'temperature', 'humidity', 'pressure', or 'rainfall'." ) while True: try: num_data_points = int(input("Number of data points (maximum of 8000): ")) if num_data_points < 1 or num_data_points > 8000: print("Error: Number of data points must be between 1 and 8000.") else: break except ValueError: print("Error: Please enter an integer value for number of data points.") return weather_type, num_data_points def call_API(weather_type, num_data_points): api_url = f"https://api.thingspeak.com/channels/12397/fields/{4 if weather_type == 'temperature' else 3 if weather_type == 'humidity' else 5 if weather_type == 'rainfall' else 6}.csv?results={num_data_points}" df = pd.read_csv(api_url) return df def clean_data(df): data_array = df.iloc[ :, 1 ].to_numpy() # Extracting the data column and converting to numpy array return data_array def plot_data(data_array, weather_type, num_data_points): import matplotlib.pyplot as plt plt.plot(np.arange(num_data_points), data_array) plt.xlabel("Data Points") plt.ylabel(f"{weather_type.capitalize()}") plt.title(f"Plot of {weather_type.capitalize()}") plt.show() weather_type, num_data_points = user_input() # <-- note the weather_type, num_data_points df = call_API(weather_type, num_data_points) # <-- df = data_array = clean_data(df) # <-- data_array = plot_data(data_array, weather_type, num_data_points) ```
|react-native|validation|react-native-firebase|
<%= link_to "Invite Admin", new_admin_invitation_path, method: :get, class: 'btn btn-primary btn-sm me-2' %> when i click on this button i am redirecting to the sign in page and getting 401 Unauthorized error in logs. i want to redirect to the new page not on sign in page
Devise:Invitable redirecting me to sign_in
|devise|devise-invitable|
null
Lets init a state, giving object as initial state. To update any property of the object, we usually clone state and re-set using setter. But in following example, without any setter, I can update properties of that object and they are reflected on the dom without any complain. ```typescript import React, {useState, useEffect} from 'react'; export function App(props) { const [x, setX] = useState({test: 0}) // setter is never used const [y, setY] = useState(0) useEffect(()=>{ // This may not be suitable for production code x.test = x.test + 1 }, [y]) return ( <div className='App'> <h1>x = {x.test}</h1> <button onClick={() => setY(y+1)}>Increase</button> </div> ); } ``` I assume this behavior is related to the mutable nature of objects in JavaScript. Question is, can this code lead to any adverse effects? Also, this can be produced only inside a `useEffect` hook. if I changed my code as ```Typescript <button onClick={() => x.test = x.test + 1}>Increase</button> ``` this will no longer works. Why there is a difference, if we mutate the same object?
We have have a Windows Task Scheduler job that runs an Excel xlsm file with some command line arguments as below: Program/script: "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE" Add arguments (optional): "C:\File\Path\MyMacroEnabledFile.xlsm" /e/Arg1,Arg2 We would like to add a third argument with today's date, which would display in Task Manager something like the following: "C:\File\Path\MyMacroEnabledFile.xlsm" /e/Arg1,Arg2,03-30-2024 The reason for that requirement is that the job sometimes hiccups and we have a demand job that spins through WMI processes and terminates running Excel instances based on checking the command line. It would be really helpful to see the date in the Task Manager Command Line column. When you google Excel Command Line Arguments there are lots of examples for all kinds of things, but I can't find one that speaks to a Date command line argument. I have tried: "C:\File\Path\MyMacroEnabledFile.xlsm" /e/Arg1,Arg2,%date "C:\File\Path\MyMacroEnabledFile.xlsm" /e/Arg1,Arg2,%date% "C:\File\Path\MyMacroEnabledFile.xlsm" /e/Arg1,Arg2,%Now "C:\File\Path\MyMacroEnabledFile.xlsm" /e/Arg1,Arg2,%Now%
Is there a way to pass Today's date as a command line argument to Excel from a Windows Task Scheduler Job
|excel|vba|scheduled-tasks|command-line-arguments|
To future Django coders. If you get this message in your Django Channels Consumer subclass, make sure the correct methods are marked as async: ``` async def disconnect(self, close_code): pass ``` is the correct way. Without the prefix async, I get the same above error, whenever my client calls closes() the WS conn.
OAuth access token attribute based reverse proxying of http ressources
|oauth-2.0|keycloak|envoyproxy|role-based-access-control|
null
### Description Hello, I'm working with CakePHP 4 and facing an issue with Paginator links not respecting my custom route definitions. To give you a context, I've set up a custom route like so: ```php $builder->connect( "/categories/{category}", ['controller' => 'Items', 'action' => 'category', 'items'], ['routeClass' => DashedRoute::class, 'pass' => ['items'],] ); ``` In the controller ItemsController, I have the category action defined as follows: ```php public function category($item_type_slug) { $category_slug = $this->getRequest()->getParam('category'); $this->loadComponent('Paginator'); $items = $this->getItemsCatalog($item_type_slug, $category_slug); $this->set('items', $items['items'] ? $this->paginate($items['items']) : []); } ``` I am using CakePHP's built-in pagination for displaying items. The issue arises when accessing the second page of the items list. The Paginator generates a link that follows CakePHP's default routing pattern ("/controller/action/param") instead of using my custom route. Consequently, the link to the second page appears as "/items/category/items?page=2" rather than following the custom route pattern "/categories/{category}?page=2". I've searched through the documentation and forums but haven't found a clear solution to make Paginator respect my custom route in generating links. How can I adjust the Paginator or the routing setup so that the pagination links follow the custom route I've defined? Any advice or pointers in the right direction would be greatly appreciated. Thank you in advance for your help! ### CakePHP Version 4 ### PHP Version 8
CakePHP 4 Custom Routing Issue with Paginator Links
|php|cakephp|pagination|cakephp-4.x|
So apparently dotnet core has a [```System.Net.IPNetwork```][1] struct that makes this a lot easier than having to twiddle bits inside a Uint32. We can set up your sample data like this: ``` $sites = @" sub1;10.41.92.0/29 sub2;10.41.92.40/29 sub3;10.188.2.0/24 sub4;10.248.232.0/21 sub5;151.156.179.0/24 "@ | convertfrom-csv -header @( "Name", "CIDR" ) -delimiter ";"; $hosts = @" bc;10.41.92.45 xyz;10.188.2.48 abc1;10.248.232.5 aabb;151.156.179.145 "@ | convertfrom-csv -header @("Hostname", "IPAddress") -delimiter ";"; ``` Then parse the CIDR ranges into ```IPNetwork``` structs: ``` # parse the cidr range text string for each site $networks = $sites | foreach-object { $parts = $_.CIDR.Split("/"); $network = new-object System.Net.IPNetwork( [System.Net.IPAddress]::Parse($parts[0]), [int]::Parse($parts[1]) ); [pscustomobject] @{ "Site" = $_ "Network" = $network } } ``` And finally check each host for membership of networks: ``` $membership = foreach( $hostinfo in $hosts ) { $hostIpAddress = [System.Net.IPAddress]::Parse($hostinfo.IPAddress); $hostNetworks = $networks | where-object { $_.Network.Contains($hostIpAddress) }; [pscustomobject]@{ "Hostname" = $hostinfo.Hostname "IPAddress" = $hostinfo.IPAddress "Site" = $hostNetworks.Site "Subnet" = $hostNetworks.Site.CIDR } } $membership ``` which outputs: ``` Hostname IPAddress Site Subnet -------- --------- ---- ------ bc 10.41.92.45 @{Name=sub2; CIDR=10.41.92.40/29} 10.41.92.40/29 xyz 10.188.2.48 @{Name=sub3; CIDR=10.188.2.0/24} 10.188.2.0/24 abc1 10.248.232.5 @{Name=sub4; CIDR=10.248.232.0/21 } 10.248.232.0/21 aabb 151.156.179.145 @{Name=sub5; CIDR=151.156.179.0/24} 151.156.179.0/24 ``` Credit to this answer for pointing the way... https://stackoverflow.com/a/63161497/3156906 [1]: https://learn.microsoft.com/en-us/dotnet/api/system.net.ipnetwork?view=net-8.0
|node.js|google-cloud-firestore|google-cloud-functions|
null
SOLVED. The problem was in the Security Atributes on the Source for Role or Group Schemes. It was the wrong selection. The right selection is Access Control User Roles Asssignments.
|html|list|button|blazor|
I have two plots, and I would like to put them in an html file, with an option to alternate between them by selecting different titles. Is this possible in plotly ?
how to add multiple plot in alternating plotly html file in python
|html|plot|plotly|
I have a simple ui, which should print every key that I've pressed. I need to generate signal **once** per real key-press. How can I achieve that? In default, tkinter generates signal once, than waits about 0.5 sec and starts generate signal in loop, until *KeyRelease* event happens. ``` if __name__ == '__main__': from tkinter import Tk, Frame root = Tk() frame = Frame(root, width=200, height=200, bg="white") frame.pack() def key_handler(event): print(event.char, event.keysym, event.keycode) return 'break' root.bind('<Key>', key_handler) root.mainloop() ``` Using 'break' at the end of the bond function doesn't stop the next event-call. In addition (bc this is a minor question, which is too small for separate post), how can I create these key sequences?: - "Shift" and some digit - some digit and '+' or '-' symbol **UPD**: I don't really want to do this: ``` def key_handler(event): global eve if eve != event.keysym: eve = event.keysym print(event.char, event.keysym, event.keycode) ``` because signal still process when I want to remove it at all. But, I don't really know how much affect does Dummy signal on the program in total, so may be this solution makes sense?