jquery drag and drop calculate distance

I’m using jquery ui sortable feature, I want to do 2 things when I drag an element:

  • If the element is close to the edges of another element (about 10-15px) then sort elements normally
  • But if the distance is larger than 10-15px and close to the center of the other object then append it as a child to that object when dropped

A simple for… loop with closure in javascript and golang bug me for a few years [duplicate]

below it is a loop with closure, i use “let” it will return 0,1,2,3,4 when i call the array function

function createFunctions() {
    var functions = [];
    for (let i = 0; i < 5; i++) { // * let scope will not be excuted first 
        functions.push(function () {
            console.log(i);
        });
    }
    return functions;
}
var funcs = createFunctions();
funcs[0](); // Outputs: 0
funcs[1](); // Outputs: 1
funcs[2](); // Outputs: 2

below it is almost same as above, i use “var” and it will return 5,5,5,5,5 when i call the array function

  function createFunctions() {
    var functions = [];
    for (var i = 0; i < 5; i++) { // * var scope will be excuted first , call hoisting in javascript
        functions.push(function () {
            console.log(i);
        });
    }
    return functions;
}
var funcs = createFunctions();
funcs[0](); // Outputs: 5
funcs[0](); // Output:  5
funcs[1](); // Outputs: 5

When I first time met it , I didn’t dive into deep to ask why, i just know it is hoist feature in Javascript ; but recently when i dealing with golang, i met this kind of closure too ;

func createFunctions() []func() {
    var functions []func()
    for i := 0; i < 5; i++ {
      functions = append(functions, func() {
        fmt.Println(i)
      })
    }
    return functions
  }
func main() {
    funcs := createFunctions()
    funcs[0]() // Outputs: 5
    funcs[1]() // Outputs: 5
}

I met it again , it makes me feel vary uncomfortable ; above if you don’t copy the value , I will output 5,5,5,5,5

func block() []func() {
    var functions []func()
    for i := 0; i < 5; i++ {
      value := i
      functions = append(functions, func() {
        fmt.Println(value)
      })
    }
    return functions
}
func main() {
    block := block() 
    block[0]() // Outputs: 0
    block[1]() // Outputs: 1   
}

Guess what , it will out put 1,2,3,4,5 …. ; I almost ask everyone I can ask , but they still can’t tell why , Can anyone help me ???

Block scope: Go also recognizes block scope. A block is any section of code surrounded by {}. If you declare a variable inside a block (like an if statement, for loop, or switch case), it’s only visible within that block.

In Go, there’s also another type of scope related to if, for, and switch constructs. For example, a variable declared in the initialization statement of an if or for clause is only visible until the end of the if or for clause.

Above it is I read from blog , but it does not make any sense ???

Is there a way to show popovers only on click of Slider dots in react-slick?

