satoshi-2000/llms-suitable huggingface dataset:
Question: How to do a lookup for the four primary keys columns yet output 6 columns to OLE DB Command

I'm moving from a SQL Server database to a DB2 database. I'm trying to compare the primary key of the SQL Server database with the DB2 database and if its the same primary key values then do an update if they are not the same do an insert.
My problem is when I use a lookup for the primary key (first four columns) it only returns the first four columns, I need someway of getting the other two columns so I can run a OLE DB command and do the update.
I want to compare the four primary keys columns (FISCAL_YR, LOC_CODE, SYSTEM_ID, SYSTEM_CODE) and see if they exist in the destination table if they do I want to update two other columns (LOC_NAME, ALIAS_NAME) and if they don't match I want to do an insert.
This is what I have for the lookup currently but it matches all the columns I just want to do the first four (FISCAL_YR, LOC_CODE, SYSTEM_ID, SYSTEM_CODE) but output 6 columns (FISCAL_YR, LOC_CODE, SYSTEM_ID, SYSTEM_CODE, LOC_NAME, ALIAS_NAME) to OLE DB Command so I can do an update:
SELECT 
    FISCAL_YR, LOC_CODE, SYSTEM_ID,  
    SYSTEM_CODE, LOC_NAME, ALIAS_NAME 
FROM 
    LC1U1.Location_Supertbl1;

This is the update command I want to execute:
UPDATE LC1U1.Location_Supertbl1 
SET ALIAS_NAME = UPPER('test') 
WHERE FISCAL_YR = ? 
  AND LOC_CODE = ? 
  AND SYSTEM_ID = ? 
  AND SYSTEM_CODE = ?

How do I do this with a Lookup transformation in SSIS?
Thank you.


Answer:
I think the issue you're not asking for the columns from the lookup component.
In the UI, you drag lines between the left (Source) and right (Lookup) side. This defines the equality match for the lookup.
What you want to do is check the 2 additional columns in that menu, something like the following image. This will add LOC_NAME and ALIAS_NAME as new columns, after the Lookup Component, into my data flow
Question: How can I validate a MongoDB document using a validation schema from a file?

I want to validate document before it is inserted into the database. I know that I can set static validator, but I would prefer to have a file with the validation schemas that I could modify at any time.
//example schema
const userCreateValidationSchema = {
        bsonType: 'object',
        required: ['username', 'password'],
        properties: {
            username: {
                bsonType: 'string',
                maxLength: 16,
            },
            password: {
                bsonType: 'string',
                maxLength: 64,
            },
        },
        additionalProperties: false,
};

//example document
const document = {
        username: "user",
        password: "passwd",
};

Then I would do something like validate(document, userCreateValidationSchema).
Thanks for any thoughts.
I have tried looking for the answer in the documentation but unfortunatelly didn't find the solution.


Answer:
To perform login validation using the npm package Joi :-
npm install joi

Import Joi and Define Validation Schema :-
const Joi = require('joi');

const loginSchema = Joi.object({
  email: Joi.string().email().required(),
  password: Joi.string().min(6).required(),
});

In the above example, the validation schema requires the email field to be a valid email address and the password field to have a minimum length of 6 characters.
Perform Validation:
Now you can use the validate() method provided by Joi for the validation.
function validateLogin(loginData) {
  const { error, value } = loginSchema.validate(loginData);
  return error ? error.details[0].message : null;
}

Usage Example:
Here's an example of how you can use the validateLogin() function to validate the login data:
const loginData = {
  email: 'test@example.com',
  password: 'password123',
};

const validationError = validateLogin(loginData);

if (validationError) {
  console.log('Login validation failed:', validationError);
} else {
  console.log('Login data is valid.');
}
Question: R-Shiny, Use action button into a leaflet popup inside a Shiny module

I am trying to use an actionbutton in a leaflet popup into a shiny module
When trying to use an action button into a leaflet popup in a Shiny module, button do not work.
See the exemple below :
library(shiny)
library(leaflet)
library(DT)

map_ui <- function(id) {
  ns <- NS(id)
  tagList(
    
    leafletOutput(ns("mymap"))
    
  )
}

