How do I get billing_state to affect billing_city’s values in Woocommerce?

I am trying to have each of the states represent a collection of cities, when an option is selected(in the billing_state field), it should display values in a billing_city drop down menu for that selected state.

I am also trying to make the billing_city field have a search bar with Select2, but I can’t get it work, I’ve tried many “Solutions”, It appears as a normal select drop down menu, without the search bar.

The solution I tried was posted on Change WooCommerce checkout city field to a dropdown for a unique country
Since I wanted to change it for the billing_state not billing_country, I’ve modified the code, but I don’t get the expected result and I am struggling to figure out why.
Here is the code:

add_filter( 'woocommerce_checkout_fields', 'add_custom_checkout_select_fields' );
function add_custom_checkout_select_fields( $fields ) {
    // Define HERE in the array, your desired cities
    $cities = array(
        __('Abrud','woocommerce'),
        __('Adjud','woocommerce'),
        __('Agnita','woocommerce'),
        __('Aiud','woocommerce'),
        __('Alba_Iulia','woocommerce'),
        __('Alesd','woocommerce'),
        __('Alexandria','woocommerce'),
        __('Amara','woocommerce'),
        __('Anina','woocommerce'),
        __('Aninoasa','woocommerce'),
        
    );

  

    // Adding 2 custom select fields
    $fields['billing']['billing_state2'] = $fields['shipping']['shipping_state2'] = array(
        'type'         => 'select',
        'required'     => true,
        'options'      => $options,
        'autocomplete' => 'address-level1',
    );
    
    // Copying data from WooCommerce city fields
    $fields['billing']['billing_city2']['class'] = array_merge($fields['billing']['billing_city']['class'], array('hidden') );
    $fields['shipping']['shipping_city2']['class'] = array_merge($fields['shipping']['shipping_city']['class'], array('hidden') );
    $fields['billing']['billing_city2']['label'] = $fields['billing']['billing_city']['label'];
    $fields['shipping']['shipping_city2']['label'] = $fields['shipping']['shipping_city']['label'];
    $fields['billing']['billing_city2']['priority'] = $fields['billing']['billing_city']['priority'] + 5;
    $fields['shipping']['shipping_city2']['priority'] = $fields['shipping']['shipping_city']['priority'] + 5;

    return $fields;
}

// Custom inline styles to hide some checkout fields
add_action( 'wp_head', 'custom_checkout_css' );
function custom_checkout_css() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ) {
        ?><style>
        #billing_city_field.hidden, #billing_city2_field.hidden,
        #shipping_city_field.hidden, #shipping_city2_field.hidden
        {display:none !important;}
        </style><?php
    }
}

// Custom jQuery code
add_action( 'wp_footer', 'custom_checkout_js_script' );
function custom_checkout_js_script() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):
    ?>
    <script type="text/javascript">
    (function($){
        var targetedState = 'Alba',
            initialBState = '<?php echo WC()->customer->get_billing_state(); ?>',
            initialSState = '<?php echo WC()->customer->get_shipping_state(); ?>';

        function showHideFields( country, fieldset ) {
            var select2Classes = 'country_select select2-hidden-accessible';

            if( country === targetedState ) {
                $('#'+fieldset+'_city2_field').removeClass('hidden');
                $('#'+fieldset+'_city_field').addClass('hidden');
                $('select#'+fieldset+'_city2').addClass(select2Classes);
            } else if( country !== targetedState && $('#'+fieldset+'_city_field').hasClass('hidden') ) {
                $('#'+fieldset+'_city2_field').addClass('hidden');
                $('#'+fieldset+'_city_field').removeClass('hidden');
                $('select#'+fieldset+'_city2').removeClass(select2Classes);
            }
        }

        // 1. On Start (after Checkout is loaded)
        showHideFields(initialBState, 'billing');
        showHideFields(initialSState, 'shipping');

        // 2. Live: On State change event
        $('body').on( 'change', 'select#billing_state', function(){
            showHideFields($(this).val(), 'billing');
        });
        $('body').on( 'change', 'select#shipping_state', function(){
            showHideFields($(this).val(), 'shipping');
        });

        // 3. Live: On City change event for "Alba" state
        $('body').on( 'change', 'select#billing_city', function(){
             $('input#billing_city').val($(this).val());
        });
        $('body').on( 'change', 'select#shipping_city', function(){
             $('input#shipping_city').val($(this).val());
        });
    })(jQuery);
    </script>
    <?php
    endif;
}

So for example if I choose “Alba” in the billing_state drop down field, there should only be the first 3 cities popping up in billing_city drop down field. (Abrud, Adjud, Agnita)

All of the changes I am making are in the functions.php located in Theme File Editor.

is there a way to remove title on each screens in expo?