I am using Slider component from “react-slick”, and wanted to show popovers only when users click on Slider dots, tried afterChange, beforeChange setting props, but that does not worked, it is like popovers should only appears when user click on any of the slider dots.
[enter image description here](https://i.stack.imgur.com/eY97S.png)

I tried For all available methods but that did not worked for me,

How can I correctly import a list of images defined in markdown frontmatter into an astro layout?

I am building a portfolio website with Astro, where each project has an object with media defined in its markdown frontmatter, like so:

media:
  - text: "descriptive text about first cluster of images"
    paths: ["../images/projects/project_1/img_0.png","../images/projects/project_1/img_1.png","../images/projects/project_1/img_2.png"]
  - text: "descriptive text about second cluster of images"
    paths: ["../images/projects/project_1/img_3.png","../images/projects/project_1/img_4.png","../images/projects/project_1/img_5.png"]
  - text: "descriptive text about third cluster of images"
    paths: ["../images/projects/project_1/img_8.png"]

There is a
All images are stored in src/images/projects/project_x/y.png

The imageContainer.astro looks like this:

...
    <div class={image-section}>
        {mediaItem.paths.map((path: string) => 
            <div class="image-container">
                <img src={path} alt="cool images about stuff"/>
            </div>
        )}
    </div>
...

I get the following error when building (I have renamed the paths in the code above and below for readability, so the paths here are not one-to-one the same):

 generating static routes

▶ src/pages/index.astro
 error   Cannot find module 'C:UsersNikoCreativeProgrammingwebastroportfolio_v1distchunksimagesprojectsproject_1img_1.png' imported from C:UsersNikoCreativeProgrammingwebastroportfolio_v1distchunkspagesall.87c76733.mjs
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:UsersNikoCreativeProgrammingwebastroportfolio_v1distchunksimagesprojectsproject_1img_1.png' imported from C:UsersNikoCreativeProgrammingwebastroportfolio_v1distchunkspagesall.87c76733.mjs

When i run npm run dev, everything works, but when i build, only the alt-text shows up. So how do I get the layout to import the listed images correctly from the object defined in the markdown frontmatter, when building?

I have already tried to make a workaround import statement in the JavaScript / TypeScript section of the layout, where i map out the source to an imported path, like so:

let sources : Record<string, string> = {};

for (let index = 0; index < mediaItem.paths.length; index++) {
    const element : any = mediaItem.paths[index];
    let source = ((await import(element)).default);
    sources[element] = source;
}

And then using the object as a dictionary like this:

...
    <div class={image-section}>
        {mediaItem.paths.map((path: string) => 
            <div class="image-container">
                <img src={sources[path]} alt="cool images about stuff"/>
            </div>
        )}
    </div>
...

This worked with npm run dev but did not build. And gave the same error as above.

Issue in the Date which accessing from different Region Framework used is FluentUI with React.js Typescript

I have been trying to implement the code to precent date issue the code is given below. I need a solution for this. This Date Picker is is fluent UI framework which i have been using to select the date in ui.


<DatePicker
  placeholder="Enter Date"
  allowTextInput={false}
  id="d"
  label="Start"
  isRequired={true}
  value={condition ? new Date(2023-05-23T00:00:00Z) : null}
  onSelectDate={(value) => this._handleDatePickerRangeInput("d", value, s, "s")}
  formatDate={(date: Date): string => {
    return this.getDateFormat(date.toString());
  }}
/>
I/P = new Date(2023-05-23T00:00:00Z)
O/P = 22/05/2023

Here I am using fluent UI Date picker and where i am facing an issue when i am trying to access the from Different Region Like Mountain Timezone then the date which is appearing is (22/05/2023) it's going 1 day back to the actual date Is there any other solution in which we can prevent the conversion of the date.

I there any other solution in the same fluent ui framework in which we can prevent the conversion.

Preventing Immediate Execution of Functions Pushed to an Array in JavaScript

I am trying to push functions into an array in JavaScript and then execute them using Promise.all(). However, I noticed that the functions are being immediately called when I push them into the array. How can I prevent the immediate execution of functions and ensure they are executed only when using Promise.all()?

Here’s a simplified example of my code:

export async function changePrices(id, prices, checkVariables) {
  let tasks = []

  tasks.push(changePrice(1, 1, 1, 1))
  tasks.push(changePrice(2, 2, 2, 2))
  tasks.push(changePrice(3, 3, 3, 3))
  tasks.push(changePrice(4, 4, 4, 4))

  console.log('tasks:', tasks);
  await Promise.all(tasks)
}

export async function changePrice(id, price, type, test) {
  console.log('start:', test);
  // Some asynchronous operations here
  console.log('end:', test);
  return 'helloooo'
}

A Download Button with Download Limits Using Html , Css and Javascript

A Download Button with Download Limits
Downloading files from websites is a frequent feature in the digital age. To manage access to certain material or cap the amount of downloads for a given file, you might occasionally wish to implement download limitations. In this lesson, we’ll look at how to use HTML, CSS, and JavaScript to make a download button with download restrictions.

By implementing download limits, you can ensure that your website’s resources are used responsibly and prevent abuse or unauthorized distribution of files. This feature can be particularly useful when providing access to premium content or offering limited-time downloads.

To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript.

get code on https://www.postforest.in/2023/05/a-download-button-with-download-limits.html

Can’t get csrftoken in Django for ajax recently

I referenced the code provided in the official doc here

https://docs.djangoproject.com/en/4.2/howto/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false

It worked well until recent. I didn’t make any modification to the getCookie
method. But it suddenly can’t work on both Chrome and Firefox.

The document.cookie always return “”. And CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False.
How sould I debug? I need the csrftoken to be passed to the ajax request.

Thanks.

Referenced src is here

function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;}

const csrftoken = getCookie('csrftoken');

Sharepoint List Validation (Only alphabets allowed)

#Only Alphabets validation in text column of sharepoint online

I am trying to set validation to allow only alphabets in Column name ” Visitor Full Name”.
I need a formula which should be lengthy because list validation have a limit of 1024 char and i have to include other formulas as well.
I have tried below formulas but no result:

