问:
Using query params in Azure functions and Cosmos DB
I'm using Azure Functions to retrieve data from a Cosmos DB. No I have the following SQL query:

```<code>SELECT * FROM r WHERE r.city = {city} AND r.district = {district} AND r.max_number_of_people = {people}
</code>```

When I make a request using these as the query params: "?city=Amsterdam&district=West&people=2" I'm not getting anything back. I tried it without the people param, and then it works.

I think it has something to do with the max_number_of_people being saved as a number in my container, but I'm not sure.

What could be the issue here?

```<code>// function.json
{
  "bindings": [
    {
      "name": "req",
      "route": "restaurants/available",
      "authLevel": "function",
      "methods": ["get"],
      "direction": "in",
      "type": "httpTrigger"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "restaurants",
      "databaseName": "find-your-spot",
      "collectionName": "restaurants",
      "connectionStringSetting": "fys-d-cdb_DOCUMENTDB",
      "sqlQuery": "SELECT * FROM r WHERE r.city = {city} AND r.district = {district} AND r.max_number_of_people = {people}",
      "direction": "in",
      "type": "cosmosDB"
    }
  ]
}
</code>```
```<code>// index.js
module.exports = async function (context, req, restaurants) {
  try {
    context.res.status(200).json(restaurants);
  } catch (error) {
    context.res.status(500).json(error);
  }
};

</code>```

答:
Well, I found a way to accomplish what I want. It may not be the only way.</p>
```<code>SELECT * FROM r WHERE r.city = {city} AND r.district = {district} AND ToString(r.max_number_of_people) = {people}
</code>```

Body:
I'm using Azure Functions to retrieve data from a Cosmos DB. No I have the following SQL query:

SELECT * FROM r WHERE r.city = {city} AND r.district = {district} AND r.max_number_of_people = {people}

When I make a request using these as the query params: "?city=Amsterdam&district=West&people=2" I'm not getting anything back. I tried it without the people param, and then it works.

I think it has something to do with the max_number_of_people being saved as a number in my container, but I'm not sure.

What could be the issue here?

// function.json
{
  "bindings": [
    {
      "name": "req",
      "route": "restaurants/available",
      "authLevel": "function",
      "methods": ["get"],
      "direction": "in",
      "type": "httpTrigger"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "restaurants",
      "databaseName": "find-your-spot",
      "collectionName": "restaurants",
      "connectionStringSetting": "fys-d-cdb_DOCUMENTDB",
      "sqlQuery": "SELECT * FROM r WHERE r.city = {city} AND r.district = {district} AND r.max_number_of_people = {people}",
      "direction": "in",
      "type": "cosmosDB"
    }
  ]
}

// index.js
module.exports = async function (context, req, restaurants) {
  try {
    context.res.status(200).json(restaurants);
  } catch (error) {
    context.res.status(500).json(error);
  }
};

Body:
Well, I found a way to accomplish what I want. It may not be the only way.

SELECT * FROM r WHERE r.city = {city} AND r.district = {district} AND ToString(r.max_number_of_people) = {people}


来源: stackexchange

问:
Error: Entrypoint isn't within the current project
Unable to run flutter from Android Studio not detecting flutter project its shows Error: Entry point isn't within the current project

Every time restart android studio same error message shows

答:
You might need to update the Gradle version. Or change the minimum android SDK version.

Here is worked for me:

Update Gradle / minSdkVersion version

Reopen the project but at the directory user/StudioProjects/yourFlutterApp/android.
After it is opened it will load some packages (see right bottom), which will take some time.

It will ask you to update the Gradle version (right-left corner) or go under File>Project Structure Project you can set a higher Gradle version and under Modules variables of your build

Now you can sync your project with Gradle files

After configuration, you might need to restart your project with File>Invalid Caches/Restart....

ContentLicense: CC BY-SA 4.0


问:
Solidity, Member "transfer" not found or not visible after argument-dependent
Using Solidity ^0.5.0,
I'm actually trying to implement an old code working in ^0.4.17, but it throws an error on Remix.
I checked syntax and everything but just can't catch what's wrong.
Any help highly appreciated.

```<code>pragma solidity ^0.5.0;

contract Lottery{
  address public manager;
  address[] public players;

  constructor() public {
      manager = msg.sender;
  }

   function participate() public payable {
       require(msg.value > .01 ether);
       players.push(msg.sender);
  }

   function pseudoRandom() private view returns(uint){
    return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
  }

  function pickWinner() public {
    uint index = pseudoRandom() % players.length;
    players[index].transfer(address(this).balance);
  }
}
</code>```

Here is the error message:

browser/Lottery.sol:22:8: TypeError: Member "transfer" not found or not visible after argument-dependent
lookup in address.

players[index].transfer(address(msg.sender).balance);

^---------------------^

答:
This is how overall contract code looks like</p>
```<code>// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

contract Lottery {
    address public manager;
    address payable[] public players;

    constructor() { }

    function lottery() public {
        manager = msg.sender;
    }

    function enter() public payable {
        require(msg.value > .01 ether);
        players.push(payable(msg.sender));
    }

    function random() public view returns (uint8) {
        return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, players)))%251);
    }

    function pickWinner() public {
        uint index = random() % players.length;
        players[index].transfer(address(this).balance);
    }
}
</code>```

Body:
Using Solidity ^0.5.0,
I'm actually trying to implement an old code working in ^0.4.17, but it throws an error on Remix.
I checked syntax and everything but just can't catch what's wrong.
Any help highly appreciated.

pragma solidity ^0.5.0;

contract Lottery{
  address public manager;
  address[] public players;

  constructor() public {
      manager = msg.sender;
  }

   function participate() public payable {
       require(msg.value > .01 ether);
       players.push(msg.sender);
  }

   function pseudoRandom() private view returns(uint){
    return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
  }

  function pickWinner() public {
    uint index = pseudoRandom() % players.length;
    players[index].transfer(address(this).balance);
  }
}

Here is the error message:

browser/Lottery.sol:22:8: TypeError: Member "transfer" not found or not visible after argument-dependent
lookup in address.

players[index].transfer(address(msg.sender).balance);

^---------------------^

Body:
This is how overall contract code looks like

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

contract Lottery {
    address public manager;
    address payable[] public players;

    constructor() { }

    function lottery() public {
        manager = msg.sender;
    }

    function enter() public payable {
        require(msg.value > .01 ether);
        players.push(payable(msg.sender));
    }

    function random() public view returns (uint8) {
        return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, players)))%251);
    }

    function pickWinner() public {
        uint index = random() % players.length;
        players[index].transfer(address(this).balance);
    }
}


问:
Does Java stream().sorted or list.sort() not increases time complexity?
While making some sortings, some people suggest using stream().sorted or list.sort() methods in Java to reduce time complexity. However, I think these methods also use some sorting algorithms that has a similar time complexity.

```<code>List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());
</code>```

So, does it mean that these algorithms use the most efficient sorting algorithms for sorting less time than I sort in 2 nested for loop?

答:
Sorting algorithms that use nested loops are usually O(n²) complexity, due to every iteration of the inner loop occurring for every iteration of the outer loop. Some of these algorithms would be

Insertion Sort;

Bubble Sort;

etc;

However, other do not use nested loops as you mentioned, for example, the most used sorting algorithm for general use would be QuickSort, which stands as a Divide and Conquer Algorithm, it starts by selecting a pivot value and rearranging the array based on said pivot value, with all smaller values coming before it, and all larger values coming after it (Not necessarily ordered yet).

QuickSort stands as O(nlog(n)) Average case complexity. Do bear in mind that some of the more advanced sorting algorithms also have a worst case scenario complexity of O(n^2).

In fact, some sorting implementations actually shuffle the array before sorting it just to avoid the worst case scenario.

I leave here some information about Quicksort below.

Quicksort explanation and how it works

Body:
While making some sortings, some people suggest using stream().sorted or list.sort() methods in Java to reduce time complexity. However, I think these methods also use some sorting algorithms that has a similar time complexity.

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

So, does it mean that these algorithms use the most efficient sorting algorithms for sorting less time than I sort in 2 nested for loop?


问:
TypeError React-Leaflet: Cannot read property 'x' of null
When I click on marker, this error appears. Everything was fine before I added custom Icon. But now it does not show the popup at all.

Custom Icon:

```<code>const MapSection = () => {
  const customIcon = new L.Icon({
    iconUrl: '../marker.svg',
    iconRetinaUrl: '../marker.svg',
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(50, 65),
    className: 'leaflet-div-icon',
  });
</code>```

Marker Code:

```<code><MarkerClusterGroup>
  {markerData.map((singleMarker) => (
    <Marker icon={customIcon} position={[singleMarker.lat, singleMarker.long]}>
      <Popup className={classes.popup}>
        {/* <Typography>موسسه دکتر شیری جلالی</Typography> */}
        <MapCard id={singleMarker.organization_id} />
      </Popup>
    </Marker>
  ))}
</MarkerClusterGroup>;
</code>```

Error:

```<code>  52 |
  53 | _add: function (point) {
  54 |  // destructive, used directly for performance in situations where it's safe to modify existing point
> 55 |  this.x += point.x;
     | ^  56 |  this.y += point.y;
  57 |  return this;
  58 | },
</code>```

答:
Leaflet doesn't know where to anchor your marker's icon (or the icon shadow, popup, etct) relative to the latLng. That is determined by the values iconAnchor, popupAnchor, shadowUrl, shadowSize, shadowAnchor need to have values. Without values, leaflet is look for x and y of null, hence the error , or you could simply cut iconAnchor, popupAnchor from you map object:</p>
```<code>let locationIcon = new L.Icon({
iconUrl: mapMarker,
iconRetinaUrl: mapMarker,
// iconAnchor: ['35.739212', '51.412767'],
// popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null,
iconSize: new L.Point(35, 45),
className: 'location-icon',
  })
 return (
      <Marker
      position={[item.lat, item.lng]}
      icon={locationIcon}

      // interactive={false}
      key={item.merchantId}
      eventHandlers={{
        click: (e) => {
          console.log('marker clicked', e)
          handleShowDetails(item)
        }
      }}
    >
</code>```

Body:
When I click on marker, this error appears. Everything was fine before I added custom Icon. But now it does not show the popup at all.

Custom Icon:

