satoshi-2000/llms-suitable huggingface dataset:
Question: React Ts trying to create guarded routed but getting an error

Hi I tried creating guards for my routes but I am getting this error:
[Error] Error: [GuardedRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

This is my code:
GuardedRoute.tsx-
import { Route, Navigate } from 'react-router-dom';
import { useUserInfo } from '../context/UserContext';

export const GuardedRoute = ({ path, element: Element, ...rest }: any) => {
  const { userInfo } = useUserInfo();

  if (userInfo.id !== '') {
    return <Route path={path} element={Element} {...rest} />;
  } else {
    return <Navigate to="/" replace />;
  }
};


App.tsx
 <BrowserRouter>
                <Nav></Nav>
                <div className="w-[100vw] fixed top-[50px] z-[100] flex flex-col">
                {
                  ErrorMessages.map((message,index)=>(
                      <div className="w-[300px] h-[50px] mt-[10px] mx-auto bg-red-600/90 rounded-md grid place-content-center" key={index}>
                        <p className="font-bold text-gray-200 text-center">{message}</p>
                      </div>
                  ))
                }
                </div>
                  <Routes>
                    <Route path="/" element={<Home />} />
                    <GuardedRoute path="/profile/:select?" element={<Profile />} />
                    <GuardedRoute path="/checkout" element={<CheckOut />}/>
                    <Route path="/register" element={<Register />} />
                    <Route path="/login" element={<Login />} />
                    <Route path="/browse" element={<Browse />} />
                    <Route path="/product/:id" element={<Product />} />
                    <Route path="/404"  element={<PageNotFound />}/>
                    <Route path="*"  element={<Navigate to="/404" />}/>
                  </Routes>
                </BrowserRouter>

Does anyone have a solution for this error? thanks.


Answer:
It is better to put all the private routes inside Authguard instead of providing Authguard to each component. you can customize the auth, like if there is cookie exists of particular user, then auth is true, otherwise false.
import { Outlet, Navigate } from 'react-router-dom';

const Authguard = () => {

    let auth = false;
    return(
        auth ? <Outlet/> : <Navigate to="/"/>
    )
}

export default Authguard

Now you Routes will be like, e.g in App.tsx
  function App(){
    return(
     <Routes>
          <Route path="/" element={<Login />} />
    
           <Route element={<Authguard />}> 
               <Route path="/register" element={<Register />} />
               <Route path="/home" element={<Home />} />
          </Route>
     </Routes>)
    }

This shows your Register and Home components are private, and Login component is public.
Question: Kotlin Error 'unresolved reference' appears when trying to run Java Code from a Kotlin file

Referencing Problem when Java Class is used in Kotlin. There is the Java class Base32Decoder.java and code from this class is used in the Kotlin file hello.kt.
When I try to run Java code through a Kotlin file, an error occurs because of no reference could be established to the Java class Base32Decoder.
Error message:

hello.kt:4:25: error: unresolved reference: Base32Decoder

Base32Decoder Java class can't resolve the reference to it. Since this class is used inside the Kotlin file, the reference needs to work.
Code
fun main(args: Array<String>){
    val Base32Decoder = Base32Decoder()
   val rectangleArea: String = Base32Decoder.base32Decode("JBSWY3DPFQQFO33SNRSCC===")
   println("inside the Kotlin codes:" + rectangleArea)
}

How can I reference Java classes when I want to use Java code in Kotlin files?


Answer:
The code must be accessible for Kotlin. This means you have to compile (If you compile code in terminal: javac SampleFile.java The Base32Decoder.java file to generate the Base32Decoder.class.
Now generate the JAR-file with a link to the Kotlin file in command line:
jar cf app.jar Base32Decoder.class hello.kt

Now since you use kotlinc you can execute the code in command line like this:
kotlinc -classpath app.jar -script hello.kt

Now your code should run fine. The problem is that Kotlin didn't have access to the Base32Decoder.java class.
Question: Azure blob storage returns Unauthorized with SAS generated URL

I am trying to generate a URL where users can access a file that is in a blob storage container on Azure. The blob storage container is heavily restricted by IP address, and then the service I'm building will manage requests and generate a URL where users can access the file directly. Here is the code used to generate the URL (I think the code itself is probably fine).
CloudBlobContainer container = BlobStorage.GetContainer(_accountStatementEmailConfig.BlobStorageContainerName);
CloudBlockBlob blob = container.GetBlockBlobReference(document.StoragePath);

if (!blob.Exists())
{
    return NotFound();
}

TimeSpan sasExpiryTime = TimeSpan.FromMinutes(_apiConfig.PresignedURLExpiryInMinutes);

SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read;

string sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
{
    Permissions = permissions,
    SharedAccessExpiryTime = DateTime.UtcNow.Add(sasExpiryTime)
}, new SharedAccessBlobHeaders(), _apiConfig.SharedAccessSignaturePermissionsPolicyName);

string documentUrl = $"{blob.Uri.AbsoluteUri}{sasToken}";

The code generates the URL fine, but when a user goes to the URL they receive the following error:
<Error>
    <Code>AuthorizationFailure</Code>
    <Message>
        This request is not authorized to perform this operation. RequestId:92d7ca35-501e-0016-2a65-973659000000 Time:2023-06-01T08:43:35.2439678Z
    </Message>
</Error>

It was perhaps my incorrect assumption about SAS that the token would allow me to bypass the IP restrictions since I am generating the URL from a whitelisted IP. Am I taking the incorrect approach, or is there something minor I am overlooking?


Answer:
As Gaurav Mantri pointed out in comments, the issue is my understanding of how Azure handles permissions since all of my previous experience is from AWS.
In Azure the storage account and the containers have separate access levels. Can achieve similar functionality to AWS's private + presignedURL option by setting the Storage Account to public, and each of the individual containers to private. Then using the generated SAS URL to access the file.
Question: How to do integer arithmetic in Makefile prerequisites?

I have a file <n>.x and <n-1>.y and I want to create a dependency in my Makefile.
Manually I can write each case as follows:
2.x : 1.y
3.x : 2.y
4.x : 3.y
...

Now I would like to be able to write this more generically:
%.x : <???>.y

Gnu Make doesn't seem to have integer arithmetic on its own and shell expansions ($$(( )), $(shell ) don't seem to work for prerequisites.
Is there a way do this in the Makefile itself or should I use an external script that can generate these dependencies and let the Makefile include them?
Edit: My specific case is dealing with files containing financial transactions. Each file (e.g. 2023.journal) represents transactions for a specific year and includes an opening statement (e.g. 2023_opening.journal), which is based on the closing statement of the year before that. This create a dependency between 2023_opening.journal and 2022.journal.


Answer:
With GNU make:
.SECONDEXPANSION:
%.x: $$(shell expr $$* + 1).y

All rules after the .SECONDEXPANSION special target have their list of prerequisites (and only that) processed twice by make: a first time, as everything else, when make parses the Makefile, plus a second time when make needs to check the prerequisites of a target. Contrary to the first phase, during the second phase the automatic variables are defined.
So, after the first phase the rule becomes:
%.x: $(shell expr $* + 1).y

$* is the make automatic variable that expands as the stem in pattern rules. In your case it is the part that matches the %.
And then, when make needs the list of prerequisites for 1.x, the rule is processed again, $(shell expr $* + 1).y is expanded, and becomes (step by step):

1.x: $(shell expr 1 + 1).y # $* --> 1
1.x: 2.y                   # $(shell expr 1 + 1) --> 2
Question: How can I add multiple non-consecutive cells to Name Manager in Excel using Python?

I am trying to add multiple cells, which are not always consecutive, in only one Name in Excel Name Manager using Python. You can see an example of what I want to do in the attached screenshot.

I have tried the Python libraries openpyxl and XlsxWriter, but both libraries can only define a specific cell or a specific range.
Examples

openpyxl

specific_cell = DefinedName('specific_cell', attr_text='Sheet1!$C$8')
specific_range = DefinedName('specific_range', attr_text='Sheet1!$C$8:$J$13')


XlsxWriter

workbook.define_name('specific_cell', '=Sheet1!$G$1')
workbook.define_name('specific_range', '=Sheet1!$G$1:$H$10')

Is there any way to add to Name Manager something more complicated than the above?
Based on the attached screenshot something like
workbook.define_name('complex_range','=Sheet1!$B$3:$E$8;Sheet1!$B$12:$C$16;Sheet1!$B$19;Sheet1!$H$12:$I$16')



Answer:
These will work for each module, the common factor being comma rather than semi-colon?

Xlsxwriter:
workbook.define_name("test", "=Sheet1!$B$3:$E$8,Sheet1!$B$12:$C$16,Sheet1!$H$12:$I$16,Sheet1!$B$19") 

Xlwings:
workbook.names.add(name="test", refers_to="=Sheet1!$B$3:$E$8,Sheet1!$B$12:$C$16,Sheet1!$H$12:$I$16,Sheet1!$B$19") 

Openpyxl:
workbook.defined_names.add(DefinedName("test", attr_text="Sheet1!$B$3:$E$8,Sheet1!$B$12:$C$16,Sheet1!$H$12:$I$16,Sheet1!$B$19"))
Question: How to fix Multer middleware when it fails to create upload folder and change filename?

i am trying to upload pdf to server using nodejs and multer but there is a problem.
a send a file from ejs templet and it must be saved at disk on folder named upload and file name changed to specific name .
but what happen that Multer middleware does not work no folder created no filename changed
There are parts of code .
ejs file
 <form enctype="multipart/form-data">
        <input type="text" placeholder="Book Name" id="name" />
        <input type="text" placeholder="Author " id="author" />
        <input type="text" placeholder="Buy link" id="link" />
        <input type="text" placeholder="Book description" id="desc" />
        <input type="file" name="pdf" id="pdf" placeholder="upload file" />
        <button type="submit">Add</button>
      </form>
<script>
      // const multer = import("multer");
      // const upload = multer({ dest: "./public/data/uploads/" });
      let form = document.querySelector("form");
      form.addEventListener("submit", async (e) => {
        let bookName = document.getElementById("name").value;
        let bookAuthor = document.getElementById("author").value;
        let bookLink = document.getElementById("link").value;
        let bookDesc = document.getElementById("desc").value;
        let pdf = document.getElementById("myfile").files[0].name;
        e.preventDefault();
        try {
          const res = await fetch("/addBooks", {
            method: "POST",
            body: JSON.stringify({
              bookName,
              bookAuthor,
              bookDesc,
              bookLink,
              pdf,
            }),
            headers: { "Content-Type": "application/json" },
          });
</script>


middleware:
onst storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "upload");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
    console.log(destination, filename);
  },
});
const upload = multer({ storage });