map_Server <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {
      
      mapdata <- datasets::quakes
      mapdata$latitude <- as.numeric(mapdata$lat)
      mapdata$longitude <- as.numeric(mapdata$long)
      mapdata$id <- 1:nrow(mapdata)
      
      output$mymap <- renderLeaflet({
        leaflet(options = leafletOptions(maxZoom = 18)) %>% addTiles() %>%
          addMarkers(lat = ~ latitude, lng = ~ longitude,
                     data = mapdata,
                     layerId = mapdata$id,
                     popup= ~paste("<b>", mag, "</b></br>", actionLink(inputId = "modal", label = "Modal", onclick = 'Shiny.setInputValue(\"button_click\", this.id, {priority: \"event\"})')))
      })

      observeEvent(input$button_click, {
        showModal(modalDialog(
          title = "TEST MODAL"
        ))      })
      

      
    }
  )
}

ui <- fluidPage(
  
  map_ui('ex1')
  
)

server <- function(input, output){
  map_Server('ex1')
  
}

shinyApp(ui, server)

Is there any way to make work that button into the module ? I think that it comes that the button is not ns() but i don't find a way to make it works.
Thanks


Answer:
Yes, you have to add the ns:
function(input, output, session) {
  
  ns <- session$ns  
  
  ...... 
  
  output$mymap <- renderLeaflet({
    leaflet(options = leafletOptions(maxZoom = 18)) %>% addTiles() %>%
      addMarkers(
        lat = ~ latitude, lng = ~ longitude,
        data = mapdata,
        layerId = mapdata$id,
        popup = 
          ~paste(
            "<b>", mag, "</b></br>", 
            actionLink(
              inputId = "modal", label = "Modal", 
              onclick = sprintf(
                'Shiny.setInputValue(\"%s\", this.id, {priority: \"event\"})',
                ns("button_click")
              )
            )
          )
      )
  })
  
  ......
  
}
Question: Adding a legend to a ggplot map

I am using ggplot2 to visualise map-related data. I have coloured regions according to a continuous value, and I would like to add a legend with colors and region names. My own data is a bit cumbersome to share, but I have recreated the scenario with public data (Mapping in ggplot2). The following code creates the included map:
library(ggplot2)
library(sf)

# Import a geojson or shapefile
map <- read_sf("https://raw.githubusercontent.com/R-CoderDotCom/data/main/shapefile_spain/spain.geojson")

ggplot(map) +
  geom_sf(color = "white", aes(fill = unemp_rate)) +
  geom_sf_text(aes(label = name), size = 2)


Instead of the continuous default legend, I would like to have a legend with names, numbers and colors. Basically, a legend that shows the name and unemp_rate columns of the data with colors matching the map (eg. unemp_rate). Somewhat like the legend of the second included picture (but the colors are not right).




name
unemp_rate




"Andalucía"
18.68


"Aragón"
8.96


"Principado de Asturias"
11.36


"Islas Baleares"
9.29


"Islas Canarias"
17.76


"Cantabria"
8.17


"Castilla y León"
10.19


"Castilla-La Mancha"
14.11


"Cataluña"
9.29


"Comunidad Valenciana"
12.81


"Extremadura"
16.73


"Galicia"
11.20


"Comunidad de Madrid"
10.18


"Región de Murcia"
12.18


"Comunidad Foral de Navarra"
8.76


"País Vasco"
8.75


"La Rioja"
10.19


"Ceuta y Melilla"
23.71





My actual code looks like so:
ggplot(map, aes(geometry = geometry, fill = Y1)) +
  theme_bw() + geom_sf(show.legend = FALSE) +
  scale_fill_gradient2(low = "brown", high = "green") +
  theme(
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank())



Answer:
Perhaps an inset bar chart instead:
library(ggplot2)
library(sf)
library(dplyr)
library(patchwork)
# Import a geojson or shapefile
map_ <- read_sf("https://raw.githubusercontent.com/R-CoderDotCom/data/main/shapefile_spain/spain.geojson") %>% 
  mutate(name = forcats::fct_reorder(name, desc(unemp_rate)))

g1 <- map_ %>% 
  ggplot() +
  geom_sf(color = "white", aes(fill = unemp_rate)) +
  geom_sf_text(aes(label = name), size = 2) +
  scale_fill_gradient2(low = "brown", high = "green", midpoint = 16) +
  theme_minimal() +
  theme(legend.position = "none", axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank())

g2 <- map_ %>% 
  ggplot(aes(x = unemp_rate, y = name, fill = unemp_rate)) +
  geom_col() + 
  scale_fill_gradient2(low = "brown", high = "green", midpoint = 16) +
  geom_text(aes(label = name, x = .5, hjust = 0)) +
  geom_text(aes(label = unemp_rate), nudge_x = - .5, hjust = 1) +
  theme_void() +
  theme(legend.position = "none")