const MapSection = () => {
  const customIcon = new L.Icon({
    iconUrl: '../marker.svg',
    iconRetinaUrl: '../marker.svg',
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(50, 65),
    className: 'leaflet-div-icon',
  });

Marker Code:

<MarkerClusterGroup>
  {markerData.map((singleMarker) => (
    <Marker icon={customIcon} position={[singleMarker.lat, singleMarker.long]}>
      <Popup className={classes.popup}>
        {/* <Typography>موسسه دکتر شیری جلالی</Typography> */}
        <MapCard id={singleMarker.organization_id} />
      </Popup>
    </Marker>
  ))}
</MarkerClusterGroup>;

Error:

  52 |
  53 | _add: function (point) {
  54 |  // destructive, used directly for performance in situations where it's safe to modify existing point
> 55 |  this.x += point.x;
     | ^  56 |  this.y += point.y;
  57 |  return this;
  58 | },

Body:
Leaflet doesn't know where to anchor your marker's icon (or the icon shadow, popup, etct) relative to the latLng. That is determined by the values iconAnchor, popupAnchor, shadowUrl, shadowSize, shadowAnchor need to have values. Without values, leaflet is look for x and y of null, hence the error , or you could simply cut iconAnchor, popupAnchor from you map object:

let locationIcon = new L.Icon({
iconUrl: mapMarker,
iconRetinaUrl: mapMarker,
// iconAnchor: ['35.739212', '51.412767'],
// popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null,
iconSize: new L.Point(35, 45),
className: 'location-icon',
  })
 return (
      <Marker
      position={[item.lat, item.lng]}
      icon={locationIcon}

      // interactive={false}
      key={item.merchantId}
      eventHandlers={{
        click: (e) => {
          console.log('marker clicked', e)
          handleShowDetails(item)
        }
      }}
    >


问:
Need to output javascript date object from a php json_encode call
```<code>$array = array('start'=>"new Date(".date("Y",strtotime($start_date)).")");
$myJson = json_encode($array);
</code>```

The returned json is a string, how can i convert the dates to objects? I'm using the jquery calendar plugin and it wants a date object. Thanks!

答:
Send a date string normally with json and then parse it with javascript:
var d = Date.parse("Jul 8, 2005");

Reference: http://www.w3schools.com/jsref/jsref_parse.asp

ContentLicense: CC BY-SA 3.0

Body:
$array = array('start'=>"new Date(".date("Y",strtotime($start_date)).")");
$myJson = json_encode($array);

The returned json is a string, how can i convert the dates to objects? I'm using the jquery calendar plugin and it wants a date object. Thanks!


问:
Get function parameter length including default params
If you make use of the Function.length property, you get the total amount of arguments that function expects.

However, according to the documentation (as well as actually trying it out), it does not include Default parameters in the count.

This number excludes the rest parameter and only includes parameters before the first one with a default value
  - Function.length

Is it possible for me to somehow get a count (from outside the function) which includes Default parameters as well?

答:
Here is a function to retrieve the 'length' of a function (expression or object) or an arrow function expression (afe). It uses a regular expression to extract the arguments part from the stringified function/afe (the part between () or before =>) and a regular expression to cleanup default values that are strings. After the cleanups, it counts the comma's, depending on the brackets within the arguments string.

Note This will always be an approximation. There are edge cases that won't be covered. See the tests in this Stackblitz snippet

const determineFnLength = fnLenFactory();

console.log(`fnTest.length: ${determineFnLength(fnTest)}`);

function fnTest(a,
  b,
  c = 'with escaped \' quote and, comma',
  d = "and double \" quotes, too!" ) { console.log(`test123`); }

function fnLenFactory() {
  const fnExtractArgsRE = /(^[a-z_](?=(=>|=>{)))|((^\([^)].+\)|\(\))(?=(=>|{)))/g;
  const valueParamsCleanupRE = /(?<=[`"'])([^\`,].+?)(?=[`"'])/g;
  const countArgumentsByBrackets = params => {
    let [commaCount, bracketCount, bOpen, bClose] = [0, 0, [...`([{`], [...`)]}`]];
    [...params].forEach( chr => {
      bracketCount += bOpen.includes(chr) ? 1 : bClose.includes(chr) ? -1 : 0;
      commaCount += chr === ',' && bracketCount === 1 ? 1 : 0; } );
    return commaCount + 1; };
  const extractArgumentsPartFromFunction = fn => {
    let fnStr = fn.toString().replace(RegExp(`\\s|function|${fn.name}`, `g`), ``);
    fnStr = (fnStr.match(fnExtractArgsRE) || [fn])[0]
              .replace(valueParamsCleanupRE, ``);
    return !fnStr.startsWith(`(`) ? `(${fnStr})` : fnStr; };

  return (func, forTest = false) => {
    const params = extractArgumentsPartFromFunction(func);
    const nParams = params === `()` ? 0 : countArgumentsByBrackets(params);
    return forTest ? [params, nParams] : nParams;
  };
}```


问:
Terminate script after 30 seconds of no user input?
I am trying to create a simple Bash script that terminates after 10 seconds of waiting for user input. If the user inputs something, the timer is reset and the 10 second rule applies again. I'm using trap to ensure that the only two ways my program can exit are:

I enter "stop"

User does not input for 10 seconds

I tried using something like:

```<code>{
sleep 10s
kill $$
} &
</code>```

But after pressing Ctrl-C, it doesn't stop the program after 10s. It goes on indefinitely.

答:
You can use the time out option for read. But note this doesn't reset when a user hits a key, only when they press enter to finish their input.

```<code>read -t 10 userinput || exit 1
</code>```

If you're using set -e, you can ommit || exit 1.

read can fail for other reasons, so you can test for a timeout specifically. Timeout error code is anything greater than 128.

```<code>read -t 10 userinput || { (($?>128)) && exit 1; }
</code>```

Or

```<code>if ! read -t 10 userinput && (($? > 128)); then
    echo 'you timed out' >&2
    exit 1
fi
</code>```

If read fails, you probably want to exit anyway. But testing for a timeout error code allows you to print a relevant error message.

Body:
I am trying to create a simple Bash script that terminates after 10 seconds of waiting for user input. If the user inputs something, the timer is reset and the 10 second rule applies again. I'm using trap to ensure that the only two ways my program can exit are:

I enter "stop"

User does not input for 10 seconds

I tried using something like:

{
sleep 10s
kill $$
} &

But after pressing Ctrl-C, it doesn't stop the program after 10s. It goes on indefinitely.

Body:
You can use the time out option for read. But note this doesn't reset when a user hits a key, only when they press enter to finish their input.

read -t 10 userinput || exit 1

If you're using set -e, you can ommit || exit 1.

read can fail for other reasons, so you can test for a timeout specifically. Timeout error code is anything greater than 128.

read -t 10 userinput || { (($?>128)) && exit 1; }

Or

if ! read -t 10 userinput && (($? > 128)); then
    echo 'you timed out' >&2
    exit 1
fi

If read fails, you probably want to exit anyway. But testing for a timeout error code allows you to print a relevant error message.


问:
Keycloak OTP for read only federated users
I have implemented a custom user storage provider for federating users from our database.

I want to manage OTP for those users via keycloak, when I set the OTP to required in the flow and Configure OTP as required action the otp form is shown after federated user login, but when I try to setup the OTP I receive the error user is read only for this update.

How can I allow read only federated users to allow OTP configuration via keycloak?

```<code>2022-01-31 17:00:12,704 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-669) Uncaught server error: org.keycloak.storage.ReadOnlyException: user is read only for this update
at org.keycloak.keycloak-server-spi@15.1.1//org.keycloak.storage.adapter.AbstractUserAdapter.removeRequiredAction(AbstractUserAdapter.java:77)
at org.keycloak.keycloak-services@15.1.1//org.keycloak.services.resources.LoginActionsService.processRequireAction(LoginActionsService.java:1044)
at org.keycloak.keycloak-services@15.1.1//org.keycloak.services.resources.LoginActionsService.requiredActionPOST(LoginActionsService.java:967)
</code>```

the user adapter is

public class UserAdminAdapter extends AbstractUserAdapter {

  private final CustomUser user;

  public UserAdminAdapter(
    KeycloakSession session,
    RealmModel realm,
    ComponentModel storageProviderModel,
    CustomUser user) {
        super(session, realm, storageProviderModel);
        this.user = user;
  }

  @Override
  public String getUsername() {
    return user.getUsername();
  }

  @Override
  public Stream<String> getAttributeStream(String name) {
        Map<String, List<String>> attributes = getAttributes();
        return (attributes.containsKey(name)) ? attributes.get(name).stream() : Stream.empty();
  }

  @Override
  protected Set<GroupModel> getGroupsInternal() {
    if (user.getGroups() != null) {
        return user.getGroups().stream().map(UserGroupModel::new).collect(Collectors.toSet());
    }
    return new HashSet<>();
  }

  @Override
  protected Set<RoleModel> getRoleMappingsInternal() {
    if (user.getRoles() != null) {
        return user.getRoles().stream().map(roleName -> new UserRoleModel(roleName, realm)).collect(Collectors.toSet());
    }
    return new HashSet<>();
  }

  @Override
  public boolean isEnabled() {
    return user.isEnabled();
  }

  @Override
  public String getId() {
    return StorageId.keycloakId(storageProviderModel, user.getUserId() + "");
  }

  @Override
  public String getFirstAttribute(String name) {
    List<String> list = getAttributes().getOrDefault(name, Collections.emptyList());
    return list.isEmpty() ? null : list.get(0);
  }

  @Override
  public Map<String, List<String>> getAttributes() {
    MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
    attributes.add(UserModel.USERNAME, getUsername());
    attributes.add(UserModel.EMAIL, getEmail());
    attributes.add(UserModel.FIRST_NAME, getFirstName());
    attributes.add(UserModel.LAST_NAME, getLastName());
    attributes.addAll(user.getAttributes());
    return attributes;
  }

  @Override
  public String getFirstName() {
    return user.getFirstName();
  }

  @Override
  public String getLastName() {
    return user.getLastName();
  }

  @Override
  public String getEmail() {
    return user.getEmail();
  }
}
```

答: The reason is that in your UserAdminAdapter class, you have not implemented the removeRequiredAction and addRequiredAction methods. The message you're receiving is from the default implementation provided by the base class. You should either implement these methods yourself and store the required actions in your underlying storage, OR consider extending your class from AbstractUserAdapterFederatedStorage instead which delegates all such functionalities to the internal Keycloak implementation.

Body:
I have implemented a custom user storage provider for federating users from our database.

I want to manage OTP for those users via keycloak, when I set the OTP to required in the flow and Configure OTP as required action the otp form is shown after federated user login, but when I try to setup the OTP I receive the error user is read only for this update.

How can I allow read only federated users to allow OTP configuration via keycloak?

2022-01-31 17:00:12,704 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-669) Uncaught server error: org.keycloak.storage.ReadOnlyException: user is read only for this update
at org.keycloak.keycloak-server-spi@15.1.1//org.keycloak.storage.adapter.AbstractUserAdapter.removeRequiredAction(AbstractUserAdapter.java:77)
at org.keycloak.keycloak-services@15.1.1//org.keycloak.services.resources.LoginActionsService.processRequireAction(LoginActionsService.java:1044)
at org.keycloak.keycloak-services@15.1.1//org.keycloak.services.resources.LoginActionsService.requiredActionPOST(LoginActionsService.java:967)

the user adapter is

public class UserAdminAdapter extends AbstractUserAdapter {

  private final CustomUser user;

  public UserAdminAdapter(
    KeycloakSession session,
    RealmModel realm,
    ComponentModel storageProviderModel,
    CustomUser user) {
        super(session, realm, storageProviderModel);
        this.user = user;
  }

  @Override
  public String getUsername() {
    return user.getUsername();
  }

  @Override
  public Stream<String> getAttributeStream(String name) {
        Map<String, List<String>> attributes = getAttributes();
        return (attributes.containsKey(name)) ? attributes.get(name).stream() : Stream.empty();
  }

  @Override
  protected Set<GroupModel> getGroupsInternal() {
    if (user.getGroups() != null) {
        return user.getGroups().stream().map(UserGroupModel::new).collect(Collectors.toSet());
    }
    return new HashSet<>();
  }

  @Override
  protected Set<RoleModel> getRoleMappingsInternal() {
    if (user.getRoles() != null) {
        return user.getRoles().stream().map(roleName -> new UserRoleModel(roleName, realm)).collect(Collectors.toSet());
    }
    return new HashSet<>();
  }

  @Override
  public boolean isEnabled() {
    return user.isEnabled();
  }

  @Override
  public String getId() {
    return StorageId.keycloakId(storageProviderModel, user.getUserId() + "");
  }

  @Override
  public String getFirstAttribute(String name) {
    List<String> list = getAttributes().getOrDefault(name, Collections.emptyList());
    return list.isEmpty() ? null : list.get(0);
  }

  @Override
  public Map<String, List<String>> getAttributes() {
    MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
    attributes.add(UserModel.USERNAME, getUsername());
    attributes.add(UserModel.EMAIL, getEmail());
    attributes.add(UserModel.FIRST_NAME, getFirstName());
    attributes.add(UserModel.LAST_NAME, getLastName());
    attributes.addAll(user.getAttributes());
    return attributes;
  }

  @Override
  public String getFirstName() {
    return user.getFirstName();
  }

  @Override
  public String getLastName() {
    return user.getLastName();
  }

  @Override
  public String getEmail() {
    return user.getEmail();
  }
}


问:
What's the difference between "myVar.constructor" and "typeof myVar"?
What is the difference between...

```<code>if(myVar.constructor == String)
</code>```

and

```<code>if(typeof myVar == "string")
</code>```

答:
The expression myVar.constructor just returns the value of the member "constructor".  It's completely possible and legal for a given object to have a constructor which points to string (or anything else).  For example

```<code>function Apple() {}
var x = new Apple();
x.constructor = String
if (x.constructor == String) {
  // True
}
</code>```

Using the typeof operator though provides the information you're looking for

```<code>if (typeof myVar == 'string') {
  // It's a string
}
</code>```

Body:
What is the difference between...

if(myVar.constructor == String)

and

if(typeof myVar == "string")

Body:
The expression myVar.constructor just returns the value of the member "constructor".  It's completely possible and legal for a given object to have a constructor which points to string (or anything else).  For example

function Apple() {}
var x = new Apple();
x.constructor = String
if (x.constructor == String) {
  // True
}

Using the typeof operator though provides the information you're looking for

if (typeof myVar == 'string') {
  // It's a string
}


问:
Stop setInterval function with a button
User have to see all bets in their dashboard so I created a a function every 2secs that loads all players bet 1 and players bet 2. I want to bind the function to a button so it will STOP running continuously when betting is close and waiting for the outcome and START the function again when the betting is open.

Here's my code:

```<code>$(document).ready(function(){
 $("#load_bets1").load("loadbet1.php");
    setInterval(function() {
        $("#load_bets1").load("loadbet1.php");
    }, 2000);
});

$(document).ready(function(){
 $("#load_bets2").load("loadbet2.php");
    setInterval(function() {
        $("#load_bets2").load("loadbet2.php");
    }, 2000);
});
</code>```

答:
setInterval returns an ID that can be passed to clearInterval to stop it.

Example to stop an interval after some time:

let i = 0;
const intervalID = setInterval(() => console.log(i++), 100);
setTimeout(() => clearInterval(intervalID), 1000);
```

See also the examples at https://developer.mozilla.org/en-US/docs/Web/API/setInterval#examples.

Title: Stop setInterval function with a button

Body:
User have to see all bets in their dashboard so I created a a function every 2secs that loads all players bet 1 and players bet 2. I want to bind the function to a button so it will STOP running continuously when betting is close and waiting for the outcome and START the function again when the betting is open.

Here's my code:

$(document).ready(function(){
 $("#load_bets1").load("loadbet1.php");
    setInterval(function() {
        $("#load_bets1").load("loadbet1.php");
    }, 2000);
});

$(document).ready(function(){
 $("#load_bets2").load("loadbet2.php");
    setInterval(function() {
        $("#load_bets2").load("loadbet2.php");
    }, 2000);
});

Body:
setInterval returns an ID that can be passed to clearInterval to stop it.

Example to stop an interval after some time:

let i = 0;
const intervalID = setInterval(() => console.log(i++), 100);
setTimeout(() => clearInterval(intervalID), 1000);

See also the examples at https://developer.mozilla.org/en-US/docs/Web/API/setInterval#examples.


问:
how to keep session enabled in firebase/auth js?
When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work.
This is my code</p>
```<code>const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}
</code>```

答:
Implement redux w/ toolkit (easiest way to set up redux IMO) - you can follow this tutorial

Important tip is to update the state with the onAuthStateChanged method available in the firebase package, instead of changing it directly during the sign-in/ sign-up function

Body:
When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work.
This is my code

const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}


问:
How to make this bubble type widget in flutter which depicts a certain message on tap?
I need help with this widget .

答: Try this package popover 0.2.6+3</p>

Body: I need help with this widget .

Body: Try this package popover 0.2.6+3


问:
JavaScript print info of an array inside an array of object in a html section
I have this array of object that contains info string number array

I'm trying to print all the info of  touristActivities inside an html

I want to print first the information of stepOne in a section tag then the information of stepTwo in another section tag

touristActivities array can contain more the these two steps

my code below i can only print the info without the section

How can i print the info of each steps inside a different section for each step

example:

```<code><section class="stepOne">
all step One information
</section>

<section class="stepTwo">
all step Two information
</section>
</code>```

const database = [{
    sectorId: 1,
    sectorName: "السياحة",
    sectorIcon: "icon-1.png",
    sectorN: "tourism",
    licenseTitle: ["إصدار ترخيص مرافق الإيواء السياحي", "الأنشطة السياحية"],
    licenseDesc: ["تقديم خدمات الترخيص لنشاط الفنادق والشقق المخدومة والمخيمات  والنزل وفنادق الكبائن والشاليهات.", "تقديم خدمات الترخيص لوكالات السياحة والسفر وتنظيم الرحلات السياحية وحجز وحدات الإيواء السياحي وتسويقها."],
    licenseNum: ["7960", "7961"],
    touristActivities: [
        stepOne = {
            subTitle: "إصدار رخصة استثمار للمستثمر الأجنبي",
            description: "إصدار رخصة استثمار لغير السعوديين لمزاولة الأنشطة التجارية بما يتوافق مع الاشتراطات والمتطلبات المحددة.",
            },
       stepTwo = {
           subTitle: "إصدار سجل تجاري",
           description: "وثيقة قانونية تحتوي على بيانات التاجر والنشاط التابع له تمكنه من مزاولة نشاطه بتصريح رسمي وفق الاشتراطات والمتطلبات المحددة.",
                }
        ]
},
{
    sectorId: 2,
},
];

let title = document.querySelector(".title");
let rightSection = document.querySelector('.right');

function getInfo(id) {
for (let i = 0; i < database.length; i++) {
    if (database[i].sectorId === parseInt(id)) {
        title.innerHTML += `<img src='img/${database[i].sectorIcon}' alt='image'>`;
        title.innerHTML += `<h2>${name}</h2>`;
        for (let j = 0; j < database[i].touristActivities.length; j++) {
            subTitle(database[i].touristActivities[j].subTitle);
            description(database[i].touristActivities[j].description);
        }
    }
}
}
getInfo(1);

function subTitle(st) {
let subTitle = `

${st}

`;
rightSection.innerHTML += subTitle;
}

function description(desc) {
    let description = `

وصف الخطوة

${desc}

    `;
    rightSection.innerHTML += description;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div class="container">
            <div class="title">

            </div>
            <div class="right">
                <div class="subTitle">

                </div>

            </div>
            <div class="left"></div>
        </div></code>```

答:
Your code is not valid syntax.

Step one is inside an array and using '='

```<code>[step1 = {}, step2 = {}]
</code>```

You will need to restructure it. Perhaps by adding a stepId field so you can mix it with other types.

```<code>[{stepId:'step1'},{stepId:'step2'},{not:'astep'}]
</code>```
```<code>database.forEach(sector => {
  const steps = sector.touristActivities.filter(activity=>activity.stepId !== undefined)
  // Now use your `steps` to generate your sections.
  steps.forEach(step=>{
    const ele = document.createElement('section')
    ele.className = step.stepId
    ele.innerText = step.subTitle
    // and so on
  })
})
</code>```

Body:
I have this array of object that contains info string number array

I'm trying to print all the info of  touristActivities inside an html

I want to print first the information of stepOne in a section tag then the information of stepTwo in another section tag

touristActivities array can contain more the these two steps

my code below i can only print the info without the section

How can i print the info of each steps inside a different section for each step

example:

all step One information

all step Two information

const database = [{
    sectorId: 1,
    sectorName: "السياحة",
    sectorIcon: "icon-1.png",
    sectorN: "tourism",
    licenseTitle: ["إصدار ترخيص مرافق الإيواء السياحي", "الأنشطة السياحية"],
    licenseDesc: ["تقديم خدمات الترخيص لنشاط الفنادق والشقق المخدومة والمخيمات  والنزل وفنادق الكبائن والشاليهات.", "تقديم خدمات الترخيص لوكالات السياحة والسفر وتنظيم الرحلات السياحية وحجز وحدات الإيواء السياحي وتسويقها."],
    licenseNum: ["7960", "7961"],
    touristActivities: [
        stepOne = {
            subTitle: "إصدار رخصة استثمار للمستثمر الأجنبي",
            description: "إصدار رخصة استثمار لغير السعوديين لمزاولة الأنشطة التجارية بما يتوافق مع الاشتراطات والمتطلبات المحددة.",
            },
       stepTwo = {
           subTitle: "إصدار سجل تجاري",
           description: "وثيقة قانونية تحتوي على بيانات التاجر والنشاط التابع له تمكنه من مزاولة نشاطه بتصريح رسمي وفق الاشتراطات والمتطلبات المحددة.",
                }
        ]
},
{
    sectorId: 2,
},
];

let title = document.querySelector(".title");
let rightSection = document.querySelector('.right');

function getInfo(id) {
for (let i = 0; i < database.length; i++) {
    if (database[i].sectorId === parseInt(id)) {
        title.innerHTML += `<img src='img/${database[i].sectorIcon}' alt='image'>`;
        title.innerHTML += `<h2>${name}</h2>`;
        for (let j = 0; j < database[i].touristActivities.length; j++) {
            subTitle(database[i].touristActivities[j].subTitle);
            description(database[i].touristActivities[j].description);
        }
    }
}
}
getInfo(1);

function subTitle(st) {
let subTitle = `

${st}

`;
rightSection.innerHTML += subTitle;
}

function description(desc) {
    let description = `

وصف الخطوة

${desc}

    `;
    rightSection.innerHTML += description;
}

Body:
Your code is not valid syntax.

Step one is inside an array and using '='

[step1 = {}, step2 = {}]

You will need to restructure it. Perhaps by adding a stepId field so you can mix it with other types.

[{stepId:'step1'},{stepId:'step2'},{not:'astep'}]

database.forEach(sector => {
  const steps = sector.touristActivities.filter(activity=>activity.stepId !== undefined)
  // Now use your `steps` to generate your sections.
  steps.forEach(step=>{
    const ele = document.createElement('section')
    ele.className = step.stepId
    ele.innerText = step.subTitle
    // and so on
  })
})


答:
The thing is your functions directly modify the HTML. It is tightly coupled. So you lose quite a bit of control over the output. With your code the sequence of these function calls is important because the output will depend on the calls. E.g. first description() must be followed by time(). Now you want to wrap all this, but you have already written it to the DOM.

The sections span the content you want to generate from each step. Therefore, they have to wrap everything inside the for-loop there.

Instead of directly modifying the DOM, write the output of your functions to an array buffer. After the loop you will attach the whole content that you have created to the section element.

So you return the HTML from your functions, store it into the array buffer and once you looped over the section, you can combine/add the content with buffer.join('') and close it.

This way, you split the generators from the assembly code.

Here is a working example:

const database = [{
    sectorId: 1,
    sectorName: "السياحة",
    sectorIcon: "icon-1.png",
    sectorN: "tourism",
    licenseTitle: ["إصدار ترخيص مرافق الإيواء السياحي", "الأنشطة السياحية"],
    licenseDesc: ["تقديم خدمات الترخيص لنشاط الفنادق والشقق المخدومة والمخيمات  والنزل وفنادق الكبائن والشاليهات.", "تقديم خدمات الترخيص لوكالات السياحة والسفر وتنظيم الرحلات السياحية وحجز وحدات الإيواء السياحي وتسويقها."],
    licenseNum: ["7960", "7961"],
    touristActivities: [
      stepOne = {
        subTitle: "إصدار رخصة استثمار للمستثمر الأجنبي",
        description: "إصدار رخصة استثمار لغير السعوديين لمزاولة الأنشطة التجارية بما يتوافق مع الاشتراطات والمتطلبات المحددة.",
        duration: "يوم واحد",
        money: "٢٠٠٠",
        year: "سنة - ٥",
        concernedParty: ["وزارة الاستثمار"],
        concernedPartyLogo: ["thumbnail_2.png"],
        address: "",
        phone: "١٩٩١١",
        website: "https://hrsd.gov.sa/ar",
        mail: "info@hrsd.gov.sa",
        requirements: ["ألا يكون النشاط الاستثماري ضمن قائمة الأنشطة المستثناة من الاستثمار الأجنبي.", "أن تكون مواصفات المنتج مطابقة للمواصفات السعودية أو الخليجية أو الدولية.", "ألا يكون طالب الترخيص قد صدرت ضده قرارات نهائية بسبب مخالفات لأحكام النظام داخل المملكة أو خارجه.", "أن يلتزم طالب الترخيص بالشروط والتعهدات الملحقة بنموذج طلب الترخيص الاستثماري.", "أن يحقق منح الترخيص أهداف الاستثمار وتطبيق هذه الشروط والضوابط على طلبات تجديد الترخيص."],
        needs: [
          "صورة السجل التجاري وعقد التأسيس للمنشاة في بلدها مصدقة من الجهات المختصة والسفارة السعودية.",
          "صورة من حجز الاسم التجاري من وزارة التجارة.",
          "مشروع عقد تأسيس شركة ذات مسؤولية محدودة صورة من.",
          "مشروع عقد التأسيس والنظام الأساسي للشركة المساهمة صورة من.",
          "إرفاق قرار الشركاء رغبتهم في الاستثمار في المملكة موضحاً به أسماء الشركاء ورأس المال ونسبة ملكية كل شريك والمركز الرئيس للمنشأة وطبيعة النشاط.",
          "تعيين المدير العام وتحديد صلاحياته مصدقًا من الجهات المختصة والسفارة السعودية.",
          "صورة من جواز السفر للمدير العام.",
          "صورة من الهوية الوطنية وبطاقة العائلة إذا كان أحد الشركاء يتمتع بالجنسية السعودية.",
          "صورة من السجل التجاري لإثبات المهنة أو مستخرج من الأحوال المدنية.",
          "تقديم موافقة مبدئية من الوزارات أو الهيئات المعنية إن كان النشاط يتطلب موافقة.",
          "تقديم خطة عمل تفصيلية.",
          "تقديم ميزانية للمنشاة طالبة الترخيص من خارج المملكة لفترة لا تقل عن 3 سنوات توضح سلامة الوضع المالي معتمدة من مكتب محاسبي ومصدقة من الجهاز المعني ومن سفارة المملكة.",
          "إثبات القدرة المالية على الاستثمار بما يتناسب مع رأس مال المشروع وحصة كل شريك وبما يتناسب مع خطة العمل المقدمة."
        ],
        linkTitle: "اضغط لاصدار الرخصة عبر المركز السعودي للأعمال",
        link: "https://www.ncc.gov.sa/ar/Pages/default.aspx",
      },
      stepTwo = {
        subTitle: "إصدار سجل تجاري",
        description: "وثيقة قانونية تحتوي على بيانات التاجر والنشاط التابع له تمكنه من مزاولة نشاطه بتصريح رسمي وفق الاشتراطات والمتطلبات المحددة.",
        duration: "حسب التصنيف",
        money: "حسب التصنيف",
        year: "",
        concernedParty: ["وزارة التجارة"],
        concernedPartyLogo: ["thumbnail_1.png"],
        address: "",
        phone: "١٩٩١١",
        website: "https://hrsd.gov.sa/ar",
        mail: "info@hrsd.gov.sa",
        requirements: ["ألا يقل العمر عن 18 سنة.", "ألا يكون موظف حكومي.", "ألا يقل رأس المال عن 5000 ر.س.", "لا يشترط إصدار سجل فرعي إذا كان بنفس النشاط وبنفس المنطقة الإدارية."],
        needs: [
          "تقديم طلب لتأسيس الشركة إلكترونيًا عبر بوابة أعمال الشركات. aamal.sa",
          "خطاب موقع من المؤسسين بتأسيس الشركة.",
          "صورة بطاقة الأحوال.",
          "ألا يقل رأس المال عن 500,000 ريال.",
          "صورة من مشروع نظام الشركة الأساسي وعقد تأسيس الشركة.",
          "مشروع نظام الشركة الأساسي وعقد تأسيس الشركة.",
          "خطاب من الشركة بإصدار فرع شركة يتضمن مدينة الفرع ومدير الفرع مصدق من الغرفة التجارية.",
          "التأكيد على المستثمر بالإيداع بعد انتهاء السنة المالية للشركة."
        ],
        linkTitle: "اضغط لاصدار الرخصة عبر المركز السعودي للأعمال",
        link: "https://www.ncc.gov.sa/ar/Pages/default.aspx",
      }

    ]
  },
  {
    sectorId: 2,
    sectorName: "التعليم",
    sectorIcon: "icon-2.png",
    sectorN: "education",
    licenseTitle: ["إصدار ترخيص مدرسة أهلية بمنهج وطني أو عالمي", "إصدار ترخيص مركز الإشراف والتدريب التربوي الأهلي", "إصدار ترخيص معاهد اللغات", "إصدار ترخيص منشأة تدريبية"],
    licenseDesc: [],
    licenseNum: ["7950", "7951"]
  },
];

let title = document.querySelector(".title");
let subTitle = document.querySelector(".subTitle");
let rightSection = document.querySelector('.right');

function getInfo(id) {
  for (let i = 0; i < database.length; i++) {
    if (database[i].sectorId === parseInt(id)) {
      title.innerHTML += `<img src='img/${database[i].sectorIcon}' alt='image'>`;
      title.innerHTML += `<h2>${name}</h2>`;

      const activities = database[i].touristActivities;
      const contentBuffer = [];

      for (let activity of activities) {
        subTitle.innerHTML += `<h3>${activity.subTitle}</h3>`;
        contentBuffer.push('
');
        contentBuffer.push(description(activity.description));
        contentBuffer.push(time(activity.duration));
        contentBuffer.push(money(activity.money, activity.year));
        contentBuffer.push(concerned(activity.concernedParty, activity.concernedPartyLogo, activity.address, activity.phone, activity.website, activity.mail));
        contentBuffer.push(requirements(activity.requirements));
        contentBuffer.push(needs(activity.needs));
        contentBuffer.push(link(activity.linkTitle, activity.link));
        contentBuffer.push('
');
      }

      rightSection.innerHTML = contentBuffer.join('');
    }
  }
}
getInfo(1);

function description(desc) {
  return `

وصف الخطوة

${desc}

    `;
}

function time(timeinfo) {
  return `

المدة الزمنية

${timeinfo}

    `;
}

function money(m, y) {
  return `

المقابل المالي

${m} ر.س / ${y} سنوات كحد أقصى

    `;
}

function concerned(a, b, m, p, w, e) {
  return `

الجهة المعنية

${a}

العنوان

${m}

الهاتف

                            مركز الاتصال الموحد s${p}

المنصة الإلكترونية

                            ${w}

البريد الإلكتروني

                            ${e}

    `;
}

function requirements(dt) {
  return `

الاشتراطات

    ${dt.map(rq =>`

    <input type="checkbox" value="${rq}">

${rq}

`).join("")}

`;
}

function needs(dt) {
  return `

المتطلبات

    ${dt.map(nd =>`

    <input type="checkbox" value="${nd}">

${nd}

`).join("")}

`;
}

function link(lt, li) {
  return `

احصل على رخصتك عبر منصة الأعمال

    ${lt}

`;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="title">

  </div>
  <div class="right">
    <div class="subTitle">

    </div>

  </div>
  <div class="left"></div>
</div></code>```

Title: JavaScript print info of an array inside an array of object in a html section

Body:
The thing is your functions directly modify the HTML. It is tightly coupled. So you lose quite a bit of control over the output. With your code the sequence of these function calls is important because the output will depend on the calls. E.g. first description() must be followed by time(). Now you want to wrap all this, but you have already written it to the DOM.

The sections span the content you want to generate from each step. Therefore, they have to wrap everything inside the for-loop there.

Instead of directly modifying the DOM, write the output of your functions to an array buffer. After the loop you will attach the whole content that you have created to the section element.

So you return the HTML from your functions, store it into the array buffer and once you looped over the section, you can combine/add the content with buffer.join('') and close it.

This way, you split the generators from the assembly code.

Here is a working example:

const database = [{
    sectorId: 1,
    sectorName: "السياحة",
    sectorIcon: "icon-1.png",
    sectorN: "tourism",
    licenseTitle: ["إصدار ترخيص مرافق الإيواء السياحي", "الأنشطة السياحية"],
    licenseDesc: ["تقديم خدمات الترخيص لنشاط الفنادق والشقق المخدومة والمخيمات  والنزل وفنادق الكبائن والشاليهات.", "تقديم خدمات الترخيص لوكالات السياحة والسفر وتنظيم الرحلات السياحية وحجز وحدات الإيواء السياحي وتسويقها."],
    licenseNum: ["7960", "7961"],
    touristActivities: [
      stepOne = {
        subTitle: "إصدار رخصة استثمار للمستثمر الأجنبي",
        description: "إصدار رخصة استثمار لغير السعوديين لمزاولة الأنشطة التجارية بما يتوافق مع الاشتراطات والمتطلبات المحددة.",
        duration: "يوم واحد",
        money: "٢٠٠٠",
        year: "سنة - ٥",
        concernedParty: ["وزارة الاستثمار"],
        concernedPartyLogo: ["thumbnail_2.png"],
        address: "<iframe src='https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3622.702432314261!2d46.721452214877665!3d24.771389754922634!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3e2efd91f30ee055%3A0x13c696d4f4a80ec3!2sHRSD%20Ministry!5e0!3m2!1sen!2slb!4v1639075198016!5m2!1sen!2slb' width='100%' height='180' style='border:0;' allowfullscreen='' loading='lazy'></iframe>",
        phone: "١٩٩١١",
        website: "https://hrsd.gov.sa/ar",
        mail: "info@hrsd.gov.sa",
        requirements: ["ألا يكون النشاط الاستثماري ضمن قائمة الأنشطة المستثناة من الاستثمار الأجنبي.", "أن تكون مواصفات المنتج مطابقة للمواصفات السعودية أو الخليجية أو الدولية.", "ألا يكون طالب الترخيص قد صدرت ضده قرارات نهائية بسبب مخالفات لأحكام النظام داخل المملكة أو خارجه.", "أن يلتزم طالب الترخيص بالشروط والتعهدات الملحقة بنموذج طلب الترخيص الاستثماري.", "أن يحقق منح الترخيص أهداف الاستثمار وتطبيق هذه الشروط والضوابط على طلبات تجديد الترخيص."],
        needs: [
          "صورة السجل التجاري وعقد التأسيس للمنشاة في بلدها مصدقة من الجهات المختصة والسفارة السعودية.",
          "صورة من حجز الاسم التجاري من وزارة التجارة.",
          "مشروع عقد تأسيس شركة ذات مسؤولية محدودة صورة من.",
          "مشروع عقد التأسيس والنظام الأساسي للشركة المساهمة صورة من.",
          "إرفاق قرار الشركاء رغبتهم في الاستثمار في المملكة موضحاً به أسماء الشركاء ورأس المال ونسبة ملكية كل شريك والمركز الرئيس للمنشأة وطبيعة النشاط.",
          "تعيين المدير العام وتحديد صلاحياته مصدقًا من الجهات المختصة والسفارة السعودية.",
          "صورة من جواز السفر للمدير العام.",
          "صورة من الهوية الوطنية وبطاقة العائلة إذا كان أحد الشركاء يتمتع بالجنسية السعودية.",
          "صورة من السجل التجاري لإثبات المهنة أو مستخرج من الأحوال المدنية.",
          "تقديم موافقة مبدئية من الوزارات أو الهيئات المعنية إن كان النشاط يتطلب موافقة.",
          "تقديم خطة عمل تفصيلية.",
          "تقديم ميزانية للمنشاة طالبة الترخيص من خارج المملكة لفترة لا تقل عن 3 سنوات توضح سلامة الوضع المالي معتمدة من مكتب محاسبي ومصدقة من الجهاز المعني ومن سفارة المملكة.",
          "إثبات القدرة المالية على الاستثمار بما يتناسب مع رأس مال المشروع وحصة كل شريك وبما يتناسب مع خطة العمل المقدمة."
        ],
        linkTitle: "اضغط لاصدار الرخصة عبر المركز السعودي للأعمال",
        link: "https://www.ncc.gov.sa/ar/Pages/default.aspx",
      },
      stepTwo = {
        subTitle: "إصدار سجل تجاري",
        description: "وثيقة قانونية تحتوي على بيانات التاجر والنشاط التابع له تمكنه من مزاولة نشاطه بتصريح رسمي وفق الاشتراطات والمتطلبات المحددة.",
        duration: "حسب التصنيف",
        money: "حسب التصنيف",
        year: "",
        concernedParty: ["وزارة التجارة"],
        concernedPartyLogo: ["thumbnail_1.png"],
        address: "<iframe src='https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3622.702432314261!2d46.721452214877665!3d24.771389754922634!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3e2efd91f30ee055%3A0x13c696d4f4a80ec3!2sHRSD%20Ministry!5e0!3m2!1sen!2slb!4v1639075198016!5m2!1sen!2slb' width='100%' height='180' style='border:0;' allowfullscreen='' loading='lazy'></iframe>",
        phone: "١٩٩١١",
        website: "https://hrsd.gov.sa/ar",
        mail: "info@hrsd.gov.sa",
        requirements: ["ألا يقل العمر عن 18 سنة.", "ألا يكون موظف حكومي.", "ألا يقل رأس المال عن 5000 ر.س.", "لا يشترط إصدار سجل فرعي إذا كان بنفس النشاط وبنفس المنطقة الإدارية."],
        needs: [
          "تقديم طلب لتأسيس الشركة إلكترونيًا عبر بوابة أعمال الشركات. aamal.sa",
          "خطاب موقع من المؤسسين بتأسيس الشركة.",
          "صورة بطاقة الأحوال.",
          "ألا يقل رأس المال عن 500,000 ريال.",
          "صورة من مشروع نظام الشركة الأساسي وعقد تأسيس الشركة.",
          "مشروع نظام الشركة الأساسي وعقد تأسيس الشركة.",
          "خطاب من الشركة بإصدار فرع شركة يتضمن مدينة الفرع ومدير الفرع مصدق من الغرفة التجارية.",
          "التأكيد على المستثمر بالإيداع بعد انتهاء السنة المالية للشركة."
        ],
        linkTitle: "اضغط لاصدار الرخصة عبر المركز السعودي للأعمال",
        link: "https://www.ncc.gov.sa/ar/Pages/default.aspx",
      }

    ]
  },
  {
    sectorId: 2,
    sectorName: "التعليم",
    sectorIcon: "icon-2.png",
    sectorN: "education",
    licenseTitle: ["إصدار ترخيص مدرسة أهلية بمنهج وطني أو عالمي", "إصدار ترخيص مركز الإشراف والتدريب التربوي الأهلي", "إصدار ترخيص معاهد اللغات", "إصدار ترخيص منشأة تدريبية"],
    licenseDesc: [],
    licenseNum: ["7950", "7951"]
  },
];

let title = document.querySelector(".title");
let subTitle = document.querySelector(".subTitle");
let rightSection = document.querySelector('.right');

function getInfo(id) {
  for (let i = 0; i < database.length; i++) {
    if (database[i].sectorId === parseInt(id)) {
      title.innerHTML += `<img src='img/${database[i].sectorIcon}' alt='image'>`;
      title.innerHTML += `<h2>${name}</h2>`;

      const activities = database[i].touristActivities;
      const contentBuffer = [];

      for (let activity of activities) {
        subTitle.innerHTML += `<h3>${activity.subTitle}</h3>`;
        contentBuffer.push('<section>');
        contentBuffer.push(description(activity.description));
        contentBuffer.push(time(activity.duration));
        contentBuffer.push(money(activity.money, activity.year));
        contentBuffer.push(concerned(activity.concernedParty, activity.concernedPartyLogo, activity.address, activity.phone, activity.website, activity.mail));
        contentBuffer.push(requirements(activity.requirements));
        contentBuffer.push(needs(activity.needs));
        contentBuffer.push(link(activity.linkTitle, activity.link));
        contentBuffer.push('</section>');
      }

      rightSection.innerHTML = contentBuffer.join('');
    }
  }
}
getInfo(1);

function description(desc) {
  return `
    <div class="discription">
    <div class="description-inner parent">
        <div class="descText">
            <img src="img/description.png" alt="desc">
            <h4>وصف الخطوة</h4>
        </div>
        <i class="fas fa-angle-down"></i>
    </div>
    <div class="descInfo toggle">
    <p>${desc}</p>
    </div>
</div>
    `;
}

function time(timeinfo) {
  return `
    <div class="time">
    <div class="time-inner">
        <div class="timeText">
            <img src="img/time.png" alt="time">
            <h4>المدة الزمنية</h4>
        </div>
        <img src="img/arrow.png" alt="arrow">
        <p class="text">${timeinfo}</p>
    </div>
</div>
    `;
}

function money(m, y) {
  return `
    <div class="money">
    <div class="money-inner">
        <div class="moneyText">
            <img src="img/money.png" alt="money">
            <h4>المقابل المالي</h4>
        </div>
        <img src="img/arrow.png" alt="arrow">
        <p class="text"><span>${m}</span> ر.س / <span>${y}</span> سنوات كحد أقصى</p>
    </div>
</div>
    `;
}

function concerned(a, b, m, p, w, e) {
  return `
    <div class="concerned">
    <div class="concerned-inner parent">
        <div class="concernedText">
            <img src="img/jeha.png" alt="jeha">
            <h4>الجهة المعنية</h4>
        </div>
        <i class="fas fa-angle-down"></i>
        </div>
        <div class="concernedInfo toggle">
            <div class="concernedInfoContent">
                <div class="box">
                    <img src="img/${b}" alt="logo" class="logo">
                    <h4 class="logoTitle">${a}</h4>
                    <p></p>
                </div>
                <div class="box">
                    <div class="locationTitle">
                        <img src="img/location.png" alt="location">
                        <h4>العنوان</h4>
                        </div>
                        <div class="map">${m}</div>

                </div>
                <div class="box">
                    <div class="phone">
                        <img src="img/phone.png" alt="phone">
                        <div class="phoneText">
                            <h4>الهاتف</h4>
                            <a href="${p}" target="_blank">مركز الاتصال الموحد s${p}</a>
                        </div>
                    </div>
                    <div class="website">
                        <img src="img/almanasa-icon.png" alt="web">
                        <div class="websiteText">
                            <h4>المنصة الإلكترونية</h4>
                            <a href="${w}" target="_blank">${w}</a>
                        </div>
                    </div>
                    <div class="mail">
                        <img src="img/bared.png" alt="mail">
                        <div class="webText">
                            <h4>البريد الإلكتروني</h4>
                            <a href="${e}" target="_blank">${e}</a>
                        </div>
                    </div>

                </div>
            </div>
        </div>
</div>
    `;
}

function requirements(dt) {
  return `
    <div class="requirements">
    <div class="requirements-inner parent">
        <div class="requirementsText">
            <img src="img/terms.png" alt="terms">
            <h4>الاشتراطات</h4>
        </div>
        <i class="fas fa-angle-down"></i>
    </div>
    <div class="requirementsInfo toggle">
    ${dt.map(rq =>`<div class="inner-info">
    <input type="checkbox" value="${rq}">
    <p>${rq}</p></div>`).join("")}
    </div>
</div>`;
}

function needs(dt) {
  return `
    <div class="needs">
    <div class="needs-inner parent">
        <div class="needsText">
            <img src="img/needs.png" alt="needs">
            <h4>المتطلبات</h4>
        </div>
        <i class="fas fa-angle-down"></i>
    </div>
    <div class="needsInfo toggle">
    ${dt.map(nd =>`<div class="inner-info">
    <input type="checkbox" value="${nd}">
    <p>${nd}</p></div>`).join("")}
    </div>
</div>`;
}

function link(lt, li) {
  return `
    <div class="link">
    <div class="link-inner parent">
        <div class="linkText">
            <img src="img/link.png" alt="link">
            <h4>احصل على رخصتك عبر منصة الأعمال</h4>
        </div>
        <i class="fas fa-angle-down"></i>
    </div>
    <div class="linkInfo toggle">
    <a href="${li}" target="_blank">${lt}</a>
    </div>
</div>`;
}

<div class="container">
  <div class="title">

  </div>
  <div class="right">
    <div class="subTitle">

    </div>

  </div>
  <div class="left"></div>
</div>


问:
Merging folders in different repositories
Hello i have searched around for an answer but couldn't quite find what i was looking for, feel free to link in the comments if i missed an answer somewhere.

I cloned two repositories down on my pc.

Repository 1: A collection of different components, one of which i have worked on and made changes to.

Repository 2: The updated version of the component i was working on, this has the changes from other people, but does not have my changes.

I guess i wouldn't be able to merge my repository 1 with repository 2 because of all the other components present in my repository, is there a way i can just merge a single folder containing files, with the same folder in repository 2?

答:
A simple answer to your question,

Enter the repository which has all your changes (this does not have the updated changes present in the server)

Do a git pull --rebase

Solve any merge conflicts.

Assuming that you have others changes synced to remote, and you have the correct remote URL set, in usual cases, you may choose to ignore this.


问:
Boost.Multiprecision cpp_dec_float_50 - convert into an array of bytes and back?
Similar question: to Boost.Multiprecision cpp_int - convert into an array of bytes?

But this time related to floating point values.

export_bits - doesn't seem to have an overload accepting floating point values

limbs of cpp_dec_float_50 are not made public to the outside world

Question:
Thus, how should one tackle the problem of converting such a data type, to and back from, an array of bytes?

答:
This answer is based on what @Sehe provided.

It provides facilities for both serialization and deserialization of Boost's mp::cpp_dec_float_50.

Since no_header flag does not seem to be honoured by Boost's serialization interface - around 10-long byte prefix-crap is inserted when interacting through the Serialization interface and since I have no idea what these bytes are supposed to represent - all the non-significant bytes are omitted and the number of these is stored within the least-significant byte of the serialization product. Thus, what follows should be compatible across versions of Boost, should Boost one day decide to handle the flag properly.

These stub bytes are then 'recovered' when de-serializing.

Enjoy.

```<code>using BigFloat = mp::cpp_dec_float_50;
/// <summary>
/// Produces a vector of bytes from mp::cpp_dec_float_50 (BigFloat).
/// Leading header is omitted for storage efficiency.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
std::vector<uint8_t>  CTools::BigFloatToBytes(BigFloat const& f)
{

    std::vector<unsigned char> raw;
    {
        std::ostringstream oss;
        {
            boost::archive::binary_oarchive oa(
                oss, boost::archive::no_header | boost::archive::no_codecvt | boost::archive::no_tracking);

            oa << f;
        }

        auto buf = std::move(oss).str();
        raw.assign(buf.begin(), buf.end());

        uint8_t leading0sCount = 0; //it will be stored within the last byte

        for (int i = 0; i < raw.size(); i++)
        {
            if (raw[i] == 0)
            {
                leading0sCount++;
            }
            else
                break;
        }

        raw.assign(raw.begin() + leading0sCount, raw.end());
        raw.push_back(leading0sCount);
    }

    return raw;
}

/// <summary>
/// Instantiates BigFloat (mp::cpp_dec_float_50) from a vector of bytes.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
BigFloat CTools::BytesToBigFloat(std::vector<uint8_t> v)
{
    //Local Variables and Namespaces - BEGIN
    namespace io = boost::iostreams;
    namespace ba = boost::archive;
    //Local Variables and Namespaces - END

    //Validation - BEGIN
    if (v.size() == 0)
        return 0;
    //Validation - END

    //Operational Logic - BEGIN

    //recover leading 0s/prefix
    uint8_t leading0sCount = v[v.size() - 1];
    v.pop_back();
    std::vector<uint8_t> prefix = std::vector<uint8_t>(leading0sCount);
    v.insert(v.begin(), prefix.begin(), prefix.end());

    io::stream_buffer<io::back_insert_device<std::vector<uint8_t>>> bb(v);

    BigFloat i;
    {
        std::vector<char> chars { v.begin(), v.end() };
        io::stream_buffer<io::array_source> bb(chars.data(), chars.size());
        boost::archive::binary_iarchive ia(bb, ba::no_header | ba::no_tracking | ba::no_codecvt);
        ia >> i;
    }
    //Operational Logic - END

    return i;
}
</code>```

Body:
This answer is based on what @Sehe provided.

It provides facilities for both serialization and deserialization of Boost's mp::cpp_dec_float_50.

Since no_header flag does not seem to be honoured by Boost's serialization interface - around 10-long byte prefix-crap is inserted when interacting through the Serialization interface and since I have no idea what these bytes are supposed to represent - all the non-significant bytes are omitted and the number of these is stored within the least-significant byte of the serialization product. Thus, what follows should be compatible across versions of Boost, should Boost one day decide to handle the flag properly.

These stub bytes are then 'recovered' when de-serializing.

Enjoy.

using BigFloat = mp::cpp_dec_float_50;
/// <summary>
/// Produces a vector of bytes from mp::cpp_dec_float_50 (BigFloat).
/// Leading header is omitted for storage efficiency.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
std::vector<uint8_t>  CTools::BigFloatToBytes(BigFloat const& f)
{

    std::vector<unsigned char> raw;
    {
        std::ostringstream oss;
        {
            boost::archive::binary_oarchive oa(
                oss, boost::archive::no_header | boost::archive::no_codecvt | boost::archive::no_tracking);

            oa << f;
        }

        auto buf = std::move(oss).str();
        raw.assign(buf.begin(), buf.end());

        uint8_t leading0sCount = 0; //it will be stored within the last byte

        for (int i = 0; i < raw.size(); i++)
        {
            if (raw[i] == 0)
            {
                leading0sCount++;
            }
            else
                break;
        }

        raw.assign(raw.begin() + leading0sCount, raw.end());
        raw.push_back(leading0sCount);
    }

    return raw;
}

/// <summary>
/// Instantiates BigFloat (mp::cpp_dec_float_50) from a vector of bytes.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
BigFloat CTools::BytesToBigFloat(std::vector<uint8_t> v)
{
    //Local Variables and Namespaces - BEGIN
    namespace io = boost::iostreams;
    namespace ba = boost::archive;
    //Local Variables and Namespaces - END

    //Validation - BEGIN
    if (v.size() == 0)
        return 0;
    //Validation - END

    //Operational Logic - BEGIN

    //recover leading 0s/prefix
    uint8_t leading0sCount = v[v.size() - 1];
    v.pop_back();
    std::vector<uint8_t> prefix = std::vector<uint8_t>(leading0sCount);
    v.insert(v.begin(), prefix.begin(), prefix.end());

    io::stream_buffer<io::back_insert_device<std::vector<uint8_t>>> bb(v);

    BigFloat i;
    {
        std::vector<char> chars { v.begin(), v.end() };
        io::stream_buffer<io::array_source> bb(chars.data(), chars.size());
        boost::archive::binary_iarchive ia(bb, ba::no_header | ba::no_tracking | ba::no_codecvt);
        ia >> i;
    }
    //Operational Logic - END

    return i;
}


问:
how to find AKS external ip using terraform data block
I am trying to get ingress EXTERNAL-IP in k8s. Is there any way to get the details from terraform data block. like using data "azurerm_kubernetes_cluster" or something?</p>

答:
The solution that pops into my head (which I'm sure is not the ideal one) is to use local-exec, and then use kubectl to interrogate the ingress resource in-cluster to get the IP.

Something like this (caveat: haven't tested it and I don't use AKS, so I don't know for sure if it'll work as expected)

```<code>resource "null_resource" "example1" {
  provisioner "local-exec" {
    command = "kubectl get ingress name-of-ingress-controller-lb | jq .status.loadBalancer.ingress[0].ip"
  }
}
</code>```

Body:
The solution that pops into my head (which I'm sure is not the ideal one) is to use local-exec, and then use kubectl to interrogate the ingress resource in-cluster to get the IP.

Something like this (caveat: haven't tested it and I don't use AKS, so I don't know for sure if it'll work as expected)

resource "null_resource" "example1" {
  provisioner "local-exec" {
    command = "kubectl get ingress name-of-ingress-controller-lb | jq .status.loadBalancer.ingress[0].ip"
  }
}


问:
How to let user switch displayed text language on page Node js Next js?
My client has a requirement for dual language on a web app.  Users need to be able to toggle between French and English.

I added a button that toggles a state and sets a cookie so that I can remember their selection for next time.

What is the most efficient straight forward way to write the code to handle the user language preference, and display the correct language text on a page?

My current approach is to use an if Statement like this, to first check the State and render the text accordingly.

```<code>const [useLang, setLang] = useState('En')

(useLang == 'En') ? <p>English Text Here</p> : <p>French Text Here</p>
</code>```

Would it be more efficient to try to get the English | French from a single source file, and if yes what should that look like, how should it be set up?

答:
Next.js has built-in support for internationalized (i18n) routing since v10.0.0. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing.

You can also disable the routing based translation and adjust it to state specific translation.

Complete documentation can be found here

Body:
My client has a requirement for dual language on a web app.  Users need to be able to toggle between French and English.

I added a button that toggles a state and sets a cookie so that I can remember their selection for next time.

What is the most efficient straight forward way to write the code to handle the user language preference, and display the correct language text on a page?

My current approach is to use an if Statement like this, to first check the State and render the text accordingly.

const [useLang, setLang] = useState('En')

(useLang == 'En') ?
English Text Here
 :
French Text Here

Would it be more efficient to try to get the English | French from a single source file, and if yes what should that look like, how should it be set up?


问:
Null terminating int arrays
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

```<code>int *array = new int[x];
..do some stuff..
delete array;
</code>```

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

答:
The block of memory used by your array has some extra data in there, that isn't directly visible to your program, that tells delete how big the block is.

What you say about char arrays is not true, by the way - the presence of a NUL terminator isn't relevant to delete - it uses the hidden block size just like any other block of memory.

(Incidentally, you should say delete [] array; when you're deleting an array.)

Title: Null terminating int arrays

Body:
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

int *array = new int[x];
..do some stuff..
delete array;

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?


问:
Do event calls stop execution of the mthod that called it until the event is done?
I have a save system I created that has two events, OnSaving and OnLoading, in my OnDestroy method I'm calling the OnSaving event then after I'm running some code that requires that the game has fully saved, so my question is when an event is called, does the method that called the event wait until all subscribers have finished as if it was calling an event in the save class, or does it continue execution immediately?</p>

答:
All events(like Action and others) are just delegates - “generic methods”. So when the event is invoked, what actually happens is just a call of all subscribers. Event invocation is atomic - all subscribed methods are called in the order they have subscribed. Simplifying all of this - you just calling multiple methods with one.
And yes, after the event invocation all subscribers' complete execution is guaranteed.</p>


答:
read has a parameter for timeout, you can use:</p>
```<code>read -t 30 answer
</code>```

Title: Terminate script after 30 seconds of no user input?

Body:
read has a parameter for timeout, you can use:

read -t 30 answer


问:
"ifelse" function for character in R
I'm trying to create a new column of religion (called "AR2") that will take the word from column "religion" and fit a specific number in the new column
Like, if it is "Christian" I want it will be "0" and if-else  "1"
So, this is the code I create:

```<code>sample.data$AR2<-(ifelse(sample.data$religion=="Christian",0,1))
</code>```

But it creates a new column with only "1" and no "0" for Christian.

Someone can please help me to understand What I'm doing wrong??

Thank you so much,
Maya

答:
There seem to be syntactic mistakes. Try this:

```<code>df$AR2 <- ifelse(df$religion == "Christian", 0, 1)
</code>```

Result:

```<code>df
   religion AR2
1 Christian   0
2    Muslim   1
3     Hindu   1
</code>```

Data:

```<code>df <- data.frame(
  religion = c("Christian", "Muslim", "Hindu")
)
</code>```

Title: "ifelse" function for character in R

Body:
I'm trying to create a new column of religion (called "AR2") that will take the word from column "religion" and fit a specific number in the new column
Like, if it is "Christian" I want it will be "0" and if-else  "1"
So, this is the code I create:

sample.data$AR2<-(ifelse(sample.data$religion=="Christian",0,1))

But it creates a new column with only "1" and no "0" for Christian.

Someone can please help me to understand What I'm doing wrong??

Thank you so much,
Maya

Body:
There seem to be syntactic mistakes. Try this:

df$AR2 <- ifelse(df$religion == "Christian", 0, 1)

Result:

df
   religion AR2
1 Christian   0
2    Muslim   1
3     Hindu   1

Data:

df <- data.frame(
  religion = c("Christian", "Muslim", "Hindu")
)


问:
Javascript split function for getting name from a whole link?
I have several link like this:

```<code>https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html
</code>```

Or, it can be:

```<code>https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html
</code>```

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

答:
Notice that solution won't help in case do you have multiple subdomains.

```<code>function getHostname(url) {
   let __url = new URL(url);
   __url = __url.origin.split("//")[1]

  if (__url.includes("www.")) {
    __url = __url.replace("www.", "");
  }

  return __url.split(".")[0]

}
console.log(getHostname(YOUR_URL_HERE))
</code>```

Body:
I have several link like this:

https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html

Or, it can be:

https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

Body:
Notice that solution won't help in case do you have multiple subdomains.

function getHostname(url) {
   let __url = new URL(url);
   __url = __url.origin.split("//")[1]

  if (__url.includes("www.")) {
    __url = __url.replace("www.", "");
  }

  return __url.split(".")[0]

}
console.log(getHostname(YOUR_URL_HERE))


问:
Error: src/app/components/button/button.component.ts:11:27 - error TS1005: '(' expected
I'm new to Angular and I'm following a tutorial to get started and I'm getting this error in line 11, even if '(' is present

Error: src/app/components/button/button.component.ts:11:27 - error TS1005: '(' expected.

this is the code of button.component.ts

```<code> import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css']
})
export class ButtonComponent implements OnInit {
  @Input() color: string;
  @Input() text: string;
  @Output() btnEvetn: new EventEmitter(); //line 11

  constructor() { }

  ngOnInit(): void {}

  onClick()
  {
    console.log("Added");
  }

}

</code>```

also, I'm getting those other errors, all of them on line 11

Error: src/app/components/button/button.component.ts:11:27 - error TS2314: Generic type 'EventEmitter' requires 1 type argument(s).

Error: src/app/components/button/button.component.ts:11:39 - error TS1441: Cannot start a function call in a type annotation.

Error: src/app/components/button/button.component.ts:11:40 - error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.

答: @Output() btnEvetn: EventEmitter<void> = new EventEmitter();

Body:
I'm new to Angular and I'm following a tutorial to get started and I'm getting this error in line 11, even if '(' is present

Error: src/app/components/button/button.component.ts:11:27 - error TS1005: '(' expected.

this is the code of button.component.ts

 import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css']
})
export class ButtonComponent implements OnInit {
  @Input() color: string;
  @Input() text: string;
  @Output() btnEvetn: new EventEmitter(); //line 11

  constructor() { }

  ngOnInit(): void {}

  onClick()
  {
    console.log("Added");
  }

}

also, I'm getting those other errors, all of them on line 11

Error: src/app/components/button/button.component.ts:11:27 - error TS2314: Generic type 'EventEmitter' requires 1 type argument(s).

Error: src/app/components/button/button.component.ts:11:39 - error TS1441: Cannot start a function call in a type annotation.

Error: src/app/components/button/button.component.ts:11:40 - error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.


问:
The play() request was interrupted by a call to pause() - when calling play too quick
I've a button that playes a sound when clicked with the help of the AudioPlayers library. But when I spam click the button, I get the error:

```<code>The play() request was interrupted by a call to pause().
    at Object.createErrorWithStack (http://localhost:53960/dart_sdk.js:5076:12)
    at Object._rethrow (http://localhost:53960/dart_sdk.js:40477:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:53960/dart_sdk.js:40473:13)
    at Object._microtaskLoop (http://localhost:53960/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:53960/dart_sdk.js:40336:13)
    at http://localhost:53960/dart_sdk.js:35811:9
</code>```

Here's the code:

```<code>AudioPlayer player = AudioPlayer();

on_pressed(){
  player.play("assets/sound.mp3");
}
</code>```

How do I fix this? Thanks!

答:
```<code>on_pressed : () async {
 await player.play("assets/sound.mp3");
}
</code>```

you aren't using any handler to stop the user from further tapping, one-time tap is enough, you should use some logic to disable the tap until the audio player starts playing.

Body:
I've a button that playes a sound when clicked with the help of the AudioPlayers library. But when I spam click the button, I get the error:

The play() request was interrupted by a call to pause().
    at Object.createErrorWithStack (http://localhost:53960/dart_sdk.js:5076:12)
    at Object._rethrow (http://localhost:53960/dart_sdk.js:40477:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:53960/dart_sdk.js:40473:13)
    at Object._microtaskLoop (http://localhost:53960/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:53960/dart_sdk.js:40336:13)
    at http://localhost:53960/dart_sdk.js:35811:9

Here's the code:

AudioPlayer player = AudioPlayer();

on_pressed(){
  player.play("assets/sound.mp3");
}

How do I fix this? Thanks!

Body:
on_pressed : () async {
 await player.play("assets/sound.mp3");
}

you aren't using any handler to stop the user from further tapping, one-time tap is enough, you should use some logic to disable the tap until the audio player starts playing.


问:
How to make directory by generator expressions in CMake?
I want to create a directory by using the file(MAKE_DIRECTORY but it doesn't work with the generator expressions.

I'm trying to use the generator expression inside another CMake module, as a rough code snippet:

```<code>function_from_another_module(target_name)
</code>```

and in that module:

```<code>file(MAKE_DIRECTORY $<TARGET_FILE_DIR:${target_name}>/foo/bar)
</code>```

And in my real case, I'm trying to do some management on my exe targets, copy assets, generate files and some other platform based configurations.

答:
The file() command is executed at configuration time and at that time and at that time generator expressions aren't evaluated yet. Furthermore the result may depend which is never available during the configuration process, just during the build.

You may be able to get the desired outcome by using adding build event logic via add_custom_command though:

```<code>add_custom_command(TARGET ${target_name} # correct target to attach logic to?
                   PRE_BUILD             # or PRE_LINK/POST_BUILD ?
                   COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:${target_name}>/foo/bar")
</code>```

Depending on your asset management logic you may want to create a cmake script doing the copying, execute it using ${CMAKE_COMMAND} -P script_file.cmake ... and pass necessary parameters using -D options, see CMake Command Line Tool: Run a Script

Body:
I want to create a directory by using the file(MAKE_DIRECTORY but it doesn't work with the generator expressions.

I'm trying to use the generator expression inside another CMake module, as a rough code snippet:

function_from_another_module(target_name)

and in that module:

file(MAKE_DIRECTORY $<TARGET_FILE_DIR:${target_name}>/foo/bar)

And in my real case, I'm trying to do some management on my exe targets, copy assets, generate files and some other platform based configurations.

Body:
The file() command is executed at configuration time and at that time and at that time generator expressions aren't evaluated yet. Furthermore the result may depend which is never available during the configuration process, just during the build.

You may be able to get the desired outcome by using adding build event logic via add_custom_command though:

add_custom_command(TARGET ${target_name} # correct target to attach logic to?
                   PRE_BUILD             # or PRE_LINK/POST_BUILD ?
                   COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:${target_name}>/foo/bar")

Depending on your asset management logic you may want to create a cmake script doing the copying, execute it using ${CMAKE_COMMAND} -P script_file.cmake ... and pass necessary parameters using -D options, see CMake Command Line Tool: Run a Script


问:
React State update a nested array with objects based on the id when iterated
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

```<code>const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });
</code>```

Here is my Jsx:

```<code>{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}
</code>```

Here is what I tried:

```<code>function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}
</code>```

答:
When you want to update the state of objects in the nested array, you must identify these objects and the property you want to update. Thus your handler should look like this.

```<code>function handleChange(index, property, value){
   // ...
}
</code>```

The setData function will only trigger a rerender if you pass it a new object. Thus you should create a copy.

```<code>function handleChange(index, property, value) {
  const new_working_hours = [...data.working_hours]; // copy the array
  const new_working_hour = { ...data.working_hours[index] }; // copy the array item to change

  new_working_hour[property] = value; // set the new value
  new_working_hours[index] = new_working_hour; // assign the new item to the copied array

  setData({ working_hours: new_working_hours }); // return a new data object
}
</code>```

Here is a working example. Click Run code snippet below.

const { useState } = React;

const App = () => {
  const [data, setData] = useState(initialState);

  function handleChange(index, property, value) {
    const new_working_hours = [...data.working_hours]; // copy the array
    const new_working_hour = { ...data.working_hours[index] }; // copy the array item to change

    new_working_hour[property] = value; // set the new value
    new_working_hours[index] = new_working_hour; // assign the new item to the copied array

    setData({ working_hours: new_working_hours }); // return a new data object
  }

  return data.working_hours.map((item, index) => (

      <input
        type="text"
        value={item.description}
        onChange={(e) => handleChange(index, "description", e.target.value)}
      />

      <input
        type="text"
        value={item.price}
        onChange={(e) => handleChange(index, "price", e.target.value)}
      />

  ));
};

const initialState = {
  working_hours: [
    {
      id: 1,
      description: "Random Text",
      price: 100
    },
    {
      id: 2,
      description: "Text Random",
      price: 100
    }
  ]
};

ReactDOM.render(<App />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });

Here is my Jsx:

{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}

Here is what I tried:

function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}

Body:
When you want to update the state of objects in the nested array, you must identify these objects and the property you want to update. Thus your handler should look like this.

function handleChange(index, property, value){
   // ...
}

The setData function will only trigger a rerender if you pass it a new object. Thus you should create a copy.

function handleChange(index, property, value) {
  const new_working_hours = [...data.working_hours]; // copy the array
  const new_working_hour = { ...data.working_hours[index] }; // copy the array item to change

  new_working_hour[property] = value; // set the new value
  new_working_hours[index] = new_working_hour; // assign the new item to the copied array

  setData({ working_hours: new_working_hours }); // return a new data object
}

Here is a working example. Click Run code snippet below.

const { useState } = React;

const App = () => {
  const [data, setData] = useState(initialState);

  function handleChange(index, property, value) {
    const new_working_hours = [...data.working_hours]; // copy the array
    const new_working_hour = { ...data.working_hours[index] }; // copy the array item to change

    new_working_hour[property] = value; // set the new value
    new_working_hours[index] = new_working_hour; // assign the new item to the copied array

    setData({ working_hours: new_working_hours }); // return a new data object
  }

  return data.working_hours.map((item, index) => (
    <div>
      <input
        type="text"
        value={item.description}
        onChange={(e) => handleChange(index, "description", e.target.value)}
      />

      <input
        type="text"
        value={item.price}
        onChange={(e) => handleChange(index, "price", e.target.value)}
      />
    </div>
  ));
};

const initialState = {
  working_hours: [
    {
      id: 1,
      description: "Random Text",
      price: 100
    },
    {
      id: 2,
      description: "Text Random",
      price: 100
    }
  ]
};

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
Find element that is causing the showing of horizontal scrollbar in Google Chrome
When I size my Chrome window to 328 x 455 pixels I still see a horizontal scrollbar.
How can I find out which element is causing this? I've been looking at elements via the developer console, but can't find the element.

I then tried the script I found here, but nothing is logged.
I tried it on element body, section1 and a bunch of others but don't know what else to do.

```<code>    $(function () {
        var f = $('body'); //document.getElementById("body");
        var contentHeight = f.scrollHeight;
        var declaredHeight = $(f).height();

        var contentWidth = f.scrollWidth;
        var declaredWidth = $(f).width();
        if (contentHeight > declaredHeight) {
            console.log("invalid height");
        }
        if (contentWidth > declaredWidth) {
            console.log("invalid width");
        }
    });
</code>```

答:
add your chrome snippets >>> by inspect > sources > snippets > new snippet > add
code $("*").css("border","2px solid #f00") >> click ctrl+enter

and the culprit appeared

In addition, it will be saved on the browser and used easily afterward

Body:
When I size my Chrome window to 328 x 455 pixels I still see a horizontal scrollbar.
How can I find out which element is causing this? I've been looking at elements via the developer console, but can't find the element.

I then tried the script I found here, but nothing is logged.
I tried it on element body, section1 and a bunch of others but don't know what else to do.

    $(function () {
        var f = $('body'); //document.getElementById("body");
        var contentHeight = f.scrollHeight;
        var declaredHeight = $(f).height();

        var contentWidth = f.scrollWidth;
        var declaredWidth = $(f).width();
        if (contentHeight > declaredHeight) {
            console.log("invalid height");
        }
        if (contentWidth > declaredWidth) {
            console.log("invalid width");
        }
    });


问:
Add my own class file in ASP.NET MVC, and it couldn't be referenced?
I am currently stuck trying to add my own class file into ASP.NET MVC project, so it could
be referenced by my controller. But Visual studio 2010 always complain about "The type or name 'Products' could not be found (are your missing a using directive or assembly reference?)

I am not sure where to put my class file and tried add the class to Models or Controllers directory, and it wouldn't work either. My the class is under the right namespace, and I did reference the Models namespace in my Controller. It could be something obvious, but I couldn't get it working:(

答:
The general rule of thumb is that business objects go it the Models folder you're correct. If it isn't working you don't have the project configured correctly. In the controller where you wanted to reference the Products object, did you add a reference to Models.Products?

Are there any other errors in listed? Sometimes multiple errors in a solution can combine to create something like this.


问:
Show/Hide Barcolor from Input Settings
how to make checkbox option to Show/Hide in Input Settings (so we don't need go to input style tab to show/hide it) for bar coloring with conditional below?

```<code>//Conditions
L_adx = DIPlus > DIMinus and ADX > th
S_adx = DIPlus < DIMinus and ADX > th

BAR_COLOR_ADX = L_adx ? color.lime : S_adx ? color.red :  color.orange

barcolor(title="ADX Bar Color", color = BAR_COLOR_ADX)
</code>```

Thanks in advance!

答:
You should use the input.bool() function to get the user input in a checkbox form. Then use this input as a condition for your color variable. Set it to na if it is unchecked.

```<code>show_barcolor = input.bool(defval=true, title="Show barcolor?")

BAR_COLOR_ADX = show_barcolor ? L_adx ? color.lime : S_adx ? color.red :  color.orange : na
barcolor(title="ADX Bar Color", color = BAR_COLOR_ADX)
</code>```

Title: Show/Hide Barcolor from Input Settings

Body:
how to make checkbox option to Show/Hide in Input Settings (so we don't need go to input style tab to show/hide it) for bar coloring with conditional below?

//Conditions
L_adx = DIPlus > DIMinus and ADX > th
S_adx = DIPlus < DIMinus and ADX > th

BAR_COLOR_ADX = L_adx ? color.lime : S_adx ? color.red :  color.orange

barcolor(title="ADX Bar Color", color = BAR_COLOR_ADX)

Thanks in advance!

Body:
You should use the input.bool() function to get the user input in a checkbox form. Then use this input as a condition for your color variable. Set it to na if it is unchecked.

show_barcolor = input.bool(defval=true, title="Show barcolor?")

BAR_COLOR_ADX = show_barcolor ? L_adx ? color.lime : S_adx ? color.red :  color.orange : na
barcolor(title="ADX Bar Color", color = BAR_COLOR_ADX)


问:
MS Access: How to query a second table when value is not found in the first
I have a simple query to find values in a related table. In some cases, the value is null.  In this case, I would like to query a second table.  I looked at the NZ function but it won't allow for another query operation.  I assume I am looking at a nested query or an operation like SQL COALASCE.

I want to first search tbl_bi_item_mstr

```<code>SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;
</code>```

For the null values, I would want to find them in tbl_cust_xref

```<code>SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;
</code>```

答:
You can simply join both tables, and use Nz() between the result fields.

```<code>SELECT d.cust_item_nr, Nz(i.bi_item_nr, x.bi_item_nr) AS bi_item_nr
FROM (tbl_cust_fcst_demd d
LEFT JOIN tbl_bi_item_mstr i ON d.cust_item_nr = i.bi_item_nr)
INNER JOIN tbl_cust_xref x ON d.cust_item_nr = x.cust_item_nr
</code>```

For >1 JOIN, parentheses are needed.

Using table aliases makes the SQL easier readable.

Body:
I have a simple query to find values in a related table. In some cases, the value is null.  In this case, I would like to query a second table.  I looked at the NZ function but it won't allow for another query operation.  I assume I am looking at a nested query or an operation like SQL COALASCE.

I want to first search tbl_bi_item_mstr

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;

For the null values, I would want to find them in tbl_cust_xref

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;

Body:
You can simply join both tables, and use Nz() between the result fields.

SELECT d.cust_item_nr, Nz(i.bi_item_nr, x.bi_item_nr) AS bi_item_nr
FROM (tbl_cust_fcst_demd d
LEFT JOIN tbl_bi_item_mstr i ON d.cust_item_nr = i.bi_item_nr)
INNER JOIN tbl_cust_xref x ON d.cust_item_nr = x.cust_item_nr

For >1 JOIN, parentheses are needed.

Using table aliases makes the SQL easier readable.