route.post("/addBooks", upload.single("pdf"), addBook);


post func
let addBook = async (req, res) => {
  console.log("reqbody >> ", req.body);
  let { bookName, bookAuthor, bookDesc, bookLink, pdf } = req.body;
  try {
    let _book = await books.create({
      name: bookName,
      author: bookAuthor,
      description: bookDesc,
      buyLink: bookLink,
      pdf:pdf,
    });
    if (_book) {
      res.status(200).send({ msg: "success" });
    }
  } catch (error) {
    logger.error("system crashed try again ");
    res.status(400).send({ msg: "Wrong" });
  }
};



Answer:
When sending a file, you must send it in the form, and the information comes in req.file, not in req.body
Question: How do I make the label text of an element bold in javascript?

My HTML :
<div id="PDF">
    <input type="checkbox" id="pdf" name="pdf" value="pdf">
    <label for="pdf">PDF</label>
</div>

My JS :
document.addEventListener('change',function(event){
    if(event.target.id == "pdf"){
        if(event.target.checked == true){
            event.target.label.style.fontWeight = "bold";
        }
        else{
            event.target.label.style.fontWeight = "normal";
        }
    }
});

To my utter dismay, when I execute the code, I am greeted with this error:

Uncaught TypeError: Cannot read properties of undefined (reading
'style')