i am a beginner in react-native, i follow tutorials on youtube to make projects. i am trying to make an expo ui-app, but each screens has a title on the top like this:
enter image description here

There is the word Explore above the screen, and each other screens has the corresponding title above it aswell. Is there a way to remove this? because i followed tutorials from youtube but they didnt have this title.

Here is the Explore.js file:

import { StyleSheet, Text, View, SafeAreaView, TextInput, Platform, StatusBar } from 'react-native';
import React, { Component } from 'react';
import { Ionicons } from '@expo/vector-icons';


class Explore extends Component {

  componentWillMount() {
    this.startHeaderHeight = 80
    if(Platform.OS == 'android')
    {
      this.startHeaderHeight = 100 + StatusBar.currentHeight
    }
  }

  render() {
   return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 }}>
        <View style={{ height: this.startHeaderHeight, backgroundColor: 'white', borderBottomWidth: 1, borderBottomColor: '#dddddd' }}>
          <View style={{flexDirection: 'row', padding: 10, backgroundColor: 'white', marginHorizontal: 20, shadowOffset:{width:0,height:0}, shadowColor: 'black', shadowOpacity: 0.2, elevation: 1, marginTop: Platform.OS == 'android' ? 30 : 20 }}>
            <Ionicons name="ios-search" size={20} color="black" />
            <TextInput 
              underlineColorAndroid="transparent"
              placeholder='Try Indonesia'
              placeholderTextColor="grey"
              style={{ flex: 1, fontWeight: '700', backgroundColor: 'white', marginLeft: 10 }}            
            />
          </View>
        </View>
      </View>
    </SafeAreaView>
    );
  }
}
export default Explore;


const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

and here is my app.js file:

import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { Ionicons } from '@expo/vector-icons';
import { FontAwesome5 } from '@expo/vector-icons'; 


import Explore from './screens/Explore';
import Saved from './screens/Saved';
import Trips from './screens/Trips';
import Inbox from './screens/Inbox';

const Tab = createBottomTabNavigator();

export default function BottomTabs() {
  return (
    <NavigationContainer>

      <..... CODE OF THE BOTTOM TAB NAVIGATOR IN HERE .....>

    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

How can i pick out the integers that are smaller or equal to 60 with .map array method

 const recipes = [
  {
    title: 'Crepes',
    duration: 60,
    ingredients: ['butter', 'flour', 'eggs', 'milk', 'salt'],
    servings: 3
  },
  {
    title: 'Scrambled Eggs',
    duration: 20,
    ingredients: ['eggs', 'milk', 'salt'],
    servings: 2
  },
  {
    title: 'Vegan Salmon',
    duration: 60 * 24 * 3, // 3 days
    ingredients: ['carrots', 'olive oil', 'nori sheets', 'liquid smoke', 'soy sauce'],
    servings: 10
  },
  {
    title: 'Carot Cake',
    duration: 120,
    ingredients: ['carrots', 'flour', 'eggs', 'salt', 'milk', 'sugar'],
    servings: 10
  }
]

I want to create an array like this:

['Crepes (60min)', ...]

Thats my code so far:

    const titlesWithDuration = recipes.map((titles) => {
      return `${titles.title} (${titles.duration}min)`; 
    }); 

console.log(titlesWithDuration)

Problem is, if i use things like operators, for example:

titles.duration <= 60

i will get this:

["Crepes (truemin)","Scrambled Eggs (truemin)","Vegan Salmon (falsemin)","Carot Cake (falsemin)"]

How can i use operators which give me a string output?

why is MapView from expo not working properly

I’m working with the MapView library from expo ! as you can see in the code everything is logic but it keeps telling me ‘The prop coordinate.latitude is marked as required in MapMarker, but its value is undefined ‘ even tho I’m consoling log the event and it’s showing that it is not undefined

  "action": "press",
  "coordinate": Object {
    "latitude": 37.73174790670175,
    "longitude": -122.47094504535197,
  },
  "position": Object {
    "x": 352,
    "y": 307,
  },
}

and this is my code :

const MapScreen = ({ navigation }) => {

  const MapRegion = {
    latitude: 37.78,
    longitude: -122.43,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
  };
  const [newCoor, setNewCoor] = useState();

  let markerCoordinates;

  const selectLocationHandler = (event) => {
    console.log("ana", event.nativeEvent);
    setNewCoor({
      lat: event.nativeEvent.coordinate.latitude,
      lng: event.nativeEvent.coordinate.longitude,
    });
    console.log(newCoor);
  };
  if (newCoor) {
    markerCoordinates = {
      latitude: newCoor.latitude,
      longitude: newCoor.longitude,
    };
  }
  const savePickedLocationHandler = () => {
    if (!newCoor) {
      return;
    }
    navigation.navigate("NewPlaceScreen", { pickedLocation: newCoor });
  };

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity
          style={{ marginHorizontal: 20 }}
          onPress={savePickedLocationHandler}
        >
          <Text
            style={{
              fontSize: 19,
              fontWeight: "bold",
              color: Platform.OS === "android" ? "#C06E00" : "white",
            }}
          >
            Save
          </Text>
        </TouchableOpacity>
      ),
    });
  }, []);
  
  return (
    <MapView
      style={styles.mapImage}
      region={MapRegion}
      onPress={selectLocationHandler}
    >
      {markerCoordinates && <Marker coordinate={markerCoordinates}></Marker>}
    </MapView>
  );
};

