Hello everyone so i’ve ran into a problem. I’ve got a jquery object:
const popup = $('#popup') and I pass it to fancybox
$.fancybox.open(popup); but I also want to run an
afterClose on this popup, didn’t manage to find any info on how to do this. Did anyone run in this problem? How did you solve it?
Category: javascript
Category Added in a WPeMatico Campaign
Trying to ITerate through SQL rows using express
Hi can anyone help me iterate through each row and print them in a UL? I’ve tried a couple things but can’t seem to sucsessfully get anything other than ALL results.
Thanks,
Fix dimensions problem for inputShape in TensorflowJS
I am a Tensorflow JS beginner and have been struggling with running this model: https://gist.github.com/fromb2b/b7c57b314e62eddaabf2f21b399fb58a
I am getting Error:
UnhandledPromiseRejectionWarning: Error: Error when checking input: expected lstm_LSTM1_input to have 3 dimension(s). but got array with shape 1679,73
Do you have any suggestions?
After build Vue.js project the CASL library not working
I try check ability by class instance:
<Can
I="delete"
:a="createHomeTask(item.teacher.id)"
>
</Can>
Where ability description:
if (role === 'ROLE_teacher') {
can('delete', 'HomeTask', { teacher: user.id });
}
Where createHomeTask:
class HomeTask {
constructor(teacherId) {
this.teacher = teacherId;
}
}
export default function createHomeTask(teacherId) {
return new HomeTask(teacherId);
}
Before building the project, everything works fine, but after the build, this functionality does not work.
What could be the problem?
Swiper js autoheight prop not resizing for first slide height
So, I’m using SwiperJs with autoheight.
I expected that on slide change the container adapts its height depending on the content (simple images in my case). And it does update on slide change.
The problem is that on first load the slide seems to miscalculate the height and makes it a square, ignoring the content height.
You can take a look here
This are my dependencies:
"dependencies": {
"next": "12.1.6",
"react": "18.2.0",
"react-dom": "18.2.0",
"swiper": "^8.2.4"
},
This is the component:
return (
<article className='card mb-8 block'>
<div className='w-full'>
<Swiper autoHeight loop spaceBetween={0} slidesPerView={1}>
{images.map((image, i) => {
return (
<SwiperSlide key={i}>
<div className='custom-img-container'>
<Image className='custom-img' layout='fill' src={image} objectFit='cover' />
</div>
</SwiperSlide>
)
})}
</Swiper>
</div>
</article>
)
how can i check if a readline is closed node.js
i want to make a simple script that detects if a readline was closed, and if it wasn’t, it would close it.
preferably there would be a solution that works something like this:
if(!readline.isClosed){
readline.close()
}
Scripted Browser Selenium Element value Monitor (NewRelic)
I want to build a Scripted Monitor which monitors a specific element title on a page.
TLDR; I’m hosting a image service and want to check if a new picture is uploaded to the current camera roll. Therefore I created a Selenium script which clicks on the newest picture and saves the url name as vars.set(pageurl). Now I want to use New Relic Scripted Monitor to check if the url value is the same as before and if not it creates an alert.
It could also work with the element title or element id nr in the Xpath which changes for each picture.
You can find my anonymized script files below. Sadly I couldn’t find a way to give a value (in this example pageurl) out to the newrelic monitor. Maybe someone could figure that out for me. “Console.log” might work as an output for a value. Logger.log only displays each step in the script log.
Step 8 and 9 hover over the picture to display the title of the current picture, also the xpath changes of the item. Step 10 is clicking on the object which is visible after hovering over it. This whole process fails from time to time because of the timings.
I tried using the CSS selector but it didn’t work aswell, whole page is written in .js.
// Generated by Selenium IDE
// New Relic Synthetics Formatter for Selenium IDE
// Feel free to explore, or check out the full documentation
// https://docs.newrelic.com/docs/synthetics/new-relic-synthetics/scripting-monitors/writing-scripted-browsers
// for details
const assert = require("assert");
const urlRequest = require("urllib").request;
// Theshold for duration of entire script - fails test if script lasts longer than X (in ms)
// Script-wide timeout for all wait and waitAndFind functions (in ms)
var DefaultTimeout = 30000;
// Change to any User Agent you want to use.
// Leave as "default" or empty to use the Synthetics default.
var UserAgent = "default";
const By = $driver.By;
const browser = $browser.manage();
var vars = new Map();
const logger = function({timeout:e=18e4,stepLogging:t=!1,insightsKey:n=""}){const r=Date.now();var s=0,o="",i=0,a=0;function l({step:e=0,msg:t="",duration:r=0,eventType:s="SyntheticsCustom",custom:o={}}){if(void 0===n||""==n)return;var i={method:"POST",headers:{"X-Insert-Key":n,"Content-Type":"application/json"},data:{eventType:s,step:e,message:t,duration:r,JOB_ID:$env.JOB_ID,MONITOR_ID:$env.MONITOR_ID,ACCOUNT_ID:$env.ACCOUNT_ID,LOCATION:$env.LOCATION,PROXY_HOST:$env.PROXY_HOST,PROXY_PORT:$env.PROXY_PORT},dataType:"text"};const a=`https://insights-collector.newrelic.com/v1/accounts/${$env.ACCOUNT_ID}/events`;i.data=Object.assign({},i.data,o),urlRequest(a,i)}function c(e,t,n=""){e>a&&0!=a&&_({testCase:n});let i=`Step ${e}: ${t} STARTED at ${s=Date.now()-r}ms. testCase=${n}`;console.log(i),o=t,a=e}function _({testCase:i=""}){var c=Date.now()-r,_=c-s;if(console.log(`Step ${a}: ${o} FINISHED. It took ${_}ms to complete. testCase=${i}`),t&&n.length>0?l({step:a,msg:o,duration:_,custom:{testCase:i}}):t&&$util.insights.set(`Step ${a}: ${o}`,_),e>0&&c>e)throw new Error("Script timed out. "+c+"ms is longer than script timeout threshold of "+e+"ms.")}return{logStep:function(e){c(i++,e)},log:c,getStep:function(){return i},end:_,endTestCase:function(e=""){var i=Date.now()-r-s;console.log(`Step ${a}: ${o} FINISHED. It took ${i}ms to complete.`),t&&n.length>0?l({step:a,msg:o,duration:i,custom:{testCase:e}}):t&&$util.insights.set(`Step ${a}: ${o}`,i),$util.insights.set("testCase",e),$util.insights.set("testCaseStatus","Pass"),t&&n.length>0&&l({eventType:"SyntheticsTests",custom:{testCase:e,testCaseStatus:"Pass"}})},error:function(e,r=""){console.log(`Error in Step ${a}: ${o}`),$util.insights.set("errorStep",""+a),$util.insights.set("errorMsg",e.message),$util.insights.set("errorLineNumber",e.lineNumber),$util.insights.set("testCase",r),$util.insights.set("testCaseStatus","fail"),t&&n.length>0&&l({eventType:"SyntheticsTests",custom:{testCase:r,testCaseStatus:"Fail"}})},postInsights:l}}({})
$browser.getCapabilities().then(function () { })
// Test Case: bf
.then(function (){
return Promise.resolve(true)
.then( function(){return logger.log(1,"Open URL https://www.google.com/","bf"),$browser.get("https://www.google.com/").then(e=>e)})
.then( function(){return logger.log(2,"Set Window Size Width=1004 Height=708","bf"),$browser.manage().window().setSize(1004,708).then(e=>e)})
.then( function(){return logger.log(7,"Click By.css(".v-btn--large > .v-btn__content")","bf"),$browser.waitForAndFindElement(By.css(".v-btn--large > .v-btn__content"),DefaultTimeout).then(e=>(e.click(),Promise.resolve(!0)))})
.then( function(){return logger.log(8,"Mouse out By.tagName("body")","bf"),$browser.waitForAndFindElement(By.tagName("body"),DefaultTimeout).then(e=>Promise.resolve($browser.actions().mouseMove(e,0,0).perform()))})
.then( function(){return logger.log(9,"Mouse move","bf"),$browser.waitForAndFindElement(By.xpath("//div[@id='app']/div[20]/div/main/div/div/div/div[2]/div[4]/div[3]/div/div[2]"),DefaultTimeout).then(e=>Promise.resolve($browser.actions().mouseMove(e).perform()))})
.then( function(){return logger.log(10,"Click By.xpath("//div[@id=\'0[object Object]\']/div/div/div/div/div[3]")","bf"),$browser.waitForAndFindElement(By.xpath("//div[@id='0[object Object]']/div/div/div/div/div[3]"),DefaultTimeout).then(e=>(e.click(),Promise.resolve(!0)))})
.then(_=>{
return $browser.executeScript("return window.location.href")
.then(function(result){
vars.set("pageurl", result)
return Promise.resolve(true)
})
})
.then(function() {
logger.endTestCase("bf");
}, function(err) {
logger.error (err, "bf");
throw(err);
});
})
Ignoring SameSite behaviour from extension
I’m developing a Chrome extension that is going to be opening links inside of an internal CRM web application that has it’s SameSite cookie set to Strict.
I’m running into an issue where when I open the links in that web application from the extension (via the codded Chrome extension popup page), the session cookie isn’t being sent to the server (since the SameSite value is set to Strict). This seems like correct behaviour and SameSite is working properly.
However, is it possible to modify the “open page” request so that it sends the session cookie over when links are clicked/opened via the Chrome extension popup page?
I guess my question is it possible to modify the web requests and how to go about doing that.
Control HTML element’s style on scroll with window.scrollY
I’m trying to change font-size and margin-bottom of a div element when scrolling using window.addEventListener(‘scroll’, function(){}); and window.scrollY value. But I don’t want it to change forever if I don’t stop scrolling. I only want to reduce the font-size from 256px to about 192px and margin-bottom to about 128px. Can you guys please show me how to control it? Sorry I just started JS for couple days.
Below is the part of my code.
let brownie = document.getElementById('backgroundBrownie');
window.addEventListener('scroll', function() {
let value = window.scrollY;
brownie.style.fontSize = 256 - value / 4 + 'px';
brownie.style.marginBottom = value + 'px';
})
<div class="background">
<div class="backgroundText" id="backgroundBrownie">
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
</div>
</div>
is it possible evalute js code in wkhtmltopdf 0.12.5?
i am trying to run this code before converting html to pdf to give all elements the same height.
<script>
var rowWrappArr = [...document.querySelectorAll(".block__row-wrapp")];
rowWrappArr.forEach((currentRow, index) => {
var currentRowWrappHeight = rowWrappArr[index].offsetHeight;
var currentRowElemsArr = [...currentRow.children];
currentRowElemsArr.forEach((currentRowChild) => {
var currentRowChildElem = [...currentRowChild.children][0];
if (currentRowChildElem && currentRowChildElem.style) {
currentRowChildElem.style.height = currentRowWrappHeight + "px";
}
});
});
</script>
i use command
wkhtmltopdf ../../test.html –enable-javascript –javascript-delay
10000 test.pdf
but i get only white sheet as a result. I’m not sure if I understand correctly how wkhtmltopdf works with javascript. I also tried using var according to one of the tip it did not help. wkhtmltopdf version is 0.12.5
useState data:null after fetching API data and set to useState
My purpose is to create a fetching function and return useState Data and use this function in other component.
It’s fine to console.log (response.data).
However, when I console.log useState “Data” it’s show nothing after fetching data.
Can anybody tell me why and how to solve it?
import axios from "axios";
import { useState} from "react";
const FetchPost = async () => {
const [Data, setData] = useState(null)
try {
const response = await axios.get('url/api/blogs')
.then(console.log(response.data))
.then(setData(response.data))
console.log (`this is useState data:${Data}`)
}
catch (error) {
console.error(error);
}
return Data
}
export default FetchPost
How can i write the formula ‘Advance Distance = Radius * (Tan(Delta/2))’ as a react native function
Input two variables to get third (all decimals rounded to tenths)
i. Degrees of Course Change (aka Delta)
ii. Radius (nautical miles)
iii. Advance distance (nautical miles)
b. Base formula: Advance Distance = Radius * (Tan(Delta/2))
i. AKA: Advance distance equals the radius times the tangent of half of the
angle of the course change
c. Examples (user inputs highlighted yellow, app calculated answer highlighted
green):
i. Delta (deg): 60; Radius (nm): 1.5; Advance (nm): 0.87
- Advance (nm) = (1.5) * (Tan(60/2))
ii. Delta (deg): 140; Radius (nm): 1.0; Advance (nm): 2.75
- Advance (nm) = (1.0) * (Tan(140/2))
import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableWithoutFeedback, TextInput, Keyboard } from 'react-native';
import { TouchableHighlight } from 'react-native';
class AdvanceForm extends Component {
constructor(props) {
super(props);
this.state = {
advance: 0,
input: '',
radius: '',
delta: '',
calc: 0
};
this.onButtonPressed = this.onButtonPressed.bind(this);
this.calcAdvance = this.calcAdvance.bind(this);
this.storeData = this.storeData.bind(this);
}
onButtonPressed = function() { this.setState({ advance:this.state.radius })}
_handleTextChange = radius => { this.setState({ radius });
};
_handleTextChange2 = delta => { this.setState({ delta });
};
calcAdvance = async function() {
var x = parseFloat(this.state.radius);
var y = parseFloat(this.state.delta);
var calc = (x) * (Math.tan((Math.tan(y / 2))));
this.setState({ advance: calc})
this.storeData(await this.state.advance)
return;
}
//save the input
storeData = async () => {
let advance = this.state.advance;
await AsyncStorage.setItem('@advance', advance.toString())
console.log('Stored Advance: ' + advance)
return;
}
render() {
const {advance} = this.state;
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<View style={styles.container}>
<Text style={styles.paragraph}>
Advance Distance: { advance.toFixed(2) } (nm)
</Text>
<Text style={styles.text}> Radius (nm): </Text>
<TextInput
value={this.state.radius}
keyboardType = 'numeric'
onChangeText={this._handleTextChange}
style={styles.input}
/>
<Text style={styles.text}> Delta (deg): </Text>
<TextInput
value={this.state.delta}
keyboardType = 'numeric'
onChangeText={this._handleTextChange2}
style={styles.input}
/>
<TouchableHighlight onPress={this.calcAdvance.bind(this)}
style={styles.button}>
<Text style={styles.buttonText}>Calculate</Text>
</TouchableHighlight>
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
color: '#34495e',
},
text: {
color: 'black',
fontSize: 18,
padding: 10,
},
input: {
backgroundColor: 'grey',
width: 300,
height: 35,
color: 'white'
},
button: {
padding: 18,
margin: 16,
alignItems: 'center',
backgroundColor: 'blue',
borderRadius: 50,
width: 300
},
buttonText:{
color: 'white'
}
});
export default AdvanceForm;
UseState doesn’t rerender component
I have a set of Buttons where I want to render different divs depending on which button is active.
So far, the active button part works, and the state of click changes on Button clicked (as seen in my console statements from useEffect). However, handClick() doesn’t update the returned div when click is updated for some reason.
import React from 'react';
import Button from '../Utils/Button.js'
import { useState, useEffect } from 'react';
function App(props) {
const [img, setImg] = useState("2D")
const [click, setClick] = useState(" ")
const [active2, setActive2] = useState(-1)
//only trigger if SidebarClass state changed
useEffect(()=>{
console.log(click);
console.log("active2: " + active2)
},[click]);
function handleClick () {
let ret = def();
switch(click) {
case "div":
ret = div1()
break;
default:
ret = def()
break;
}
return ret;
}
function activeButton2(num, clicked) {
if (active2 == num) {
setActive2(-1)
setClick(" ")
console.log("unclick")
} else {
setActive2(num)
setClick(clicked)
console.log("click")
}
}
function div1() {
const modal = <h4>hello</h4>
return modal;
}
function def() {
const left = <div>
<h1> default </h1>
</div>
</div>
return left
}
function index() {
let i = props.index;
if (i == 0) {
const left = <div>
<Button text="3" more="no" status={active2 == 8} onClick={() => activeButton2(8, "div1")}/>
<Button text="4" more="no" status={active2 == 7} onClick={() => activeButton2(7, "div1")}/>
</div>
return left;
} else if (i == 1) {
const left = <div>
{handleClick()}
</div>
return left
}
return <div><h5>1</h5></div>
}
return (
<div>
{index()}
</div>
)
}
export default App;
I only have 1 div written for the rerender, and I’m looking to go from the default div to div1. However, that is not working atm.
Here’s my Button component:
import React from 'react';
import './Button.css'
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
};
this.handle = this.handle.bind(this)
}
handle() {
const currentState = this.state.active;
this.setState({ active: !currentState });
}
render() {
let c = 'inactive-button'
if (this.props.status == "false" || this.props.status == "0") {
c = 'inactive-button'
} else if (this.props.status == "true" || this.props.status == "1") {
c = 'active-button'
}
return (
<div>
<button className={c + " " + this.props.more} onClick={this.props.onClick}>
{this.props.text}
</button>
</div>
)
}
}
export default Button;
String /login?error after authorization attempt
I’m new in spring boot. Creating my own website. There was a problem logging in to the app. I’ve tried different methods, I don’t understand what the problem is. When entering an http request, this request appears http://localhost:8088/login?error and displays the Invalid email and password message in the form. The request goes through the database and everything is fine.I need it to go to the main page after logging in, which is what I tried to do.
UserService
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
private final UserRepository userRepository;
private final PasswordConfig passwordConfig;
private final RoleRepository roleRepository;
@Autowired
public UserServiceImpl(UserRepository userRepository, PasswordConfig passwordConfig,
RoleRepository roleRepository) {
this.userRepository = userRepository;
this.passwordConfig = passwordConfig;
this.roleRepository = roleRepository;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
final Optional<User> user = userRepository.findByEmail(email);
if(user.isPresent()) {
return user.get();
}else {
throw new UsernameNotFoundException(MessageFormat.format("User with email {0} not
found",email));
}
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
public User findUserById(Long userId) {
Optional<User> userFromDb = userRepository.findById(userId);
return userFromDb.orElse(new User());
}
@Override
@Transactional
public boolean signUp(User user) {
user.setPassword(passwordConfig.getPasswordEncoder().encode(user.getPassword()));
user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
userRepository.save(user);
return true;
}
AuthenticationController
@Controller
public class AuthenticationController {
private final UserServiceImpl userService;
@Autowired
public AuthenticationController(UserServiceImpl userService) {
this.userService = userService;
}
@GetMapping("/registration")
public String registerPage(Model model) {
model.addAttribute("user", new User());
return "registration";
}
@PostMapping ("/registration")
public String registerUser(@ModelAttribute("user") @Valid User user, BindingResult
bindingResult) {
if (bindingResult.hasErrors()) {
return "registration";
}
userService.signUp(user);
return "login";
}
@GetMapping("/login")
public String loginPage(){
return "login";
}
@GetMapping("/logout")
public String logoutPage() throws Exception {
return "redirect:/";
}
WebSecurityConfig
@Configuration
@EnableWebSecurity
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserServiceImpl userService;
private final PasswordConfig passwordConfig;
private final AuthenticationSuccessHandler authSuccessHandler;
@Autowired
public WebSecurityConfig(UserServiceImpl userService, PasswordConfig passwordConfig,
AuthenticationSuccessHandler authSuccessHandler) {
this.userService = userService;
this.passwordConfig = passwordConfig;
this.authSuccessHandler = authSuccessHandler;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordConfig.getPasswordEncoder());
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(passwordConfig.getPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/**")
.hasRole("USER")
.antMatchers("/admin/**")
.hasRole("ADMIN")
.antMatchers("/**")
.permitAll()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.permitAll();
http.csrf().disable();
http.headers().frameOptions().disable();
}
login.html
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title>SMS - Вход</title>
<link rel="stylesheet" type="text/css" href="/static/css/home.css"
th:href="@{/css/signup.css}">
</head>
<body>
<div sec:authorize="isAuthenticated()" class="container has-text-centered has-text-info">
<h1>already logged in!</h1>
</div>
<div sec:authorize="isAnonymous()" class="container">
<img th:src="@{/img/SMS.JPG}" class="logo" alt="">
<form action="/login" method="POST">
<input class="input" type="email" placeholder="email" name="username" >
<input class="input" type="password" placeholder="password" name="password" >
<p th:if="${param.error}" class="has-text-danger">
Invalid email and password.
</p>
<input type="checkbox" checked class="checkbox" id="terms-and-cond">
<label for="terms-and-cond">agree to our <a href="">terms and conditions</a></label>
<br>
<input type="checkbox" class="checkbox" id="notification">
<label for="notification">recieve upcoming offers and events mails</a></label>
<br>
<button type="submit" class="submit-btn">sign in</button>
</form>
<a href="/registration" class="link">registr</a>
<a href="/" class="link">index</a>
</div>
</body>
</html>
There are no errors in the console, only:
Hibernate: select user0_.user_id as user_id1_8_, user0_.create_time as create_t2_8_,
user0_.email as email3_8_, user0_.first_name as first_na4_8_, user0_.last_name as
last_nam5_8_, user0_.password as password6_8_, user0_.phone_number as phone_nu7_8_ from user
user0_ where user0_.email=?
Uncaught ReferenceError: function-name-here is not defined
I have a simple function:
function showit() {
$("#makeNewNet").removeClass("hidden");
$("#callsign").focus();
$("#openNets").addClass("hidden"); // Added 01-31-2017
$("#form-group-1").hide();
}
I’ve recently upgraded PHP from v4.7.9 to v7.4.21, but I’m not sure why that matters. In any case I now get this error, so maybe it does;
“Uncaught ReferenceError: showit is not defined”
Other SO articles said to take it out of a ready function. Did this to no avail.
Another one said to try…. nothing I could find helped.
I then tried removing all the content of the function replacing it with a simple console.log(“hello i’m in showit function”);
But it still says showit is not defined.
Why is this failing? What do I need to do to make the function work?