How do I fix this issue?


Answer:
There are two main issues here. Firstly, the event target has no attribute of label. You should just select the label explicitly and change the styles. Secondly, I would recommend adding the event listener to only the #pdf div rather than the whole document. This way, you won't need to check for the ID and the event listener won't be fired on every change. For example:
document.getElementById("pdf").addEventListener("click", event => {
  const label = document.querySelector("label[for=pdf]");
  if(event.target.checked == true){
    label.style.fontWeight = "bold";
  }
  else{
    label.style.fontWeight = "normal";
  }
})
Question: Oracle SQL Case with Null

I have a simple query that is taking an input from a bind variable.
CREATE TABLE "FRUITS" 
(   "FRUIT_NAME" VARCHAR2(100), 
"COLOR" VARCHAR2(100)
) ;

insert into fruits (fruit_name, color)
values ('Banana', 'Yellow')
insert into fruits (fruit_name, color)
values ('Lemon', '')
insert into fruits (fruit_name, color)
values ('Apple', 'Red')

SELECT * FROM FRUITS
WHERE
COLOR =     case
            when :P1_ITEM is null then null
            else :P1_ITEM
            end

If the input is 'Yellow' the result would be 'Banana' (when 'Red' then 'Apple'). However, if the input happens to be null the result is 'no data found'.
How can this be avoided knowing that null is not a null value?
If the input is null on color then how can I return the null color row? meaning 'Lemon' + null
Thanks