const styles = StyleSheet.create({
  mapImage: {
    flex: 1,
  },
});

export default MapScreen;

chatbot reponse to increase progress bar

I working on a chatbot where I want to increase the progress bar depending on which intents the chatbot response comes from. The dataset is a JSON file containing responses for the chatbot. I want the progress bar to move accordingly by a certain percent depending on which “tag” the chatbot response comes from. I have used the fetch method to get the JSON data, looped through intents, and put them in different lists. The problem seems to be that the progress bar only moves once and then stops no matter what I type.

function botResponse(rawText) {
    const bot_rep = [];
    const bot_tag_1 = [];
    const bot_tag_2 = [];
    let counter = 0;
    let percent = document.getElementById('percent');
        let bar = document.getElementById('bar');
    //const i=0;
     fetch("http://127.0.0.1:5000/json") //fetch the json file
    .then(response=>response.json())
    .then(data=>{
          for (i in data.intents[0].responses){ //loop through intetnts
          bot_tag_1.push(data.intents[0].responses[i]); //push all responses from intents "greeting" [0] to list bot_tag_1
          //console.log(data.intents[0].responses)
          console.log(bot_tag_1.length);
          }
          if(bot_rep.indexOf(bot_tag_1 )){ //if the chatbot's response comes from/exists in bot_tag_1 increase by 2%
            //var count = 1;
            //console.log(bot_tag_2);
            console.log("from tag greeting "+ "points increase 2 pts");
            counter = 2;//count * 2;
            percent.innerHTML = `${counter}%`;
            bar.style.width = `${counter}%`;
        }

          for (i in data.intents[1].responses){  //loop through intents
          bot_tag_2.push(data.intents[1].responses[i]); //push all responses from intents "goodbye" [1] to list bot_tag_2
          //console.log(data.intents[1].tag)
          console.log(bot_tag_2.length);
          }
          if(bot_rep.indexOf(bot_tag_2 )){ //if the chatbot's response comes from/exists in bot_tag_2 increase by 10%
            //var count = 1;
            //console.log(bot_tag_2);
            console.log("from tag goodbye "+ "points increase 10pts");
            counter = 10;
            percent.innerHTML = `${counter}%`;
            bar.style.width = `${counter}%`;
        }
          //console.log(data);
          //console.log(data.intents[1].responses);
          //console.log(data.intents[0].tag);
         
    })
#progress {
 width: 500px;   
 border: 1px solid black;
 position: relative;
 padding: 3px;
 top: 16px; 
}

#percent {
 position: absolute;   
 left: 50%;
 bottom: 25px;
}

#bar {
 height: 20px;
 background-color: green;
 
 
 width: 0%;
}