=IF(ISERROR(FIND(LOWER([Visitor Full Name]), “abcdefghijklmnopqrstuvwxyz”)), TRUE, FALSE)
=IF(ISERROR(FIND(“^([a-zA-Z0-9]+)$”, [Visitor Full Name])), FALSE, TRUE)
=IF(REGEX([Visitor Full Name], “^[a-zA-Z0-9]+$”), TRUE, “Special characters are not allowed.”)
=AND(IF(ISERROR(FIND(REGEX(“[^a-zA-Z0-9]”,[Visitor Full Name]))),TRUE,FALSE))
=IF(ISERROR(FIND(REGEX(“[^a-zA-Z0-9]”,ColumnName))),TRUE,FALSE)

below one is working but i need shorten length formula
=AND(IF(ISERROR(FIND(“0”,Title)),TRUE),IF(ISERROR(FIND(“1”,Title)),TRUE),IF(ISERROR(FIND(“2”,Title)),TRUE),IF(ISERROR(FIND(“3”,Title)),TRUE),IF(ISERROR(FIND(“4”,Title)),TRUE),IF(ISERROR(FIND(“5”,Title)),TRUE),IF(ISERROR(FIND(“6”,Title)),TRUE),IF(ISERROR(FIND(“7”,Title)),TRUE),IF(ISERROR(FIND(“8”,Title)),TRUE),IF(ISERROR(FIND(“9”,Title)),TRUE)

Thank you in advanced for your help..

How to make a scrollable bucket_list using shiny and sortable

Assuming following app from here.

How to

  1. fix the hight of the container aka “bucket-mother” aka rank_list_1 to a specific size (SOLVED using style i.e. max-height: 700px)
  2. and more importantly, how to make the list items scrollable?

Thus, a scrollbar has to be appear on the right side of the container if the number of list items is too high to show all.

library(shiny)
library(sortable)


ui <- fluidPage(
  tags$head(
    tags$style(HTML(".bucket-list-container {min-height: 350px;}"))
  ),
  fluidRow(
    column(
      width = 12,
      #choose list of variable names to send to bucket list
      radioButtons(inputId="variableList",
                   label="Choose your variable list",
                   choices = c("names(mtcars)"="names(mtcars)","state.name"="state.name")),
      #input text to subset variable names
      textInput(
        inputId = "subsetChooseListText",
        label = "Input text to subset list of states to choose from",
        value = "c"
      ),
      div(
        # class value is current default class value for container
        class = "bucket-list-container default-sortable",
        "Drag the items in any desired bucket",
        div(
          # class value is current default class value for list
          class = "default-sortable bucket-list bucket-list-horizontal",
          # need to make sure the outer div size is respected
          # use the current default flex value
          uiOutput("selection_list", style="flex:1 0 200px;"),
          rank_list(
            text = "to here",
            labels = list(),
            input_id = "rank_list_2",
            options = sortable_options(group = "mygroup")
          ),
          rank_list(
            text = "and also here",
            labels = list(),
            input_id = "rank_list_3",
            options = sortable_options(group = "mygroup")
          )
        )
      )
    )
  ),
  fluidRow(
    column(
      width = 12,
      tags$b("Result"),
      column(
        width = 12,
        
        tags$p("input$rank_list_1"),
        verbatimTextOutput("results_1"),
        
        tags$p("input$rank_list_2"),
        verbatimTextOutput("results_2"),
        
        tags$p("input$rank_list_3"),
        verbatimTextOutput("results_3")
        
      )
    )
  )
)

server <- function(input,output) {
  
  #initialize reactive values
  varList <- reactive({
    req(input$variableList)
    if (input$variableList == "state.name") {
      state.name
    } else {
      paste0(rep(names(mtcars), 20),"_", 1:220)
    }
  })
  
  subsetChooseList <- reactive({
    items <- varList()
    pattern <- input$subsetChooseListText
    if (nchar(pattern) < 1) {
      return(items)
    }
    items[
      grepl(
        x = items,
        pattern = input$subsetChooseListText,
        ignore.case = TRUE
      )
    ]
  })
  
  output$selection_list <- renderUI({
    labels <- subsetChooseList()
    
    # remove already chosen items
    labels <- labels[!(
      labels %in% input$rank_list_2 |
        labels %in% input$rank_list_3
    )]
    rank_list(
      text = "Drag from here",
      labels = labels,
      input_id = "rank_list_1",
      options = sortable_options(group = "mygroup")
    )
  })
  
  #visual output for debugging
  output$results_1 <- renderPrint(input$rank_list_1)
  output$results_2 <- renderPrint(input$rank_list_2)
  output$results_3 <- renderPrint(input$rank_list_3)
  
}


shinyApp(ui, server)

How can I build a text editor in React with contentEditable boxes to wrap user input that allows dynamic insertion of new boxes?

I am trying to build a text editor with React. I wish to wrap each paragraph the user enters with a “box” (which is a contentEditable HTMLElement) such that when the user press Enter, a new box will be inserted below the current working box.

During testing, I first created three boxes:
https://i.stack.imgur.com/Ylx8P.png

Then I tried to insert a new box between the 1st and 2nd boxes. However, instead of seeing four boxes, the last two boxes were replaced by this new box:
https://i.stack.imgur.com/U3xyX.png

Here are my code for the editor and the box. The addBoxHandler is the function responsible for inserting the new box:

export default function Editor(): JSX.Element {
  const initBox: BoxItem = {
    id: uuidv4(),
    html: ""
  };

  const [[Boxes, currBoxData], setBoxes] = useState<[BoxItem[],
    NewBoxData | undefined]>([[initBox], undefined]);

  useEffect(() => (currBoxData?.ref?.nextElementSibling as HTMLElement)?.focus(), 
    [Boxes, currBoxData]);

  const updatePageHandler = (updatedBox: BoxItem) => {
    const updatedBoxIndex: number = [...Boxes].findIndex(box => box.id === updatedBox.id);
    const updatedBoxes: BoxItem[] = [...Boxes];
    updatedBoxes[updatedBoxIndex] = {
      ...updatedBoxes[updatedBoxIndex],
      html: updatedBox.html,
    };
    const newBoxesState: [BoxItem[], NewBoxData | undefined] = [updatedBoxes, currBoxData];
    setBoxes(newBoxesState);
  };

  const addBoxHandler = (currBox: NewBoxData) => {
    const currBoxIndex: number = [...Boxes].findIndex(box => box.id === currBox.id);
    const updatedBoxes: BoxItem[] = [...Boxes];
    updatedBoxes.splice(currBoxIndex + 1, 0, { id: uuidv4(), html: "" });
    const newBoxesState: [BoxItem[], NewBoxData | undefined] = [updatedBoxes, currBox];
    console.log("Adding new box: " + updatedBoxes);
    setBoxes(newBoxesState);
    console.log("The new state is: " + Boxes);
  };

  return (
    <div>
      {Boxes.map(box => <Box
        id={box.id}
        html={box.html}
        onAddBox={addBoxHandler}
        onUpdatePage={updatePageHandler}
      />)}
    </div>
  );
}
export default function Box(props: BoxProps): JSX.Element {
  const [innerHtml, setInnerHtml] = useState<string>(props.html + "A Box for texts");
  const BoxRef = useRef<HTMLElement>(null);

  useEffect(() => {
    props.onUpdatePage({
      id: props.id,
      html: innerHtml,
    })
  }, [innerHtml]);

  return (
    <ContentEditable
      innerRef={BoxRef}
      html={innerHtml}
      tagName="p"
      onChange={event => setInnerHtml(event.target.value)}
      onKeyDown={event => {
        if (!event.shiftKey && event.key === "Enter") {
          event.preventDefault();
          props.onAddBox({ id: props.id, ref: BoxRef.current });
        }
      }}
    />
  );
}

I am following this guide. I tried to store an array of data for my boxes as a React state. However, according to what my debug code has logged, the useState did not seem to register the change in this array: https://i.stack.imgur.com/dG3yZ.png

I am quite confused with why React did not register the state changes and would like to seek a fix to my issue.

How can I fix ‘Something went wrong initializing the native ReactNativeLocalization module’ error when deploying a React Native iOS build?

So I want to create a build for iOS on my mac and I successfully did that. But currently my having these below errors:

`[Sat May 27 2023 13:03:34.703] ERROR Something went wrong initializing the native ReactNativeLocalization module.
Please check your configuration.
Did you run ‘react-native link’?

[Sat May 27 2023 13:03:34.704] ERROR TypeError: null is not an object (evaluating ‘localization.language’)
[Sat May 27 2023 13:03:34.705] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

[Sat May 27 2023 13:03:35.915] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)`

I tried pod install and update also but it’s still not working. All I can see is white blank screen on my emulator.

Rendering issue with state change In React

Here I want to conditionally render a loader when the state isLoading is true and otherwise show the button. Flow of the action -> once the dialog box is opened isLoading will be false and it will show the button, on clicking it it should change isLoading to true and show the loader in place of the button and then close the dialog.

code ->

export default function DialogBox(props) {
  const {
    show = false,
    title = "Title",
    onClose,
    onSuccess,
    primaryBtnText,
    secondaryBtnText,
    content,
    dark = false,
    danger = false,
    width,
    height,
    children,
    type,
    loading = false,
    ...rest
  } = props;
  const [open, setOpen] = useState(show);
  const classes = useStyles();
  const [isLoading, setIsLoading] = useState(loading);
  let paperStyle = {
    width,
    height,
  };
  paperStyle = dark
    ? {
        backgroundColor: "#161C23",
        ...paperStyle,
      }
    : paperStyle;

useEffect(() => {
  console.log(isLoading);
}, [isLoading])

  useEffect(() => {
    setOpen(show);
  }, [show]);

  const onCancelClick = () => {
    onClose && onClose();
    // setOpen(!open);
  };

  const onSucessClick = async () => {
    setIsLoading(true);
    // onSuccess && onSuccess();
    if (onSuccess) {
      await onSuccess();
    }
    setIsLoading(false);
    setOpen(false);
    // setOpen(!open);
  };

  const DiagTitle = dark ? NewDialogTitle : DialogTitle;

  const MainButton = withStyles({
    root: {
      fontSize: 14,
      fontWeight: 700,
      color: danger ? "#E76F6F" : "#92CFB3",
      marginLeft: 'auto',
    },
  })(Button);

  return (
    <Dialog
      open={open}
      PaperProps={{
        style: paperStyle,
      }}
      onClose={onCancelClick}
      aria-labelledby="form-dialog-title"
      {...rest}
    >
      {type !== "simple" && (
        <DiagTitle disableTypography={true} id="form-dialog-title">
          <div className={classes.dlgTitle}>{title}</div>
        </DiagTitle>
      )}
      <DialogContent className={`${type === "simple" ? classes.dlgContent : ""}`}>
        {content || children}
      </DialogContent>
      {type !== "simple" && (
        <DialogActions style={{ justifyContent: 'flex-start' }}>
          <CommonButton onClick={onCancelClick} color="primary">
            {`${secondaryBtnText || "Cancel"}`}
          </CommonButton>
          {isLoading ? (
            <div>
              <Loader small />
            </div>
          ) : (
            <MainButton onClick={onSucessClick} color="primary">
              {`${primaryBtnText || "Ok"}`}
            </MainButton>
          )}
          {/* <MainButton onClick={onSucessClick} color="primary">
            {isLoading ? <Loader small /> : `${primaryBtnText || "Ok"}`}
          </MainButton> */}
        </DialogActions>
      )}
    </Dialog>
  );
}

what happens with this code -> it shows the button initially, when button is clicked it will do the task and close the dialog, now on the next when when dialog is opened it will show the loader and not the button. Some logical error seems to be here.
(if for more details you want the calling components code, let me know in comments I will edit and put it, ig it is now needed)

return array of values from a function calling promise function in a loop

I have a list of orders called listedOrders. In a loop I have to call myGetMemberFunction() which will return email of one member. After the loop is finished I have to put all the emails for all the members in a list and send it back in the response body.

myListOrdersFunction() and myGetMemberFunction() both return a promise that resolve to the desired data.
How do I return back the list of values. Do i use resolve or what

I am trying to return a list of emails whenever someone calls my API. (using wix-http-functions)

const myListOrdersFunction = require('backend/test').myListOrdersFunction;
const myGetMemberFunction = require('backend/getMember').myGetMemberFunction;

$w.onReady(function () {
    const emailList = myListOrdersFunction()
        .then(listedOrders => {
            const loginEmails = [];
            for (const order of listedOrders) {
                myGetMemberFunction(order.buyer.memberId)
                    .then(member => {
                        loginEmails.push(member.loginEmail);
                    })
                    .catch(error => {
                        console.log(error);
                    });
            }
            return loginEmails;
            
        })
        .catch(error => {
            console.log(error);
        });

        const printEmails = async () => {
            const a = await emailList;
            console.log("a ",a);
            //response.body = {
            //   "emails": loginEmails
            //};
            //return ok(response);
        }

        printEmails();
});

The problem is how do I return loginEmails in response.body. I understand that you have to implement a callback to get promise value. I have tried to do it but I don’t know where I am wrong. I have seen a lot of stack overflow answers on the same problem but I am not getting it. I am using a loop. I get all the listedOrders from myListOrdersFunction(). For all listedOrders I call the myGetMemberFunction in a loop. Every call returns an email. I want to make a list of these emails and send in back in the response body. Please help. I am at my wits end