g1 + inset_element(g2, 0, .2, .9, 1)
Question: android app LocalDate alternative for older API level

I am building a calendar app and mostly in my code I use LocalDate to set my RecyclerView and some more functions.
I have a tablet that it's android version is 7.1.1, so it cant run anything in my code related to LocalDate.
I want to contest my self and make my app run to min SDK 16. Are there any alternatives for LocalDate for my code? I also use Calendar in my code but for my RecyclerView is almost the triple code to do same task. Any other suggestion would be apreciated.


Answer:
If you want to have Java 8+ features available in lower Android version, you can use one of the following options:

import the ThreeTen Android Backport (ABP)
make use of Android API Desugaring

With (one of) these two, you can use nearly all of the classes and functions of java.time in Android API Levels < 26, including LocalDate.
Question: Variable not updated in compose

I have a class in Kotlin (Jetpack compose) with a variable title and an exoplayer that updates the title.
class Player{
var title by mutableStatOf("value")
....

title= "new value"
...
}

@Composable
fun Display(){
val player = Player()

player.title?.let{
Text(it)
} 
}

In the user interface an instance of the class is created and the title displayed but it remains unchanged after being updated in the class. Can someone help?


Answer:
You forgot to remember the player instance. Here, when you change title, your composable is recomposed because it reads the title. But when it is recomposed, you create new instance of Player with the default title.
val player = remember { Player() }
Question: No loader is configured for ".html" files: index.html Vitejs