<!-- JSON file 
{"intents": [
            {"tag": "greeting",
            "patterns": ["Hi", "How are you?", "Hello", "Whats up?", "hiii"],
            "responses": ["Hello!", "Hi there, how can I help?"],
            "context_set": ""
            },
            {"tag": "goodbye",
                "patterns": ["cya", "See you later!", "Bye Bye!", "Goodbye", "Peace out"],
                "responses": ["Will miss you!", "Okay, talk to you later!", "Goodbye!"],
                "context_set": ""
            },
            {"tag": "language",
                "patterns": ["What language are you written in??"],
                "responses": ["Im written in Python"],
                "context_set": ""
            },
<html lang="en">

<head>

</head>

<body>
    <div class="progress">
            progress Bar
    <div id="progress">
           <span id="percent">0%</span>
           <div id="bar"></div>
    </div>


</body>

</html>

Regular expression not supported by Javascript? [duplicate]

I’m trying to use a regular expression, I tried several changes and searches but none worked correctly.

regular expression
https://regex101.com/r/lK1tD6/1

var reg = '(?:(?<=^)|(?<=D))((00|+)?55(s|.|-)*)?((()?0 ?d{2}(?(5))|)(s|.|-)*)?(9(s|.|-)*)?d{4}(s| .|-)*d{4}(?=D|$)'gm
var search = value => value && value.match(reg);

var content = '+55 55 55555-5555';
var phones = search(content);
console.log(phones);

Thanks in advance 🙂

State not Rendering to UI, Element is added in array

Hi I have created a react application, I am passing an array of object that renders in the UI , When I am adding an element to it using useState , The element is added but it doesn’t render in the UI , I am adding the jsx code for refrence, I need a suggestion on what is causing the issue.

App.jsx

import logo from "./logo.svg";
import "./App.css";
import Expense from "./components/ExpenseComponent/Expense";
import NewExpense from "./components/AddExpenseComponent/NewExpense";
import React,{useState} from "react";

const expenseItem = [
  { title: "furniture", ammount: 568, date: new Date(2022, 2, 23) },
  { title: "books", ammount: 30, date: new Date(2022, 2, 24) },
  { title: "Electronics", ammount: 468, date: new Date(2022, 2, 23) },
  { title: "sports", ammount: 340, date: new Date(2022, 2, 24) },
  { title: "virtual media", ammount: 268, date: new Date(2022, 2, 23) },
];

const App=()=> {
  
  const[expenses,newExpenseItem] = useState(expenseItem);
  const addExpense = (expense) =>{
    newExpenseItem((prevExpense) =>{
      return [expense,...prevExpense];
    });
    
  };
  return (
    <div id="root">
      <NewExpense addExpenseToArray={addExpense}/>
      <Expense items={expenseItem} />
    </div>
  );
}

export default App;

Expense.jsx

import "../ExpenseComponent/Expense.css";
import ExpenseItem from "../ExpenseComponent/ExpenseItem";
import ExpenseFilter from "../AddExpenseComponent/ExpenseFilter";
export const Expense = (props) => {
  //let item = props.items;
  const getYear = (targetYear) => {
    console.log(targetYear);
    //console.log(item);
  };
  return (
    <div className="expenses">
      <ExpenseFilter getTargetYear={getYear} />
      {props.items.map((expense) => (
        <ExpenseItem
          title={expense.title}
          ammount={expense.ammount}
          date={expense.date}
        />
      ))}
    </div>
  );
};

export default Expense;

NewExpense.jsx

import React from "react";
import ExpenseForm from "./ExpenseForm";
import "./NewExpense.css";
const NewExpense = (props) => {
  const getNewExpenseData = (newExpenseData) => {
    //const expenseData = newExpenseData;
    props.addExpenseToArray(newExpenseData);
    //console.log(expenseData);
  };

  return (
    <div>
      <div className="new-expense">
        <ExpenseForm getExpenseData={getNewExpenseData} />
      </div>
    </div>
  );
};

export default NewExpense;

Challenge: Predict what an element’s calculated CSS property would fall back to if it’s effective value was deleted – without causing style flickers?

Let’s say we have an HTMLElement that is styled inline relative to a given CSS property and that window.getComputedStyle(HTMLElement).getPropertyValue(theCSSProperty) returns the value reflecting the inline styling.

If we did: HTMLElement.style.removeProperty(theCSSProperty), window.getComputedStyle(HTMLElement ).getPropertyValue(theCSSProperty) would show the fallback value (not necessarily the same as the default value).

I would like to be able to predict that fallback value without actually deleting the effective value, but with my current take at it, it seems quite difficult because the process of calculating the effective style, as this post hints at, is not at all that simple.

I have thought about other hackish solutions such as cloning the element out of sight and manipulating the clone instead, but that is not a bullet proof solution – due to possible nth-child styling for one thing.

So my conclusion is: It ain’t easy (not the same as undoable). But before I leave it at that, I thought I might as well check with the community that there isn’t some obvious solution I have missed. How would you approach this if you had to?

How to convert string from ENV to hex in JavaScript? [duplicate]

In my .env file I have such environmental variable:

CRYPTO_KEY_SHORT=x12x34x56x78x9Ax12x32xE3

I use this string as a key in code, like this:

const decryptedHash = cryptoService.decryptHex(confirmToken, `${process.env.CRYPTO_KEY_SHORT}`, null)

And here is the problem, it doesn’t work this way, every time I get error – Error: Invalid key length, but if I hardcode this it work:

const decryptedHash = cryptoService.decryptHex(confirmToken, "x12x34x56x78x9Ax12x32xE3", null)

So, after putting such variable to .env how can I use it?

Possibility of Downloading a file with a specified content length slightly bigger than actual file

I want to know if it’s possible to download a file that has a file size lesser than the specified content length.
For example, let’s say it has an actual size of

size: 3165076 Bytes

And the specified content length is

3336523 Bytes

From my previous experience this results in an infinite download loop. So i want to know if it’s possible to round off the download when it has reached its total size or better still specify a size range