Answer:
Something like this might be one option:
SELECT * FROM FRUITS
WHERE
nvl(COLOR, 'x') = case
                    when :P1_ITEM is null then 'x'
                    else :P1_ITEM
                  end;
Question: A local object disappeared in ABAP from $TMP package

There was a local report in the $TMP that is "disappeared" somehow. I did not delete it, but can't see it in SE80 anymore.
What could be the reason?
Somebody else has deleted it. The system has been resetted somehow to an older backup state. Are any other reasons possible?
Is there a possibility to see in the traces what has happened or are there any other (better) tracking possibilities?
Unfortunately I don't know what was the exact name of the disappeared report, but I know the beginning of its name (like Z_ABCD_...)


Answer:
You cannot restore or track local objects if they were deleted. There could  be any reason from that you have mentioned. Better ask collegues / basic team if they made some changes.
Try to look up the table TADIR (Directory of Repository Objects) to check which local development objects exist. Use SE16 / SE16N transaction with condition DEVCLASS = $TMP, additionally AUTHOR to include only objects from specific user, OBJ_NAME = Z_ABCD* to restrict the program name.
You can also check the table REPOSRC (Report Source Code), where reports source code in RAWSTRING (DATA field) is stored. Filter on PROGNAME, CNAM (username) to check if the source sode is available on the system (there are also several views avaiable for this table, TRDIR, D010SINF).
If the program were assigned to a package / transport and deleted, than you could find it in TADIR with a deletion flag DELFLAG = X, and also in the table E071 with OBJFUNC = D in case of a transport assignment. Local objects just get deleted from the repository tables.
Question: Cannot convert value of type 'Image' to expected argument type 'String'

I make a category included image scroll butI can't put my variable named tabBarItemName name into image, it keeps giving error like this : Cannot convert value of type 'Image' to expected argument type 'String'
struct ContentView: View {
        @State var currentTab: Int = 0
        var body: some View {
            ZStack(alignment:.top) {
                        TabView(selection:self.$currentTab){
                            Image1View().tag(0)
                            Image2View().tag(1)
                            Image3View().tag(2)
                        }
                        .tabViewStyle(.page(indexDisplayMode: .never))
                        .edgesIgnoringSafeArea(.all)
                        .padding(.top,76)
                        CategoryScroll(currentTab: self.$currentTab)
                    }   
       }
    }

    struct CategoryScroll:  View {
        var tabBarOptions: [Image] = [Image("bim")]
        @Binding var currentTab : Int
        var body: some View {
              ScrollView(.horizontal){
                  HStack(spacing:20){
                      ForEach(Array(zip(self.tabBarOptions.indices, self.tabBarOptions)),
                              id:\.0,
                              content: {
                          index, name in
                          CategoryView(currentTab: self.$currentTab, tab: index, tabBarItemName: name)
              })
            }
        }.padding(7)
        .background(Color.white)
    }

    struct CategoryView: View {
        @Binding var currentTab: Int
        var tab : Int
        var tabBarItemName: Image
        var body: some View{
            Button{
                self.currentTab = tab
            } label: {
                VStack{
                    Image(tabBarItemName) // I'm trying to make changes right here
                        .frame(width: 12, height: 12)
                        .padding(.leading, 65)
    
                    if currentTab == tab {
                        Color.init( red: 0.965, green: 0.224, blue: 0.49)
                            .frame(height: 2)
                            .padding(.leading,65)
                    } else {
                        Color.clear.frame(height: 6)
                    }
                }
                .animation(.spring(), value: self.currentTab)
                
            }
           .buttonStyle(.plain)
        }
      }
    }