Greetings I have problem. I am using Visual studio 2022 and created two projects there for one solution. One for back-end (ASP.NET) and the second one for fron-end (vuejs and vite). So here starts the problem. I used npm create vue@3 command to create vue project. And  its launched fine , but when I did same thing in folder of front-end in my sln project vite throws error what it can not find index.html file
Error:   Failed to scan for dependencies from entries:
  D:/Projects/C#/DAINIS/vueapp/index.html

  X [ERROR] No loader is configured for ".html" files: index.html

    <stdin>:1:7:
      1 │ import "D:/Projects/C#/DAINIS/vueapp/index.html"
        ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


    at failureErrorWithLog (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:1638:15)
    at D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:1050:25
    at runOnEndCallbacks (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:1473:45)
    at buildResponseToResult (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:1048:7)
    at D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:1060:9
    at new Promise (<anonymous>)
    at requestCallbacks.on-end (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:1059:54)
    at handleRequest (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:725:19)
    at handleIncomingPacket (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:747:7)
    at Socket.readFromStdout (D:\Projects\C#\DAINIS\vueapp\node_modules\esbuild\lib\main.js:675:7)

Just in case I did not changed project it is as is.
Project structure
Error dump example
I tried solutions found here and here in stack overflow but still no luck


Answer:
The issue is the # symbol in your file path
D:/Projects/C#/DAINIS/vueapp/

I don't know the technical reason why this causes it to fail, but if you remove it, the project should run.
Question: Saving an extremely long figure as pdf in R will cause all text invisible

R 4.2.1
package usage: netmeta 2.8-1
Issue:
In netmeta package, the function forest() will create a forest plot. One need to know that forest() can generate a forest plot presenting the network inconsistency between direct and indirect comparisons.
In my case, I have an extremely large network, which will lead to more than 2000 comparisons. The forest plot describing network inconsistency will be VERY long in height.
The following script can only create "part" of the forest because the forest is too long.
pdf("filename.pdf",width = 12, height = 200)
forest(out, show = "all")
dev.off()

I tried to increase the height to make all the content in this document. But any value above 200 in height will generate a "blank" pdf (but I think the text should be there because the file size is 240KB rather than a NULL file which only takes 4KB in my disk).
I have no idea how to make the text visible in pdf and keep all content in this file at the same time. Any suggestion will be appreciated. Thank you.


Answer:
PDF 1.x has an implementation limit for the page size:

The minimum page size should be 3 by 3 units in default user space; the maximum should be 14,400 by 14,400 units. In versions of PDF earlier than 1.6, the size of the default user space unit was fixed at 1⁄72 inch, yielding a minimum of approximately 0.04 by 0.04 inch and a maximum of 200 by 200 inches. Beginning with PDF 1.6, the size of the unit may be set on a page-by-page basis; the default remains at 1/72 inch.

(ISO 32000-1, Annex C.2 Architectural limits)
If R doesn't adjust the default user space unit size in case of large width or height arguments, it generates PDFs that go beyond these limits whenever you set either argument to a value greater than 200.
As those limits originate from the Adobe implementation of the PDF spec, i.e. Adobe Acrobat, tests with Adobe software may indeed show issues...
Question: Complex Cocatenation in gsheets

I have a table to entries where I am trying to concatenate few columns and the concatenation should not happen when any one of the required values are empty
Here is the spreadsheet. https://docs.google.com/spreadsheets/d/1lQUG4TmFTKghV8r6Gg3EilLx6zyuTkrNfnCatRVWp_U/edit#gid=189998773
I did try to use the formula =MAP(scan(,D5:D,I5:I,lambda(a,b,d,if(or(a="",b="",d="",and(e="",f="")),,if(f<>"",f,e)&" "&a&" "&b&" "&c))),D5:D,H5:H,I5:I,J5:J,K5:K,lambda(a,b,c,e,f,if(or(a="",b="",c="",and(e="",f="")),,if(f<>"",f,e)&" "&a&" "&b&" "&c)))
But not able to get the the desired output.
Please help!


Answer:
You can simplify your formula by omitting SCAN
=MAP(D5:D,H5:H,I5:I,J5:J,K5:K,
      LAMBDA(dd,hh,ii,jj,kk,
       IF(OR(dd="",hh="",ii="",AND(jj="",kk="")),,dd&"-"&hh&"-"&ii&"-"&if(kk<>"",kk,jj))))

(for future reference: try naming your LAMBDAs accordingly)
Question: Using glm in R for linear regression on a large dataframe - issues with column subsetting

I am trying to use glm in R using a dataframe containing ~ 1000 columns, where I want to select a specific independent variable and run as a loop for each of the 1000 columns representing the dependent variables.
As a test, the glm equation works perfectly fine when I specify a single column using df$col1 for both my dependent and independent variables.
I can't seem to correctly subset a range of columns (below) and I keep getting this error, no matter how many ways I try to format the df:
'data' must be a data.frame, environment, or list

What I tried:
df = my df
cols <- df[, 20:1112]

for (i in cols{
    glm <- glm(df$col1 ~ ., data=df, family=gaussian)
}



Answer:
It would be more idiomatic to do:
predvars <- names(df)[20:1112]
glm_list <- list()  ## presumably you want to save the results??
for (pv in predvars) {
    glm_list[[pv]] <- glm(reformulate(pv, response = "col1"), 
       data=df, family=gaussian)
}

In fact, if you really just want to do a Gaussian GLM then it will be slightly faster to use
lm(reformulate(pv, response = "col1"), data = df)

in the loop instead.
If you want to get fancy:
formlist <- lapply(predvars, reformulate, response = "col1")
lm_list <- lapply(formlist, lm, data = df)
names(lm_list) <- predvars
Question: Firebase Hosting Can't Add Domain

When I try to add a custom domain to Firebase Hosting, I encounter this error. Nothing happens when I click Continue.
Upon clicking continue, it loads for a few seconds, and then the same screen persists.

When I checked the console, HTTP requests are responded with 503 Service Unable.



Answer:
firebaser here
While we did make some changes to our custom domain provisioning this week, it seems that you're hitting another problem.
Is any part of this on a Google Workspace account by any chance? If that is the case, your domain may not allow the search console. You'll want to reach out to their GSuite organization admin/owner to enable the Search Console. See Turn Google Search Console on or off for users for complete instructions.
Question: Google Sheets vlookup to prioritize a column

Wonder if anyone can help.
On the attached on tab 2 I'm trying to do a vlookup to tab 1 to use column 1 'code' to bring back column 3 'email'. But if there is more than 1 match in column 1 for 'code', prioritize the row that has Level 1 in column 2 in tab 1. For example, there are two code 20, on tab 1 but the formula should bring back row 5 - test4@live.co.uk rather than row 2 - test1@live.co.uk as row 5 has Level 1 in column 2. If there is no duplicate code in column 1 just bring back the first result in column 1.
I've got a formula already in column 3 in tab 2 but it isn't working as it doesn't bring back anything if there isn't level 1 in column 2, see column 4. On tab 3, I've got an example of what the right result should be. This can be either a vlookup, a match & index or what ever works as long as its in google sheets.
Addition to the above, it needs to be an array based on something being in column 1 and have an iferror, just in case. Thanks.
Link to sheet


Answer:
You may try:
=index(ifna(vlookup(A2:A,sort(LookTable!A:C,2,),3,)))


the above code prioritizes Level 1 over blank level. Not sure if there's goin' to be 10s of levels and I have to choose say level 15 over level 8 or so; then use this alternate variant
=index(ifna(vlookup(A2:A,sort(LookTable!A2:C,--ifna(regexextract(LookTable!B2:B,"\d+")),),3,)))
Question: Sort Rows Based on Tuple Index

Overview:
Pandas dataframe with a tuple index and corresponding 'Num' column:
Index                               Num

('Total', 'A')                      23

('Total', 'A', 'Pandas')            3

('Total', 'A', 'Row')               7

('Total', 'A', 'Tuple')             13

('Total', 'B')                      35

('Total', 'B', 'Rows')              12

('Total', 'B', 'Two')               23

('Total', 'C')                      54

('Total', 'C', 'Row')               54

Total                               112

The index and 'Num' column are already sorted with a lambda function by Alphabetical Order and based on the length of tuple elements:
dataTable = dataTable.reindex(sorted(dataTable.index, key=lambda x: (not isinstance(x, tuple), x)))

Problem:
Now, I want to sort only the 3rd tuple index element based on it's corresponding 'Num' value. Here would be an updated example of the dataframe:
Index                               Num

('Total', 'A')                      23

('Total', 'A', 'Tuple')             13

('Total', 'A', 'Row')               7

('Total', 'A', 'Pandas')            3

('Total', 'B')                      35

('Total', 'B', 'Two')               23

('Total', 'B', 'Rows')              12

('Total', 'C')                      54

('Total', 'C', 'Row')               54

Total                               112

Question:
What Lambda function can achieve this?


Answer:
You can try:
def fn(x):
    vals = x.sort_values(by='Num', ascending=False)
    df.loc[x.index] = vals.values

m = df['Index'].apply(len).eq(3)
df[m].groupby(df.loc[m, 'Index'].str[1], group_keys=False).apply(fn)

print(df)

Prints:
                Index  Num
0          (Total, A)   23
1   (Total, A, Tuple)   13
2     (Total, A, Row)    7
3  (Total, A, Pandas)    3
4          (Total, B)   35
5     (Total, B, Two)   23
6    (Total, B, Rows)   12
7          (Total, C)   54
8     (Total, C, Row)   54
9               Total  112


Initial df:
                Index  Num
0          (Total, A)   23
1  (Total, A, Pandas)    3
2     (Total, A, Row)    7
3   (Total, A, Tuple)   13
4          (Total, B)   35
5    (Total, B, Rows)   12
6     (Total, B, Two)   23
7          (Total, C)   54
8     (Total, C, Row)   54
9               Total  112
Question: RouteChildrenProps is not an exported member

I am getting the below error pointing to 'RouteChildrenProps':

I am just trying to get through a tutorial but I got stuck here.  Here is the full code:
import React from 'react';
import { Route, RouteChildrenProps, Routes } from 'react-router';
import routes from './config/routes';

export interface IApplicationProps {}

const Application: React.FunctionComponent<IApplicationProps> = (props) => {
  return (
    <Routes>
      {routes.map((route, index) => {
        return <Route 
          key={index} 
          exact={route.exact} 
          path={route.path} 
          render={(routeProps: RouteChildrenProps<any>) =>
            <route.component {...routeProps} />} />;
          }
      )}
    </Routes>
  );
};

export default Application;

The tutorial itself did not encounter this issue, so I'm hoping someone here can me solve this.


Answer:
React-Router v6 removed route props, these are a v4/5 export. The Route component API changed significantly from v4/5 to v6. There are no route props, no exact prop since routes are now always exactly matched, and all routed content is rendered on a single element prop taking a React.ReactNode, e.g. JSX, value.
import React from 'react';
import { Route, Routes } from 'react-router';
import routes from './config/routes';

export interface IApplicationProps {}

const Application: React.FunctionComponent<IApplicationProps> = (props) => {
  return (
    <Routes>
      {routes.map((route) => {
        const Component = route.component;
        return (
          <Route 
            key={route.path} 
            path={route.path} 
            element={<Component />}
          />
        );
      })}
    </Routes>
  );
};

If any of the routed component need to access what was previously passed via props, they should use the provided React hooks: useNavigate for navigate function that replaced useHistory, useParams for route path parameters, useLocation for the location object, etc.