I would be very happy if you could help me with this.


Answer:
Change
var tabBarOptions: [Image] = [Image("bim")]

to
var tabBarOptions: [String] = ["bim"]

And change
var tabBarItemName: Image

to
var tabBarItemName: String

The issue:
Image(tabBarItemName) is expecting a String, not an Image
Question: express js error handler(s) get ignored after first one

I have an express js app with some routes and a protected route that matches all the calls to an endpoint that starts with /app. after that i add generic error handler to the app like so:

app.use("/app", authenticate);

// app.post("/new_user", validate({body: schema}), route_handler);
// more routes etc. 

app.use((error: TypeError | ValidationError, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK FOR VALIDATION ERROR");
        if(error instanceof ValidationError) {
            console.log("VALIDATION ERROR FOUND")
            res.status(403).send(error);
        } else {
            console.log("NO VALIDATION ERROR")
            next();
        }
    });

    app.use((error: TypeError | AuthError, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK FOR AUTH ERROR");
        if(error instanceof AuthError) {
            console.log("AUTH ERROR FOUND");
            res.status(403).send({msg: "Authentication failed"});
        } else {
            console.log("NO AUTH ERROR")
            next();
        }
    });

    app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK GENERIC ERROR");
        if(error) {
            res.status(500).send({msg: "Some generic error happend"});
        } else {
            next();
        }
    });

    app.use((req: Request, res: Response, next: NextFunction) => {
        console.log("ROUTE NOT FOUND");
        res.status(404).send({
            msg: "this endpoint was not found",
        });

        next();
    });

When i do a request to for example the following endpoint: https://localhost/app/ and throw a AuthError on purpose in this endpoint the only console.log()'s i ever see are:
CHECK FOR VALIDATION ERROR
NO VALIDATION ERROR
ROUTE NOT FOUND
But i think i should see the following:
CHECK FOR VALIDATION ERROR
NO VALIDATION ERROR
CHECK FOR AUTH ERROR
AUTH ERROR FOUND
Why is my Auth error middleware never called??


Answer:
You need to pass error to the other error middleware when you call next like this:
app.use((error: TypeError | AuthError, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK FOR AUTH ERROR");
        if(error instanceof AuthError) {
            console.log("AUTH ERROR FOUND");
            res.status(403).send({msg: "Authentication failed"});
        } else {
            console.log("NO AUTH ERROR")
            next(error);
        }
    });

Without it, the normal middleware will get called.
Question: Notification Manager getSystemService() call not working

I am following this tutorial on creating notifications
However, I cannot seem to do the following:
NotificationManager notificationManager = getSystemService(NotificationManager.class);

Because my Android studio reports the error:
Required Type: Context
Provided: Class <android.app.NotificationManager>
reason: Class<NotificationManager> is not compatible with Context

Please let me know how to resolve this issue.


Answer:
I found this was my solution:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Question: Can an f77 subroutine be called from C?

In modern Fortran, we can call a subroutine from C by using C binding. E.g. The Fortran subroutine will look like this
subroutine my_routine(...) bind (C, name="my_routine")

However, if the fortran subroutine is an old f77 subroutine, this binding is presumably not an available solution. What would be the best alternative?


Answer:

However, if the fortran subroutine is an old f77 subroutine, this binding is presumably not an available solution.

It depends.  Modern Fortran is largely backwards compatible with Fortran 77.  Your F77 subroutine will not come with a bind attribute, but if you're willing to add one and compile it with a modern Fortran compiler then chances are pretty good that it will work just as you expect of code originally written for a newer Fortran version.
On the other hand, what C interop brings to Fortran is standardization, not a new capability.  People have been calling Fortran routines from C almost as long as people have been using C.
The issue here is that the specifics are system and compiler dependent.  If you don't rely on C interop, then you will need to accommodate your Fortran compiler's name-mangling and argument-passing conventions to successfully call Fortran-compiled functions from C code.  These vary.  There used to be a fair amount of tools and documentation for such activity.  I imagine it's harder to find these days, but much of it should still work.

What would be the best alternative?

That depends on your specific constraints.  If you're up for modifying the Fortran source and compiling with a modern compiler then I'd at least start with adding a bind attribute to the function, and see how that plays out.