问:
How to extract specifc part from a string in MySQL
I am trying to extract a specifc part from a string in MySQL, however, I am unable to extract it correctly.

The pattern is the following:

```<code>-MB|{field_1}-AA|{field_2}-BB|{field_3}
</code>```

This is the example

```<code>-MB|string1-AA|string2-BB|string3
</code>```

I've written the following code to extract the last field, however it is not dynamic, and will only work, when we have a specific number of letters/numbers:

```<code>SELECT
    test_string,
    SUBSTRING(test_string, LOCATE( '|', test_string) + 1 - LOCATE( '|', test_string) - 9) as string3
FROM test_table;
</code>```

The output is the whole string and then just the last part of it:

string3

Having this said, can someone suggest a syntax that I can use in order to extract:

the values between the 1st | and second |

the value between the 2nd | and the 3rd |

and a better way to extract everything after the 3rd |

Thank you in advance!

答:
If you're going for the last string only, you can REVERSE() the string first then locate | and then use it to do SUBSTRING() on the reversed string.. THEN reverse it again to get the original string. There are three REVERSE() in total if you're going with SUBSTRING() without a subquery:

```<code>SELECT test_string,
       REVERSE(SUBSTRING(REVERSE(test_string),1,LOCATE('|',REVERSE(test_string))-1))
 FROM test_table;
</code>```

If you're using a subquery, you can reduce the usage of REVERSE() to two, albeit with a longer query:

```<code>SELECT test_string,
       REVERSE(SUBSTRING(rvstr,1,LOCATE('|',rvstr)-1))
  FROM
(SELECT test_string,
       REVERSE(test_string) rvstr
 FROM test_table) a;
</code>```

But you can avoid all that and just use SUBSTRING_INDEX

```<code>SELECT test_string,
       SUBSTRING_INDEX(test_string, '|', -1)
 FROM test_table;
</code>```

You can use the same function to extract other string separated by the delimiter using something like this:

```<code>SELECT test_string,
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',1),'|',-1) AS 'Str1',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',2),'|',-1) AS 'Str2',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',3),'|',-1) AS 'Str3'
 FROM test_table;
</code>```

As for "way to extract everything after the 3rd", I think it's a bit tricky but maybe:

```<code>SELECT test_string,
        Str1,Str2,Str3,
        SUBSTRING(test_string,LENGTH(CONCAT(Str1,Str2,Str3))+4) AS 'StrAfter3rd'
 FROM
(SELECT test_string,
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',1),'|',-1) AS 'Str1',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',2),'|',-1) AS 'Str2',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',3),'|',-1) AS 'Str3'
 FROM test_table) v;
</code>```

Getting the LENGTH() of the concatenated results of Str1 to Str3 with 3 of the original | re-added and + the last | before the 4th string (+4 in total), then use it for the SUBSTRING().

Demo fiddle

Body:
I am trying to extract a specifc part from a string in MySQL, however, I am unable to extract it correctly.

The pattern is the following:

-MB|{field_1}-AA|{field_2}-BB|{field_3}

This is the example

-MB|string1-AA|string2-BB|string3

I've written the following code to extract the last field, however it is not dynamic, and will only work, when we have a specific number of letters/numbers:

SELECT
    test_string,
    SUBSTRING(test_string, LOCATE( '|', test_string) + 1 - LOCATE( '|', test_string) - 9) as string3
FROM test_table;

The output is the whole string and then just the last part of it:

string3

Having this said, can someone suggest a syntax that I can use in order to extract:

the values between the 1st | and second |

the value between the 2nd | and the 3rd |

and a better way to extract everything after the 3rd |

Thank you in advance!

Body:
If you're going for the last string only, you can REVERSE() the string first then locate | and then use it to do SUBSTRING() on the reversed string.. THEN reverse it again to get the original string. There are three REVERSE() in total if you're going with SUBSTRING() without a subquery:

SELECT test_string,
       REVERSE(SUBSTRING(REVERSE(test_string),1,LOCATE('|',REVERSE(test_string))-1))
 FROM test_table;

If you're using a subquery, you can reduce the usage of REVERSE() to two, albeit with a longer query:

SELECT test_string,
       REVERSE(SUBSTRING(rvstr,1,LOCATE('|',rvstr)-1))
  FROM
(SELECT test_string,
       REVERSE(test_string) rvstr
 FROM test_table) a;

But you can avoid all that and just use SUBSTRING_INDEX

SELECT test_string,
       SUBSTRING_INDEX(test_string, '|', -1)
 FROM test_table;

You can use the same function to extract other string separated by the delimiter using something like this:

SELECT test_string,
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',1),'|',-1) AS 'Str1',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',2),'|',-1) AS 'Str2',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',3),'|',-1) AS 'Str3'
 FROM test_table;

As for "way to extract everything after the 3rd", I think it's a bit tricky but maybe:

SELECT test_string,
        Str1,Str2,Str3,
        SUBSTRING(test_string,LENGTH(CONCAT(Str1,Str2,Str3))+4) AS 'StrAfter3rd'
 FROM
(SELECT test_string,
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',1),'|',-1) AS 'Str1',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',2),'|',-1) AS 'Str2',
       SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',3),'|',-1) AS 'Str3'
 FROM test_table) v;

Getting the LENGTH() of the concatenated results of Str1 to Str3 with 3 of the original | re-added and + the last | before the 4th string (+4 in total), then use it for the SUBSTRING().

Demo fiddle


来源: stackexchange

问:
How to upload file into docker volume
I am facing the problem of how to save photos on the server side. Well, my application is on the docker and from what I've read, it's best to use docker volume. The problem is that I do not know how to send Base64 images on the docker volume. When creating the volume, I am using docker-compose.yml.</p>

答:
Using docker compose you can map volume like this:

version: '3.8'
services:
  cluster:
    image: <image-name>
    volumes:
        - ./path/to/imagefile64:/path/in/container/imagefile64 # This is a file containing image content in base 64
```

or you can simply do the same thing by bind mounting the image then converting it to base64 inside the container

ContentLicense: CC BY-SA 4.0

Title: How to upload file into docker volume

Body:
Using docker compose you can map volume like this:

version: '3.8'
services:
  cluster:
    image: <image-name>
    volumes:
        - ./path/to/imagefile64:/path/in/container/imagefile64 # This is a file containing image content in base 64

or you can simply do the same thing by bind mounting the image then converting it to base64 inside the container


问:
Is my code a performance killer?
I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?

Thank you.

index.php

```<code><script language='JavaScript'>
setInterval( 'SANAjax();', 1000 );

$(function() {
SANAjax = function(){

$('#dataDisplay').load('timer.php');

}
 });

</script>
<div id="dataDisplay"></div>
</code>```

timer.php

```<code>function time_difference($endtime){
    $days= (date("j",$endtime)-1);
    $hours =date("G",$endtime);
    $mins =date("i",$endtime);
    $secs =date("s",$endtime);
    $diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
    return $diff;
}

$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>
</code>```

答: By setting a setInterval for every second, you are basically saying that for 30 clients, you will be getting roughly 30 txn per second to your php server.  Its hard to say its a performance killer outside of just saying you will have to handle 30tps for this simple call.  I would first quesiton why you are doing this with a server side script.  You could just as easily give the html file a datetime when the page loads and do the countdown with just javascript in the browser.</p>

ContentLicense: CC BY-SA 3.0

Title: Is my code a performance killer?

Body:
I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?

Thank you.

index.php

timer.php

function time_difference($endtime){
    $days= (date("j",$endtime)-1);
    $hours =date("G",$endtime);
    $mins =date("i",$endtime);
    $secs =date("s",$endtime);
    $diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
    return $diff;
}

$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>


问:
RecyclerView not showing data on first load
I am trying to load a list of data from local db using LiveData.

view.xml

```<code>... // constraint layout surrounds this
<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView_cities"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp" />
</code>```

here is how I am setting up the recycler view in the Fragment:

```<code>val citiesAdapter = CitiesAdapter(cityRepository)
with(view.recyclerView_cities) {
    layoutManager = LinearLayoutManager(activity)
    setHasFixedSize(true)
    adapter = citiesAdapter
}
cityRepository.getAllCities().observe(this, Observer { list ->
    citiesAdapter.submitList(list)
})
</code>```

adapter:

```<code>class CitiesAdapter(private val repository: CityRepository) : ListAdapter<City, CitiesAdapter.CardViewHolder>(CityCallback()) {
    class CityCallback: DiffUtil.ItemCallback<City>() {
        override fun areItemsTheSame(oldItem: City, newItem: City): Boolean {
            return oldItem.city == newItem.city && oldItem.stateId == newItem.stateId
        }

        override fun areContentsTheSame(oldItem: City, newItem: City): Boolean {
            return oldItem.city == newItem.city &&
                    oldItem.stateName == newItem.stateName &&
                    oldItem.stateId == newItem.stateId &&
                    oldItem.selected == newItem.selected
        }
    }

    fun getCityAt(position: Int): City = getItem(position)

    // Provide a reference to the views for each data item
    class CardViewHolder(cardView: CardView) : RecyclerView.ViewHolder(cardView) {
        lateinit var checkBox: CheckBox
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        ...
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        ...
    }
}
</code>```

cityRepository.getAllCities() returns a LiveData> from my database.

I am using the ListAdapter that extends from RecyclerView so that it can handle managing the list for me. Also I am using the DiffUtil so that more granular notifies are called instead of just using notifyDataSetChanged.

Expected Behavior:
When I load the fragment, a list is shown in a RecyclerView with all of the cities in the database.

Actual Behavior:
When I load the fragment, an empty list is shown even though there are cities in the database. if I add a new city from the fragment, the list is populated with everything that was there before and the newly added item.

EDIT:
I hacked in an EditText to the xml and the list populates when I click it from the emulator. It does not work when I try and click it programmatically.

答:
You have two choices to solve this issue.

First, you can set Fixed Size to false.

```<code>recyclerView_cities.setHasFixedSize(false)
</code>```

Second, you can set the minimum height of your RecyclerView to your preferred size in your XML file.

```<code>android:minHeight="300dp"
</code>```

Body:
I am trying to load a list of data from local db using LiveData.

view.xml

... // constraint layout surrounds this
<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView_cities"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp" />

here is how I am setting up the recycler view in the Fragment:

val citiesAdapter = CitiesAdapter(cityRepository)
with(view.recyclerView_cities) {
    layoutManager = LinearLayoutManager(activity)
    setHasFixedSize(true)
    adapter = citiesAdapter
}
cityRepository.getAllCities().observe(this, Observer { list ->
    citiesAdapter.submitList(list)
})

adapter:

class CitiesAdapter(private val repository: CityRepository) : ListAdapter<City, CitiesAdapter.CardViewHolder>(CityCallback()) {
    class CityCallback: DiffUtil.ItemCallback<City>() {
        override fun areItemsTheSame(oldItem: City, newItem: City): Boolean {
            return oldItem.city == newItem.city && oldItem.stateId == newItem.stateId
        }

        override fun areContentsTheSame(oldItem: City, newItem: City): Boolean {
            return oldItem.city == newItem.city &&
                    oldItem.stateName == newItem.stateName &&
                    oldItem.stateId == newItem.stateId &&
                    oldItem.selected == newItem.selected
        }
    }

    fun getCityAt(position: Int): City = getItem(position)

    // Provide a reference to the views for each data item
    class CardViewHolder(cardView: CardView) : RecyclerView.ViewHolder(cardView) {
        lateinit var checkBox: CheckBox
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        ...
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        ...
    }
}

cityRepository.getAllCities() returns a LiveData> from my database.

I am using the ListAdapter that extends from RecyclerView so that it can handle managing the list for me. Also I am using the DiffUtil so that more granular notifies are called instead of just using notifyDataSetChanged.

Expected Behavior:
When I load the fragment, a list is shown in a RecyclerView with all of the cities in the database.

Actual Behavior:
When I load the fragment, an empty list is shown even though there are cities in the database. if I add a new city from the fragment, the list is populated with everything that was there before and the newly added item.

EDIT:
I hacked in an EditText to the xml and the list populates when I click it from the emulator. It does not work when I try and click it programmatically.

Body:
You have two choices to solve this issue.

First, you can set Fixed Size to false.

recyclerView_cities.setHasFixedSize(false)

Second, you can set the minimum height of your RecyclerView to your preferred size in your XML file.

android:minHeight="300dp"


问:
Livewire Event not firing - Modals
I'm trying to create a separate component to open a modal, but my events are not getting fired.

My parent component is Admin, and the component to open a modal is AddVideo

here is my Admin Component

```<code>public function add()
{
    $this->emit('addvideoModal');

}
</code>```

This is the button to fire that method

```<code>   <x-jet-button wire:click="add">
           {{ __('+ Video') }}
   </x-jet-button>

</code>```

This is from the AddVideoModal

```<code>class AddVideo extends Component
{
    protected $listeners = ['addvideoModal' => 'render'];

    public function render()
     {
         return view('livewire.add-video');
     }
}
</code>```

*Note, all my components are enclosed in a single Element. Am I missing something here?

Any help would be greatly appreciated.

答:
apparently need to create a new method.</p>
```<code>protected $listeners = ['addvideoModal' => 'sample'];

public function sample()
{
    $this->addModal = true;
}
</code>```

Title: Livewire Event not firing - Modals

Body:
I'm trying to create a separate component to open a modal, but my events are not getting fired.

My parent component is Admin, and the component to open a modal is AddVideo

here is my Admin Component

public function add()
{
    $this->emit('addvideoModal');

}

This is the button to fire that method

   <x-jet-button wire:click="add">
           {{ __('+ Video') }}
   </x-jet-button>

This is from the AddVideoModal

class AddVideo extends Component
{
    protected $listeners = ['addvideoModal' => 'render'];

    public function render()
     {
         return view('livewire.add-video');
     }
}

*Note, all my components are enclosed in a single Element. Am I missing something here?

Any help would be greatly appreciated.

Body:
apparently need to create a new method.

protected $listeners = ['addvideoModal' => 'sample'];

public function sample()
{
    $this->addModal = true;
}


问:
Storing function parameters within a variable
I'm trying to store parameters in a variable to later be used in a function, such as simple InquirerPy question.

A simple, functional question might look like this:

```<code>from InquirerPy.separator import Separator
from InquirerPy import inquirer

inquirer.select(
        message = "Select an action:",
        choices=[
            "Upload",
            "Download",
            Separator(),
            "Other"
        ]
).execute()
</code>```

However, as large parts of questions are identical, I would like to store the question and parameters and them use them later. Something like this:

```<code>question_details = (
    message = "Select an action:",
    choices=[
        "Upload",
        "Download",
        Separator(),
        "Other"
    ],
    )
inquirer.select(question_details).execute() # Fails
# SyntaxError: invalid syntax
</code>```

But this gives me a syntax error. I thought I could maybe store the parameters as a string to stop them being evaluated:

```<code>question_details = {' \
    message="Select an action:", \
    choices=[ \
        "Upload", \
        "Download", \
        Separator(), \
        "Other" \
    ], \
    '}
inquirer.select(question_details).execute() # Fails
# TypeError: __init__() missing 1 required positional argument: 'choices'
</code>```

However it doesn't recognise the string as a set of parameters and fails.

How can I store these parameters so they aren't evaluated before being stored, but can still be read correctly later when they are used by my InquirerPy function?

The documentation is here but I don't think anyone will need it.

答:
Store keyword parameters as a dictionary: question_details = {"message": "Select an action:", "choices": [...]).

Use double-asterisk to use dictionary for keyword parameters in the actual call: inquirer.select(**question_details).execute().

Body:
I'm trying to store parameters in a variable to later be used in a function, such as simple InquirerPy question.

A simple, functional question might look like this:

from InquirerPy.separator import Separator
from InquirerPy import inquirer

inquirer.select(
        message = "Select an action:",
        choices=[
            "Upload",
            "Download",
            Separator(),
            "Other"
        ]
).execute()

However, as large parts of questions are identical, I would like to store the question and parameters and them use them later. Something like this:

question_details = (
    message = "Select an action:",
    choices=[
        "Upload",
        "Download",
        Separator(),
        "Other"
    ],
    )
inquirer.select(question_details).execute() # Fails
# SyntaxError: invalid syntax

But this gives me a syntax error. I thought I could maybe store the parameters as a string to stop them being evaluated:

question_details = {' \
    message="Select an action:", \
    choices=[ \
        "Upload", \
        "Download", \
        Separator(), \
        "Other" \
    ], \
    '}
inquirer.select(question_details).execute() # Fails
# TypeError: __init__() missing 1 required positional argument: 'choices'

However it doesn't recognise the string as a set of parameters and fails.

How can I store these parameters so they aren't evaluated before being stored, but can still be read correctly later when they are used by my InquirerPy function?

The documentation is here but I don't think anyone will need it.


问:
Can't call HideBubble within conditional statement
Good evening, all.  I have a script where I would like to let the user choose whether to show the price bubbles on my plot.  I've created an input parameter but it looks like you can't call the hide function inside an if block.  The following seems straightforward but doesn't compile... any workarounds?</p>
```<code>input hidePriceBubbles = no;
.
.
.
plot p_amLows = amLows;
p_amLows.SetStyle(Curve.POINTS);
p_amLows.SetDefaultColor(Color.YELLOW);

if hidePriceBubbles then {
    p_amLows.HideBubble();    <--- "can not be called within branching"
} else {
}
</code>```

答: Newbie mistake on my part.  I didn't realize that the ThinkOrSwim UI automatically provides a settings panel for every plot in a script.  Among the choices on this panel is one that allows the user to hide the price bubble.  No coding required... it is baked into the system.</p>

Body:
Good evening, all.  I have a script where I would like to let the user choose whether to show the price bubbles on my plot.  I've created an input parameter but it looks like you can't call the hide function inside an if block.  The following seems straightforward but doesn't compile... any workarounds?

input hidePriceBubbles = no;
.
.
.
plot p_amLows = amLows;
p_amLows.SetStyle(Curve.POINTS);
p_amLows.SetDefaultColor(Color.YELLOW);

if hidePriceBubbles then {
    p_amLows.HideBubble();    <--- "can not be called within branching"
} else {
}


答:
Depends on your server specs and number of clients, this could quickly become a server-killer.

The multiple calls to a file every second will quickly put a lot of load for nothing though, so best practice calls for using a javascript timer countdown. I particularly like this one: http://stuntsnippets.com/javascript-countdown/

And for the jQuery implementation:

```<code><script type="text/javascript">
var myDate = new Date(); //Retrieve actual date
myDate.setTime(this.getTime() + (3600 * 2)); //Add two hours

$(document).ready(function() {
    $("#time").countdown({
        date: myDate.toGMTString(),
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>
</code>```

This should be enough, no more need for PHP calls and the client does everything.

Title: Is my code a performance killer?

Body:
Depends on your server specs and number of clients, this could quickly become a server-killer.

The multiple calls to a file every second will quickly put a lot of load for nothing though, so best practice calls for using a javascript timer countdown. I particularly like this one: http://stuntsnippets.com/javascript-countdown/

And for the jQuery implementation:

<script type="text/javascript">
var myDate = new Date(); //Retrieve actual date
myDate.setTime(this.getTime() + (3600 * 2)); //Add two hours

$(document).ready(function() {
    $("#time").countdown({
        date: myDate.toGMTString(),
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>

This should be enough, no more need for PHP calls and the client does everything.


问:
Add subdocument for each document in array dynamically
I want to $addField for every document in a sub-array with the name as arrayName_index (don't know how long the array is).

For example:
I have a collection of fun activities that looks like:

```<code>{
  _id: "1",
  activity: movie,
  attendees: [
    {firsName: "personA", lastName: "lasty"},
    {firsName: "personB", lastName: "namey"},
    {firsName: "personC", lastName: "blabla"}
  ]},
{
  _id: "2",
  activity: bowling,
  attendees: [{firsName: "personA", lastName: "lasty"}]
}
</code>```

I want a MongoDB aggregation to create output as:

```<code>{
  _id: "1",
  activity: movie,
  attendees: [
    {firsName: "personA", lastName: "lasty"},
    {firsName: "personB", lastName: "namey"},
    {firsName: "personC", lastName: "blabla"}
  ],
  attendees_1: {firsName: "personA", lastName: "lasty"},
  attendees_2: {firsName: "personB", lastName: "namey"},
  attendees_3: {firsName: "personC", lastName: "blabla"},
},
{
  _id: "2",
  activity: bowling,
  attendees: [{firsName: "personA", lastName: "lasty"}],
  attendees_1: {firsName: "personA", lastName: "lasty"}
}
</code>```

答:
Maybe slightly better since this avoids array searches, but it's largely the same as Yong Shun's answer.

db.collection.aggregate([
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          {
            "$arrayToObject": {
              "$reduce": {
                "input": { "$range": [ 0, { "$size": "$attendees" } ] },
                "initialValue": [],
                "in": {
                  "$concatArrays": [
                    "$$value",
                    [
                      {
                        k: {
                          "$concat": [
                            "attendees_",
                            { "$toString": { "$add": [ 1, "$$this" ] } }
                          ]
                        },
                        v: { "$arrayElemAt": [ "$attendees", "$$this" ] }
                      }
                    ]
                  ]
                }
              }
            }
          }
        ]
      }
    }
  }
])
```

Try it on mongoplayground.net.

Body:
I want to $addField for every document in a sub-array with the name as arrayName_index (don't know how long the array is).

For example:
I have a collection of fun activities that looks like:

{
  _id: "1",
  activity: movie,
  attendees: [
    {firsName: "personA", lastName: "lasty"},
    {firsName: "personB", lastName: "namey"},
    {firsName: "personC", lastName: "blabla"}
  ]},
{
  _id: "2",
  activity: bowling,
  attendees: [{firsName: "personA", lastName: "lasty"}]
}

I want a MongoDB aggregation to create output as:

{
  _id: "1",
  activity: movie,
  attendees: [
    {firsName: "personA", lastName: "lasty"},
    {firsName: "personB", lastName: "namey"},
    {firsName: "personC", lastName: "blabla"}
  ],
  attendees_1: {firsName: "personA", lastName: "lasty"},
  attendees_2: {firsName: "personB", lastName: "namey"},
  attendees_3: {firsName: "personC", lastName: "blabla"},
},
{
  _id: "2",
  activity: bowling,
  attendees: [{firsName: "personA", lastName: "lasty"}],
  attendees_1: {firsName: "personA", lastName: "lasty"}
}

Body:
Maybe slightly better since this avoids array searches, but it's largely the same as Yong Shun's answer.

db.collection.aggregate([
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          {
            "$arrayToObject": {
              "$reduce": {
                "input": { "$range": [ 0, { "$size": "$attendees" } ] },
                "initialValue": [],
                "in": {
                  "$concatArrays": [
                    "$$value",
                    [
                      {
                        k: {
                          "$concat": [
                            "attendees_",
                            { "$toString": { "$add": [ 1, "$$this" ] } }
                          ]
                        },
                        v: { "$arrayElemAt": [ "$attendees", "$$this" ] }
                      }
                    ]
                  ]
                }
              }
            }
          }
        ]
      }
    }
  }
])

Try it on mongoplayground.net.


问:
How to get a nested object from an json parent array in c#
In a C# Controller.cs how do I get a "child" or "nested" object from a "parent" object. I am currently able to retrieve the values for objects that are NOT nested, but I also need to be able to grab the values to certain child objects as well.

Please see my currently working code below that actually retrieves the data when the object is NOT nested. I am able to get the values invoiceNumber, email, and paymentMethod .

```<code>using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];

        }
</code>```

Now when I attempt to get the data for objects that are nested, I just get retuned NULL. These values are NOT actually null as when I am debugging in visual studio JSON Visualizer, they have values but I just do not know how to write the syntax I need in order to grab these that are "child" or "nested" objects. So as you can see in the code below I tried to call this value for amountSaved in every way that I could think of, but it just returns NULL each time.

```<code>            string rate = (string)obj["discounts.[0].amountSaved"];
            string rate2 = (string)obj["discounts.amountSaved"];
            string rate3 = (string)obj["discounts amountSaved"];
            string rate4 = (string)obj["discounts:amountSaved"];
            string rate5 = (string)obj["{discounts}:amountSaved"];
            string rate6 = (string)obj["{discounts}.amountSaved"];
            string rate7 = (string)obj["discounts.{amountSaved}"];
            string rate8 = (string)obj["{discounts.amountSaved}"];
</code>```

I figured the solution might be something like I call the parent object first which in this case is called discounts and then after a period or colon or space(. :) or something, I enter the name of the child object which in this case is amountSaved. That did not work.

Please see my screenshot below. This is when I debugging in visual studio and use the JSON Visualizer. You can see what I mean by discounts being a parent object with child values such as amountSaved. You can also see that it has a value of 0.75. You can can also see what I mean by the other values that are not nested which I am able to grab like shippingMethod.

How can I accomplish this?
Thank you.

答:
when you use the square brakets you should not put . between them. And you can omit square brakets and use dot syntax only if you have deserialized object, not just parsed it</p>
```<code> string rate = (string)obj["discounts"][0]["amountSaved"];
</code>```

Body:
In a C# Controller.cs how do I get a "child" or "nested" object from a "parent" object. I am currently able to retrieve the values for objects that are NOT nested, but I also need to be able to grab the values to certain child objects as well.

Please see my currently working code below that actually retrieves the data when the object is NOT nested. I am able to get the values invoiceNumber, email, and paymentMethod .

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];

        }

Now when I attempt to get the data for objects that are nested, I just get retuned NULL. These values are NOT actually null as when I am debugging in visual studio JSON Visualizer, they have values but I just do not know how to write the syntax I need in order to grab these that are "child" or "nested" objects. So as you can see in the code below I tried to call this value for amountSaved in every way that I could think of, but it just returns NULL each time.

            string rate = (string)obj["discounts.[0].amountSaved"];
            string rate2 = (string)obj["discounts.amountSaved"];
            string rate3 = (string)obj["discounts amountSaved"];
            string rate4 = (string)obj["discounts:amountSaved"];
            string rate5 = (string)obj["{discounts}:amountSaved"];
            string rate6 = (string)obj["{discounts}.amountSaved"];
            string rate7 = (string)obj["discounts.{amountSaved}"];
            string rate8 = (string)obj["{discounts.amountSaved}"];

I figured the solution might be something like I call the parent object first which in this case is called discounts and then after a period or colon or space(. :) or something, I enter the name of the child object which in this case is amountSaved. That did not work.

Please see my screenshot below. This is when I debugging in visual studio and use the JSON Visualizer. You can see what I mean by discounts being a parent object with child values such as amountSaved. You can also see that it has a value of 0.75. You can can also see what I mean by the other values that are not nested which I am able to grab like shippingMethod.

How can I accomplish this?
Thank you.

Body:
when you use the square brakets you should not put . between them. And you can omit square brakets and use dot syntax only if you have deserialized object, not just parsed it

 string rate = (string)obj["discounts"][0]["amountSaved"];


问:
How to parse CSV to object fields with different type C#?
I dont see this question specifically? But how do you parse a CSV file and store it as a model when one of the fields is not of the same type because it requires a little extra logic and a conversion. See below:
CSV rows/cols

```<code>"EmployeeId,OrganizationIdList"
    "12345,987/654/321"
    "54321,123/456/789"
</code>```

Model

```<code>public class Employee
{
    public long EmployeeId { get; set; }
    public List<long> OrganizationIdList { get; set; }
}
</code>```

Code I'm thinking about?

```<code>   using (var stream = xxx(I get my stream using Azure))
   using (var reader = new StreamReader(stream))
   using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var employees = new List<employees>();
    var records = csv.GetRecords<Employee>().ToList();
    foreach (var record in records)
    {
      employees.Add(new Employee { EmployeeId = record.EmployeeId, OrganizationIdList = record.OrganizationIdList });
    }
}

</code>```

Now as you and I know, OrganizationidList comes up NULL so how do I split and breakdown the incoming string to grab the longs? I cant figure this out? I need it to not be hard coded so the columns can switch places or the rows as I figured out how to do this by indexing. Any and all help welcomed!

Edit
I need to split and grab the 987/654/321 to convert(parse) into longs but how?

答:
parse the second column as a string then

```<code>    string inp ="987/654/321";
    var bits = inp.Split('/');
    var orgs = bits.Select(b=>Int32.Parse(b)).ToList();
</code>```

you will need using System.Linq

Body:
I dont see this question specifically? But how do you parse a CSV file and store it as a model when one of the fields is not of the same type because it requires a little extra logic and a conversion. See below:
CSV rows/cols

"EmployeeId,OrganizationIdList"
    "12345,987/654/321"
    "54321,123/456/789"

Model

public class Employee
{
    public long EmployeeId { get; set; }
    public List<long> OrganizationIdList { get; set; }
}

Code I'm thinking about?

   using (var stream = xxx(I get my stream using Azure))
   using (var reader = new StreamReader(stream))
   using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var employees = new List<employees>();
    var records = csv.GetRecords<Employee>().ToList();
    foreach (var record in records)
    {
      employees.Add(new Employee { EmployeeId = record.EmployeeId, OrganizationIdList = record.OrganizationIdList });
    }
}

Now as you and I know, OrganizationidList comes up NULL so how do I split and breakdown the incoming string to grab the longs? I cant figure this out? I need it to not be hard coded so the columns can switch places or the rows as I figured out how to do this by indexing. Any and all help welcomed!

Edit
I need to split and grab the 987/654/321 to convert(parse) into longs but how?

Body:
parse the second column as a string then

    string inp ="987/654/321";
    var bits = inp.Split('/');
    var orgs = bits.Select(b=>Int32.Parse(b)).ToList();

you will need using System.Linq


问:
Function to check for NULL and concatenating the strings
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

```<code>ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')
</code>```

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

答:
Actually if you just wrap you current expression inside TRIM() it should give you the behavior you want:

SELECT TRIM(ISNULL(FullName.FirstName, '') + ' ' +
            ISNULL(FullName.LastName, '')) AS FullName
FROM yourTable;
```

In the event that only the first or last name be present, your original expression would leave a dangling leading/trailing space.  The call to TRIM() fixes that by removing this extra space.

Body:
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

Body:
Actually if you just wrap you current expression inside TRIM() it should give you the behavior you want:

SELECT TRIM(ISNULL(FullName.FirstName, '') + ' ' +
            ISNULL(FullName.LastName, '')) AS FullName
FROM yourTable;

In the event that only the first or last name be present, your original expression would leave a dangling leading/trailing space.  The call to TRIM() fixes that by removing this extra space.


问:
Restarting an app in Eclipse
Is there any way to restart a program in Eclipse? (preferably 1-click)

I really wish the console view had something like a restart button that would kill the app and restart it with the latest changes.

This always takes me at least three clicks.  I click the down arrow next to the green circle with white triangle (play button) to open the dropdown menu, then I click to choose the Java main that I want to run, and then to stop I click the red square terminate button in the console view.  Is there any easier way to do this that requires fewer clicks?

答:
In Eclipse 4.1
open:
windows->Preferences->keys

in the filter text type:   terminate and relaunch

In the binding add your binding (i use shift-F5)

For "when" select "In Windows"

This will do it in single shorcut for you.

ContentLicense: CC BY-SA 2.5

Title: Restarting an app in Eclipse


问:
How do you sort a list from least to greatest in Standard ML?
I'm new to ML, and a bit of my code isn't working. I'm creating a function in ML where it's supposed to sort reals and then compile them into a single list. I created a large if-then statement, but it keeps failing at one particular point and I can't figure out why.

Here's my code:

```<code>fun sort3(c: real, g: real, j: real) =
  if c < g andalso g < j then [c, g, j]
  else if c < g andalso g > j then [c, j, g]
  else if c > g andalso c < j then [g, c, j]
  else if c > g andalso c > j then [g, j, c]
  else if c > g andalso g > j then [j, g, c]
  else [j, c, g];
</code>```

When I submit 3 real numbers into them, I expect to get them sorted from least to greatest. Most of the time, this is true, with two major exceptions. I'll write my results down below (all of them are real, not int).

(1,2,3) = (1,2,3)

(3,2,1) = (2,1,3) X

(2,1,3) = (1,2,3)

(3,1,2) = (1,2,3)

(2,3,1) = (2,1,3) X

(1,3,2) = (1,2,3)

Is there something wrong with my code? Is ML particular about using too many if-then statements? Thank you in advance!

答:
Looking at your code, you've made some bad assumptions:

```<code>fun sort3(c: real, g: real, j: real) =
  if c < g andalso g < j then [c, g, j]
  else if c < g andalso g > j then [c, j, g]
  else if c > g andalso c < j then [g, c, j]
  else if c > g andalso c > j then [g, j, c]
  else if c > g andalso g > j then [j, g, c]
  else [j, c, g];
</code>```
```<code>if c < g andalso g < j then [c, g, j]
</code>```

This holds up.

```<code>else if c < g andalso g > j then [c, j, g]
</code>```

This one not so much. We know from your conditional expression that c is less than g, and that j is less than g, but this does not tell us anything about the relationship between c and j.

```<code>else if c > g andalso c < j then [g, c, j]
</code>```

This logic holds up.

```<code>else if c > g andalso c > j then [g, j, c]
</code>```

We know from this that both g and j are less than c, but not how g and j relate to each other.

```<code>else if c > g andalso g > j then [j, g, c]
</code>```

This logic works.

A different way to approach this might be with nested conditionals, establish first which is the smallest, at which point there are only two values to compare.

```<code>let sort(a: real, b: real, c: real) =
  if a < b andalso a < c then
    (* 'a' must be the smallest *)
    if b < c then [a, b, c]
    else [a, c, b]
  else if b < a andalso b < c then
    (* 'b' must be the smallest *)
    if a < c then [b, a, c]
    else [b, c, a]
  else
    (* 'c' is the smallest *)
    if a < b then [c, a, b]
    else [c, b, a]
</code>```

Body:
I'm new to ML, and a bit of my code isn't working. I'm creating a function in ML where it's supposed to sort reals and then compile them into a single list. I created a large if-then statement, but it keeps failing at one particular point and I can't figure out why.

Here's my code:

fun sort3(c: real, g: real, j: real) =
  if c < g andalso g < j then [c, g, j]
  else if c < g andalso g > j then [c, j, g]
  else if c > g andalso c < j then [g, c, j]
  else if c > g andalso c > j then [g, j, c]
  else if c > g andalso g > j then [j, g, c]
  else [j, c, g];

When I submit 3 real numbers into them, I expect to get them sorted from least to greatest. Most of the time, this is true, with two major exceptions. I'll write my results down below (all of them are real, not int).

(1,2,3) = (1,2,3)

(3,2,1) = (2,1,3) X

(2,1,3) = (1,2,3)

(3,1,2) = (1,2,3)

(2,3,1) = (2,1,3) X

(1,3,2) = (1,2,3)

Is there something wrong with my code? Is ML particular about using too many if-then statements? Thank you in advance!

Body:
Looking at your code, you've made some bad assumptions:

fun sort3(c: real, g: real, j: real) =
  if c < g andalso g < j then [c, g, j]
  else if c < g andalso g > j then [c, j, g]
  else if c > g andalso c < j then [g, c, j]
  else if c > g andalso c > j then [g, j, c]
  else if c > g andalso g > j then [j, g, c]
  else [j, c, g];

if c < g andalso g < j then [c, g, j]

This holds up.

else if c < g andalso g > j then [c, j, g]

This one not so much. We know from your conditional expression that c is less than g, and that j is less than g, but this does not tell us anything about the relationship between c and j.

else if c > g andalso c < j then [g, c, j]

This logic holds up.

else if c > g andalso c > j then [g, j, c]

We know from this that both g and j are less than c, but not how g and j relate to each other.

else if c > g andalso g > j then [j, g, c]

This logic works.

A different way to approach this might be with nested conditionals, establish first which is the smallest, at which point there are only two values to compare.

let sort(a: real, b: real, c: real) =
  if a < b andalso a < c then
    (* 'a' must be the smallest *)
    if b < c then [a, b, c]
    else [a, c, b]
  else if b < a andalso b < c then
    (* 'b' must be the smallest *)
    if a < c then [b, a, c]
    else [b, c, a]
  else
    (* 'c' is the smallest *)
    if a < b then [c, a, b]
    else [c, b, a]


问:
How can I print an int array in C in one line (meaning, without for loops)?
Consider this char* example:

```<code>char* s;
s = (char*) malloc(5 * sizeof(char));

s = "Hello";

for (int i = 0; i < 5; i++)
{
   printf("%c", s[i]);
}

printf("\n%s", s);
</code>```

The code above shows two ways of printing the same thing: "Hello".

I tried to find an equivalent for int* and this is the best I could come up with:

```<code>int* ptr;
ptr = (int*) malloc(5 * sizeof(int));

ptr[0] = 2;
ptr[1] = 3;
ptr[2] = 3;
ptr[3] = 3;
ptr[4] = 4;

for (int i = 0; i < 5; i++)
{
    printf("%i ", ptr[i]);
}

printf("\n%d", *ptr);
</code>```

The first printf in the second example prints the whole array (2, 3, 3, 3, 4), but the second one only prints the first int value in the array (2).

How can I change the second printf for me to get the whole array? Also, how can I initialize the dynamically allocated array in one line? I tried ptr = {2, 3, 3, 3, 4}, but I got "error: expected expression".

I know in Python one can very easily initialize and print an array like this:

```<code>arr = [2, 4, 5, 7, 9]

print("The Array is: ", arr) #printing the array
</code>```

What's the equivalent of that in C?

答:
No,In C you cannot print array with single line of code, there is no inbuilt function available in C to print the array in single line.

Python also doesn't print array in single line, it does use loops but those functions are not visible to us.

How ever there are ways by which we can print C array without for-loop, You can refer this Question answered in stack overflow for that.

Is printing array possible without any loop in the C Language?

Body:
Consider this char* example:

char* s;
s = (char*) malloc(5 * sizeof(char));

s = "Hello";

for (int i = 0; i < 5; i++)
{
   printf("%c", s[i]);
}

printf("\n%s", s);

The code above shows two ways of printing the same thing: "Hello".

I tried to find an equivalent for int* and this is the best I could come up with:

int* ptr;
ptr = (int*) malloc(5 * sizeof(int));

ptr[0] = 2;
ptr[1] = 3;
ptr[2] = 3;
ptr[3] = 3;
ptr[4] = 4;

for (int i = 0; i < 5; i++)
{
    printf("%i ", ptr[i]);
}

printf("\n%d", *ptr);

The first printf in the second example prints the whole array (2, 3, 3, 3, 4), but the second one only prints the first int value in the array (2).

How can I change the second printf for me to get the whole array? Also, how can I initialize the dynamically allocated array in one line? I tried ptr = {2, 3, 3, 3, 4}, but I got "error: expected expression".

I know in Python one can very easily initialize and print an array like this:

arr = [2, 4, 5, 7, 9]

print("The Array is: ", arr) #printing the array

What's the equivalent of that in C?


问:
How to use google/zx to execute ffmpeg shell in windows?
I download the ffmpeg through scoop,and I can use ffmpeg in powershell.

My script is below:

```<code>#!/usr/bin/env zx
const filePath = `./abc.mp4`;
const srsServerURL = `192.168.30.100`;
await $`ffmpeg -re -i ${filePath} -c copy -f mp4 -y rtmp://${srsServerURL}/live/livestream`;
</code>```

but the zx tell me that ffmpeg not found.

答:
I think the issue might be that zx is using the bash inside WSL. Assuming you also don't want to use ffmpeg in WSL, here is how I fixed it.

Install git.

Find the bash.exe inside the installed git. In my case, it is located at C:/Program Files/Git/usr/bin/bash.exe.

Insert the following line after the shebang: $.shell = `Location to your bash`. In my case, it is $.shell = `C:/Program Files/Git/usr/bin/bash.exe`;.

I am fairly sure this works with other distributions of bash for Windows, but I have not tested.

Body:
I download the ffmpeg through scoop,and I can use ffmpeg in powershell.

My script is below:

#!/usr/bin/env zx
const filePath = `./abc.mp4`;
const srsServerURL = `192.168.30.100`;
await $`ffmpeg -re -i ${filePath} -c copy -f mp4 -y rtmp://${srsServerURL}/live/livestream`;

but the zx tell me that ffmpeg not found.


问:
VBA lookup with multiple returns
I am looking for help with applying VLOOKUP function to add extension to my pre existing table,

TABLE 1:

CAR
TOP SPEED
COLOR

BMW
200
BLACK

TESLA
220
WHITE

Table 2:

CAR
MODEL
YEAR

FORD
MUSTANG
2022

BMW
X5
2020

HONDA
ACCORD
2019

TESLA
Model S
2021

NISSAN
MAXIMA
2017

I am aiming to have the Table B as follows:

CAR
TOP SPEED
COLOR
MODEL
YEAR

BMW
200
BLACK
X5
2020

TESLA
220
WHITE
Model S
2021

```<code>sub CARSPEC()

Dim R As Long
Dim C As Long
Table1 = Sheets("Sheet1").Range("A2:A" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
Table2 = Sheets("Sheet2").Range("A2:H" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
R = Sheets("Sheet1").Range("D2").Row
C = Sheets("Sheet1").Range("D2").Column
For Each cell In Table1
 Sheets("Sheet1").Cells(R, C) = Application.WorksheetFunction.VLookup(cell, Table2, 2, False)
 R = R + 1
Next cell

End sub
</code>```

With the code above I am only getting the table without the year, meaning :

BMW
200
BLACK
X5

TESLA
220
WHITE
Model S

How could I expand the return values to cover the years as well.

Very much appreciated and THX Ahead.

答:
```<code>'R = Sheets("Sheet2").Cells(2, 9).Row
'C = Sheets("Sheet2").Cells(2, 9).Column
'R1 = Sheets("Sheet2").Cells(2, 10).Row
'C1 = Sheets("Sheet2").Cells(2, 10).Column
'R2 = Sheets("Sheet2").Cells(2, 11).Row
'C2 = Sheets("Sheet2").Cells(2, 11).Column

    'For Each cl In Table1

        'Sheets("Sheet2").Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 3, 0)
        'Dept_Row = Dept_Row + 1
        'Sheets("Sheet2").Cells(Dept_Row1, Dept_Clm1) = Application.WorksheetFunction.VLookup(cl, Table2, 4, 0)
        'Dept_Row1 = Dept_Row1 + 1
        'Sheets("Sheet2").Cells(Dept_Row2, Dept_Clm2) = Application.WorksheetFunction.VLookup(cl, Table2, 5, 0)
        'Dept_Row2 = Dept_Row2 + 1
    'Next c1
</code>```

Title: VBA lookup with multiple returns

Body:
I am looking for help with applying VLOOKUP function to add extension to my pre existing table,

TABLE 1:

CAR
TOP SPEED
COLOR

BMW
200
BLACK

TESLA
220
WHITE

Table 2:

CAR
MODEL
YEAR

FORD
MUSTANG
2022

BMW
X5
2020

HONDA
ACCORD
2019

TESLA
Model S
2021

NISSAN
MAXIMA
2017

I am aiming to have the Table B as follows:

CAR
TOP SPEED
COLOR
MODEL
YEAR

BMW
200
BLACK
X5
2020

TESLA
220
WHITE
Model S
2021

sub CARSPEC()

Dim R As Long
Dim C As Long
Table1 = Sheets("Sheet1").Range("A2:A" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
Table2 = Sheets("Sheet2").Range("A2:H" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
R = Sheets("Sheet1").Range("D2").Row
C = Sheets("Sheet1").Range("D2").Column
For Each cell In Table1
 Sheets("Sheet1").Cells(R, C) = Application.WorksheetFunction.VLookup(cell, Table2, 2, False)
 R = R + 1
Next cell

End sub

With the code above I am only getting the table without the year, meaning :

BMW
200
BLACK
X5

TESLA
220
WHITE
Model S

How could I expand the return values to cover the years as well.

Very much appreciated and THX Ahead.


问:
Regex Conditional validation
I have a input field, and I want to create a regex that only receive input value from 0.00 to 100.00(include both). I have created a regex check:

```<code>^1?\d{0,2}(\.\d{1,2})?$
</code>```

But with this one, it not only accept values from 0.00 to 100.00 but also accept the input from 100.01 to 199.99.

How can I set a condition that if there are three digital before the dot, it can be only 100 and the decimals part is 00 or 0 only if having decimals?

So 100.00, 100.0 or 100 are the only accept for the values over 99.99 and the input between 100.01 to 199.99 is not pass.

Here are some passed input:

```<code>100
100.00
100.0
3
0
0.00
5.2
8.21
37.23
</code>```

Here are some not passed:

```<code>40.323
100.50
101.50
199.99
40.
100.
</code>```

答:
This should work:

```<code>^((?:100(?:\.00?)?)|(?:\d\d?(?:\.\d\d?)?))$
</code>```

It matches:

x

x.x

x.xx

xx

xx.x

xx.xx

100

100.0

100.00

You can get the match via directly match or with the first capturing group :)

P.S. BTW, @Ouroborus's solution (in comments) also works, and his solution unexpectedly having the exact same length as mine lol:

^(?=.)(100(\.0{1,2})?|\d{1,2}(\.\d{1,2})?)$

Title: Regex Conditional validation

Body:
I have a input field, and I want to create a regex that only receive input value from 0.00 to 100.00(include both). I have created a regex check:

^1?\d{0,2}(\.\d{1,2})?$

But with this one, it not only accept values from 0.00 to 100.00 but also accept the input from 100.01 to 199.99.

How can I set a condition that if there are three digital before the dot, it can be only 100 and the decimals part is 00 or 0 only if having decimals?

So 100.00, 100.0 or 100 are the only accept for the values over 99.99 and the input between 100.01 to 199.99 is not pass.

Here are some passed input:

100
100.00
100.0
3
0
0.00
5.2
8.21
37.23

Here are some not passed:

40.323
100.50
101.50
199.99
40.
100.

Body:
This should work:

^((?:100(?:\.00?)?)|(?:\d\d?(?:\.\d\d?)?))$

It matches:

x

x.x

x.xx

xx

xx.x

xx.xx

100

100.0

100.00

You can get the match via directly match or with the first capturing group :)

P.S. BTW, @Ouroborus's solution (in comments) also works, and his solution unexpectedly having the exact same length as mine lol:

^(?=.)(100(\.0{1,2})?|\d{1,2}(\.\d{1,2})?)$


问:
Narrowing a union of array types using Array.every
I have a variable with a type that is a union of different array types. I want to narrow its type to a single member of that union, so I can run the appropriate code over it for each type. Using Array.every and a custom type guard seems like the right approach here, but when I try this TypeScript complains that "This expression is not callable." along with an explanation that I don't understand.

Here is my minimum reproducible example:

```<code>const isNumber = (val: unknown): val is number => typeof val === 'number';

const unionArr: string[] | number[] = Math.random() > 0.5 ? [1, 2, 3, 4, 5] : ['1', '2', '3', '4', '5'];

if (unionArr.every(isNumber)) { // <- Error
  unionArr;
}
</code>```

TypeScript Playground

Here is the error:

```<code>This expression is not callable.
  Each member of the union type
    '{
      <S extends string>(predicate: (value: string, index: number, array: string[]) => value is S, thisArg?: any): this is S[];
      (predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): boolean;
    } | {
      ...;
    }'
  has signatures, but none of those signatures are compatible with each other.
</code>```

This isn't preventing me from continuing. I've found that using a type assertion to recast my array to unknown[] before I narrow its type, as I would do if I were writing an isNumberArray custom type guard, removes the error without compromising type safety.

I've also found that recasting my string[] | number[] array to (string | number)[] removes the error.

However, the type of the array doesn't seem to be narrowed correctly, so I would need to use an additional as number[] after the check:

```<code>const isNumber = (val: unknown): val is number => typeof val === 'number';

const unionArr: string[] | number[] = Math.random() > 0.5 ? [1, 2, 3, 4, 5] : ['1', '2', '3', '4', '5'];

if ((unionArr as unknown[]).every(isNumber)) { // <- No error
  unionArr; // <- Incorrectly typed as string[] | number[]
}

if ((unionArr as (string | number)[]).every(isNumber)) { // <- No error
  unionArr; // <- Incrrectly typed as string[] | number[]
}
</code>```

TypeScript Playground

I tried a comparison with a non-array union as well, though of course in this case I was just using the custom type guard directly instead of using it with Array.every. In that case, there was also no error and the type was narrowed correctly:

```<code>const isNumber = (val: unknown): val is number => typeof val === 'number';

const union: string | number = Math.random() > 0.5 ? 1 : '1';

if (isNumber(union)) {
  union; // <- Correctly typed as number
}
</code>```

TypeScript Playground

Because I have that safe type assertion workaround, I can continue without needing to understand this. But I'm still very confused as to why that error appears in the first place, given I am trying to narrow a union of types to a single member of that union.

I'm guessing this is something to do with how Array.every has been typed by TypeScript, and there's probably nothing I can do aside from the workaround I'm already using. But it's hard to be sure of that when I don't really understand what's going wrong. Is there something I could do differently here, or is the as unknown[] type assertion I've used the correct or best way to handle this?

答:
Let's take a simpler example:

```<code>type StringOrNumberFn = (a: string | number) => void
type NumberOrBoolFn = (a: number | boolean) => void
declare const justNumber: StringOrNumberFn | NumberOrBoolFn

// works
justNumber(123)

// errors
justNumber('asd')
justNumber(true)
</code>```

When you have a union of functions that you try to invoke, you are actually calling a function that is the intersection of those members. If you don't know which function it is, then you may only call that function in ways that both functions support. In this case, both functions can take a number, so that's all that's allowed.

And if the intersection of those functions would have incompatible arguments, then the function cannot be called. So let's model that:

```<code>type StringFn = (a: string) => void
type NumberFn = (a: number) => void
declare const fnUnion: StringFn | NumberFn

fnUnion(123)    // Argument of type 'number' is not assignable to parameter of type 'never'.(2345)
fnUnion('asdf') // Argument of type 'string' is not assignable to parameter of type 'never'.(2345)
</code>```

This is closer to your problem.

Playground

A string array's every and a number array's every are typed to receive different parameters.

```<code>(value: string, index: number, array: string[]) // string[] every() args
(value: number, index: number, array: number[]) // number[] every() args
</code>```

Which is essentially the same problem as above.

So I don't think there's a way that the compiler will be okay with calling the every method on this union.

Instead, I'd probably write a type assertion for the whole array and loop over it manually.

```<code>const isNumberArray = (array: unknown[]): array is number[] => {
  for (const value of array) {
    if (typeof value !== 'number') return false
  }

  return true
}

declare const unionArr: string[] | number[]

if (isNumberArray(unionArr)) {
  Math.round(unionArr[0]); // works
}
</code>```

Playground

Body:
I have a variable with a type that is a union of different array types. I want to narrow its type to a single member of that union, so I can run the appropriate code over it for each type. Using Array.every and a custom type guard seems like the right approach here, but when I try this TypeScript complains that "This expression is not callable." along with an explanation that I don't understand.

Here is my minimum reproducible example:

const isNumber = (val: unknown): val is number => typeof val === 'number';

const unionArr: string[] | number[] = Math.random() > 0.5 ? [1, 2, 3, 4, 5] : ['1', '2', '3', '4', '5'];

if (unionArr.every(isNumber)) { // <- Error
  unionArr;
}

TypeScript Playground

Here is the error:

This expression is not callable.
  Each member of the union type
    '{
      <S extends string>(predicate: (value: string, index: number, array: string[]) => value is S, thisArg?: any): this is S[];
      (predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): boolean;
    } | {
      ...;
    }'
  has signatures, but none of those signatures are compatible with each other.

This isn't preventing me from continuing. I've found that using a type assertion to recast my array to unknown[] before I narrow its type, as I would do if I were writing an isNumberArray custom type guard, removes the error without compromising type safety.

I've also found that recasting my string[] | number[] array to (string | number)[] removes the error.

However, the type of the array doesn't seem to be narrowed correctly, so I would need to use an additional as number[] after the check:

const isNumber = (val: unknown): val is number => typeof val === 'number';

const unionArr: string[] | number[] = Math.random() > 0.5 ? [1, 2, 3, 4, 5] : ['1', '2', '3', '4', '5'];

if ((unionArr as unknown[]).every(isNumber)) { // <- No error
  unionArr; // <- Incorrectly typed as string[] | number[]
}

if ((unionArr as (string | number)[]).every(isNumber)) { // <- No error
  unionArr; // <- Incrrectly typed as string[] | number[]
}

<a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBAlhAcgVwLYCMCmAnGBeGACgDcBDAGwC4ZkwBrMEAdzAEpqzz4IYw0tceAHwwoATwAOmEADMYnfHgIByPhhzKA3AFgAUHtCRYtOOACC2bNWjY4YAOYBtALowAPr344X+GAFlSKAALADpsUjAAExBUQlYYEQAGEIBWGAB+GEcARgAaGAAmfIBmfIAWfJTXakdlbOV85QKGmGViluUyjpTlZx19XTg5QkITc0sYUh5aBmYwF1YQzGIcMUIEFHVsVniAbxgAegOYAB4AWhhEEBgcbBBsPRgaMFMwC2xNQ+PzmABJMFAlkwwCg5DEokkmEikx4NjsTlcHjUAhcegAvno9EMiKMXuNcFMiHCHO5PFtWAslitsGsNl5tnsvqcLlcbpZ7o9nq93p8jsy-gCgSCwRCpNDCcSEaTkd5nOigA" rel="nofollow noreferrer">TypeScript Playground

I tried a comparison with a non-array union as well, though of course in this case I was just using the custom type guard directly instead of using it with Array.every. In that case, there was also no error and the type was narrowed correctly:

const isNumber = (val: unknown): val is number => typeof val === 'number';

const union: string | number = Math.random() > 0.5 ? 1 : '1';

if (isNumber(union)) {
  union; // <- Correctly typed as number
}

TypeScript Playground

Because I have that safe type assertion workaround, I can continue without needing to understand this. But I'm still very confused as to why that error appears in the first place, given I am trying to narrow a union of types to a single member of that union.

I'm guessing this is something to do with how Array.every has been typed by TypeScript, and there's probably nothing I can do aside from the workaround I'm already using. But it's hard to be sure of that when I don't really understand what's going wrong. Is there something I could do differently here, or is the as unknown[] type assertion I've used the correct or best way to handle this?

Body:
Let's take a simpler example:

type StringOrNumberFn = (a: string | number) => void
type NumberOrBoolFn = (a: number | boolean) => void
declare const justNumber: StringOrNumberFn | NumberOrBoolFn

// works
justNumber(123)

// errors
justNumber('asd')
justNumber(true)

When you have a union of functions that you try to invoke, you are actually calling a function that is the intersection of those members. If you don't know which function it is, then you may only call that function in ways that both functions support. In this case, both functions can take a number, so that's all that's allowed.

And if the intersection of those functions would have incompatible arguments, then the function cannot be called. So let's model that:

type StringFn = (a: string) => void
type NumberFn = (a: number) => void
declare const fnUnion: StringFn | NumberFn

fnUnion(123)    // Argument of type 'number' is not assignable to parameter of type 'never'.(2345)
fnUnion('asdf') // Argument of type 'string' is not assignable to parameter of type 'never'.(2345)

This is closer to your problem.

Playground

A string array's every and a number array's every are typed to receive different parameters.

(value: string, index: number, array: string[]) // string[] every() args
(value: number, index: number, array: number[]) // number[] every() args

Which is essentially the same problem as above.

So I don't think there's a way that the compiler will be okay with calling the every method on this union.

Instead, I'd probably write a type assertion for the whole array and loop over it manually.

const isNumberArray = (array: unknown[]): array is number[] => {
  for (const value of array) {
    if (typeof value !== 'number') return false
  }

  return true
}

declare const unionArr: string[] | number[]

if (isNumberArray(unionArr)) {
  Math.round(unionArr[0]); // works
}

Playground


问:
Understanding pandas.Series.str.replace behavior when I try to pass pat as a list?
The signature of the subject method is Series.str.replace(self, pat, repl, n=-1, case=None, flags=0, regex=True) where:

pat:str or compiled regex

String can be a character sequence or regular expression.

repl : str or callable

Replacement string or a callable. The callable is passed the regex match object and must return a replacement string to be used. See re.sub()

Example: pd.Series(['a','b',5,np.nan]).str.replace(['a'],'999') results in a series with all NaNs

Why does this convert my entire column to NaNs if I pass pat as a list. It should throw an error if it does not see a list as a regex compiled pattern or a string. what is causing this behavior?

答:
You didn't state the version, but I confirm in pandas 1.3 it throws an error if you try to pass pat as a list:

```<code>pd.Series(['a','b',5,np.nan]).str.replace(['a'],'999')

TypeError: unhashable type: 'list'
</code>```

Beyond that, the place to file a bug/enhance request on pandas is https://github.com/pandas-dev/pandas/issues. (They are responsive to enhance requests, see this one they implemented: Should str.replace accept a compiled expression? #15446 back in 0.20)

Body:
You didn't state the version, but I confirm in pandas 1.3 it throws an error if you try to pass pat as a list:

pd.Series(['a','b',5,np.nan]).str.replace(['a'],'999')

TypeError: unhashable type: 'list'

Beyond that, the place to file a bug/enhance request on pandas is https://github.com/pandas-dev/pandas/issues. (They are responsive to enhance requests, see this one they implemented: Should str.replace accept a compiled expression? #15446 back in 0.20)


问:
"rake cucumber" insists these gems aren't installed, though they clearly are
I've run across two very similar questions but the answers there apparently don't apply for my issue so I conclude I am getting the same error, but for different reasons.

Basically, I have rspec-rails and cucumber-rails installed, but I can't seem to convince "rake cucumber" of this.

```<code>chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ rake cucumber
(in /Users/chuckhoffman/projects/siteman/releases/siteman)
DEPRECATION WARNING: require "activesupport" is deprecated and will be removed in Rails 3. Use require "active_support" instead. (called from /Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2/gems/activesupport-2.3.11/lib/activesupport.rb:2)
 [FSTR] Using Red Five FileStorage version 0.1
/Users/chuckhoffman/.rvm/rubies/ruby-1.8.7-p334/bin/ruby -I "/Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2/gems/cucumber-0.10.0/lib:lib" "/Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2/gems/cucumber-0.10.0/bin/cucumber"  --profile default
Using the default profile...
 [FSTR] Using Red Five FileStorage version 0.1
Missing these required gems:
  cucumber-rails  >= 0.3.2
  rspec-rails  >= 1.3.2

You're running:
  ruby 1.8.7.334 at /Users/chuckhoffman/.rvm/rubies/ruby-1.8.7-p334/bin/ruby
  rubygems 1.6.2 at /Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2, /Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@global

Run `rake gems:install` to install the missing gems.
rake aborted!
Command failed with status (1): [/Users/chuckhoffman/.rvm/rubies/ruby-1.8.7...]

(See full trace by running task with --trace)
chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ gem list cucumber-rails

*** LOCAL GEMS ***

cucumber-rails (0.3.2)
chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ gem list rspec-rails

*** LOCAL GEMS ***

rspec-rails (1.3.3, 1.3.0)
chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ ls vendor/gems
ls: vendor/gems: No such file or directory
</code>```

As you can see, gem list reports the exact versions rake cucumber tells me are missing, and I have no gems in vendor. I've also tried it in a newly generated fresh Rails 2.3.11 app, with the same results. So what gives?

答: First, it looks like you're running an old version of RVM, updating may help. Second, it appears you have a rails2 gemset, which may be causing some gem mismatches if you're installing to one gemset but your application is using another. Last, you should definitely be using Bundler for managing gems in your application since it solves a lot of these types of problems.</p>

Body:
I've run across two very similar questions but the answers there apparently don't apply for my issue so I conclude I am getting the same error, but for different reasons.

Basically, I have rspec-rails and cucumber-rails installed, but I can't seem to convince "rake cucumber" of this.

chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ rake cucumber
(in /Users/chuckhoffman/projects/siteman/releases/siteman)
DEPRECATION WARNING: require "activesupport" is deprecated and will be removed in Rails 3. Use require "active_support" instead. (called from /Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2/gems/activesupport-2.3.11/lib/activesupport.rb:2)
 [FSTR] Using Red Five FileStorage version 0.1
/Users/chuckhoffman/.rvm/rubies/ruby-1.8.7-p334/bin/ruby -I "/Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2/gems/cucumber-0.10.0/lib:lib" "/Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2/gems/cucumber-0.10.0/bin/cucumber"  --profile default
Using the default profile...
 [FSTR] Using Red Five FileStorage version 0.1
Missing these required gems:
  cucumber-rails  >= 0.3.2
  rspec-rails  >= 1.3.2

You're running:
  ruby 1.8.7.334 at /Users/chuckhoffman/.rvm/rubies/ruby-1.8.7-p334/bin/ruby
  rubygems 1.6.2 at /Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@rails2, /Users/chuckhoffman/.rvm/gems/ruby-1.8.7-p334@global

Run `rake gems:install` to install the missing gems.
rake aborted!
Command failed with status (1): [/Users/chuckhoffman/.rvm/rubies/ruby-1.8.7...]

(See full trace by running task with --trace)
chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ gem list cucumber-rails

*** LOCAL GEMS ***

cucumber-rails (0.3.2)
chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ gem list rspec-rails

*** LOCAL GEMS ***

rspec-rails (1.3.3, 1.3.0)
chuckhoffman@Lucky-Charm:~/projects/siteman/current(rspec)$ ls vendor/gems
ls: vendor/gems: No such file or directory

As you can see, gem list reports the exact versions rake cucumber tells me are missing, and I have no gems in vendor. I've also tried it in a newly generated fresh Rails 2.3.11 app, with the same results. So what gives?


问:
How to verify that method was NOT called in Moq?
How do I verify that method was NOT called in Moq?

Does it have something like AssertWasNotCalled?

UPDATE: Starting from Version 3.0, a new syntax can be used:

```<code>mock.Verify(foo => foo.Execute("ping"), Times.Never());
</code>```

答:
Using VerifyNoOtherCalls (requires Moq 4.8 or later)

This answer is an indirect approach.  Instead of checking that a particular method wasn't called, you check that no unexpected calls were made in general.

Consider that a thorough test of a mock does 2 things:

Verify that all expected calls were made

Verify that no unexpected calls were made

If you're already doing step 1, adding step 2 is trivial:

```<code>// Step 1 (if relevant - see note below)
mock.Verify(..., Times.Exactly(2));
mock.Verify(..., Times.Once());
// ...

// Step 2
mock.VerifyNoOtherCalls();
</code>```

Notes

If you omit step 1, step 2 will simply ensure no calls were made to the mock at all.

This does not require a strict mock.

Source: Moq Quickstart

OwnerDisplayName: alex

Body:
How do I verify that method was NOT called in Moq?

Does it have something like AssertWasNotCalled?

UPDATE: Starting from Version 3.0, a new syntax can be used:

mock.Verify(foo => foo.Execute("ping"), Times.Never());

LastEditorDisplayName: alex

Body:
Using VerifyNoOtherCalls (requires Moq 4.8 or later)

This answer is an indirect approach.  Instead of checking that a particular method wasn't called, you check that no unexpected calls were made in general.

Consider that a thorough test of a mock does 2 things:

Verify that all expected calls were made

Verify that no unexpected calls were made

If you're already doing step 1, adding step 2 is trivial:

// Step 1 (if relevant - see note below)
mock.Verify(..., Times.Exactly(2));
mock.Verify(..., Times.Once());
// ...

// Step 2
mock.VerifyNoOtherCalls();

Notes

If you omit step 1, step 2 will simply ensure no calls were made to the mock at all.

This does not require a strict mock.

Source: Moq Quickstart


问:
How do I extract rows of a 2D NumPy array by condition?
I have a 4*5 NumPy array and I want to retrieve rows in which all elements are less than 5.

```<code>arr = np.array([[0,2,3,4,5],[1,2,4,1,3], [2,2,5,4,6], [0,2,3,4,3]])
arr[np.where(arr[:,:] <= 4)]
</code>```

expected output:

```<code>[[1,2,4,1,3],[0,2,3,4,3]]
</code>```

actual output:

```<code>array([0, 2, 3, 4, 1, 2, 4, 1, 3, 2, 2, 4, 0, 2, 3, 4, 3])
</code>```

Any help is appreciated!

答:
This actually quite simple. Just convert the entire array to booleans (each value is True if it's less than 5, False otherwise), and use np.all with axis=1 to return True for each row where all items are True:

```<code>>>> arr[np.all(arr < 5, axis=1)]
array([[1, 2, 4, 1, 3],
       [0, 2, 3, 4, 3]])
</code>```

Body:
I have a 4*5 NumPy array and I want to retrieve rows in which all elements are less than 5.

arr = np.array([[0,2,3,4,5],[1,2,4,1,3], [2,2,5,4,6], [0,2,3,4,3]])
arr[np.where(arr[:,:] <= 4)]

expected output:

[[1,2,4,1,3],[0,2,3,4,3]]

actual output:

array([0, 2, 3, 4, 1, 2, 4, 1, 3, 2, 2, 4, 0, 2, 3, 4, 3])

Any help is appreciated!

Body:
This actually quite simple. Just convert the entire array to booleans (each value is True if it's less than 5, False otherwise), and use np.all with axis=1 to return True for each row where all items are True:

>>> arr[np.all(arr < 5, axis=1)]
array([[1, 2, 4, 1, 3],
       [0, 2, 3, 4, 3]])


问:
Trying to take the file extension out of my URL
Curious on how to take the file extension out of my URL to make it appear as "https://thedigitalagetech.info/" instead of "https://thedigitalagetech.info/index.html."</p>

答:
You've got a few options like: .htaccess, folder structure or JavaScript.

Solution 1.

As suggested by other users the best solution for this is probably using a script in your .htaccess file. But it's quitte difficult to understand if you're new to it. So your best option would be to search for a similar script in a tutorial or something.

Solution 2.

Another simple trick for a few pages would be to use the browsers way of showing index.html. Because it doesn't need to show index.html in the url if you just call the parent folder! As you might already have figured out you don't need to visit "https://thedigitalagetech.info/index.html" just visiting "https://thedigitalagetech.info" will already show you the index.html page. This is because when the browsers makes this request your server checks for a file called index if such a file exists it returns that one.

But ofcourse if you've got a page like services.html or contact.html then the url becomes something like "https://thedigitalagetech.info/contact.html" and I guess this is the part that you don't want. Instead of having a page called contact.html create a folder called contact and rename the contact.html to index.html inside that folder.
This way you could make a request to the folder and it will show the index.html of that folder. The request would look like this "https://thedigitalagetech.info/contact/"

So the folder structure is like:  *parts between () are folders

```<code> (public-html)    <-- root folder of your server
    index.html    <-- Your homepage
    (contact)     <-- a new folder
       index.html <-- Your old contact.html
    (services)    <-- a new folder
       index.html <-- Your old services.html
</code>```

Solution 3.

You could use JavaScript I guess but only to hide the file extentsion in the url after they've already visited it. And you're actually adding a none excisting page to there browser history so I think it's really bad practice as well. But still it might be a solution for you.

```<code>function rewriteUrl()
{
     let newURL = window.location.href.split('.html')[0];
     history.pushState(null,null,newURL);
}
</code>```

Body:
You've got a few options like: .htaccess, folder structure or JavaScript.

Solution 1.

As suggested by other users the best solution for this is probably using a script in your .htaccess file. But it's quitte difficult to understand if you're new to it. So your best option would be to search for a similar script in a tutorial or something.

Solution 2.

Another simple trick for a few pages would be to use the browsers way of showing index.html. Because it doesn't need to show index.html in the url if you just call the parent folder! As you might already have figured out you don't need to visit "https://thedigitalagetech.info/index.html" just visiting "https://thedigitalagetech.info" will already show you the index.html page. This is because when the browsers makes this request your server checks for a file called index if such a file exists it returns that one.

But ofcourse if you've got a page like services.html or contact.html then the url becomes something like "https://thedigitalagetech.info/contact.html" and I guess this is the part that you don't want. Instead of having a page called contact.html create a folder called contact and rename the contact.html to index.html inside that folder.
This way you could make a request to the folder and it will show the index.html of that folder. The request would look like this "https://thedigitalagetech.info/contact/"

So the folder structure is like:  *parts between () are folders

 (public-html)    <-- root folder of your server
    index.html    <-- Your homepage
    (contact)     <-- a new folder
       index.html <-- Your old contact.html
    (services)    <-- a new folder
       index.html <-- Your old services.html

Solution 3.

You could use JavaScript I guess but only to hide the file extentsion in the url after they've already visited it. And you're actually adding a none excisting page to there browser history so I think it's really bad practice as well. But still it might be a solution for you.

function rewriteUrl()
{
     let newURL = window.location.href.split('.html')[0];
     history.pushState(null,null,newURL);
}


问:
HTML DOM id Array Property & Adding to Stage JavaScript (Array)
I am trying to create an array of values using a for loop in JavaScript with multiple div id's with successive numbers (i.e. their values) denoting depth. The issue that I am running into is that I can't add the DOM element, i.e. 'text by ship here' successfully to the stage.  I added // to show different sections where I am stuck. In particular, I believe I am stuck on the for loop part of the code below //Trying to create a div array here with id's q0, q1, q2, ..., q3 and have used different functions such as for div[0].setAttribute("id", "q0") to be able to connect it with the create.jsDOMElement to add this text to the stage. Any help would be extremely appreciated! My apologies in advance if the code is too long. I have tried to express it succinctly.

⛵

<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>

  <canvas>This browser or document mode doesn't support canvas object.</canvas>

```
</div>
</div>
</p>
<hr />
<p>I have been able to make some progress on this. I am now running into the issue with the numbers needing to appear relative to the pixel 0, 0 on the Canvas/screen now, i.e. see the word <code>relative.</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1> I have some text here, and I need the numbers to appear relative to the Canvas/screen. </h1>
</br> </br>
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#gameCanvas {
  background-color: LightCyan;
}
</style>
<div class="canvasHolder1">

  <div id="alien"> |- - - - -| (1.5 mph)</div>
  <div id="alien1"> </div>
  <div id="alien2">  </div>
  <div id="alien3"></div>
  <div id="alien4">  </div>
<script>
</script>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
<script type="text/javascript">

  var stage = new createjs.Stage("gameCanvas");
  //Trying to create a div array here with id's q0, q1, q2, ..., q3 k is number of numbers
   var k=10;
   var div = [];
   for(i=0; i<=k; i++){
   div[i] = document.createElement('div');
   div[i].id = `q${i}`;
   div[i].style.position = "relative";
   div[i].innerHTML = i;
   div[i].style.top = 0;
   div[i].style.left = 0;
   document.body.appendChild(div[i]);
   }
     //Creating an object array of div elements to add to the stage
  var objectArray = [];
  for(j=0; j<=k; j++){
  objectArray[j] = new createjs.DOMElement(document.getElementById(`q${j}`));
  }
   var object = new createjs.DOMElement(document.getElementById("alien"));
   var object1 = new createjs.DOMElement(document.getElementById("alien1"));
  var object2 = new createjs.DOMElement(document.getElementById("alien2"));
   var object3 = new createjs.DOMElement(document.getElementById("alien3"));
  var object4 = new createjs.DOMElement(document.getElementById("alien4"));
  can = document.getElementById("gameCanvas");
  for(l=0; l<=k; l++){
  objectArray[l].x= 50;
  objectArray[l].y = can.height/10*l;
  }
  object1.x = can.width/3;
  object1.y = 1;
  object2.x = can.width/5;
  object2.y = 1;
  object3.x = can.width/10;
  object3.y = 1;
  object4.x = can.width/2.5;
  object4.y = 1;
  object.x = can.width/2;
  object.y = 1;
  var speedY=5;
  var speedX=5;
  var speedY1=5;
  var speedX1=5;
  var speedY2=5;
  var speedX2=5;
  var speedY3=5;
  var speedX3=5;
  var speedY4=5;
  var speedX4=5;
  var line = new createjs.Shape();
   stage.addChild(line);
   line.graphics.setStrokeStyle(3).beginStroke("rgba(0,0,0,9)");
   line.graphics.moveTo(30, 0);
   line.graphics.lineTo(35, 0);
   line.graphics.lineTo(30, 0);
   for( let n=0; n<=k; n++){
   var j=5;
   line.graphics.lineTo(30, can.height/10*n);
   line.graphics.lineTo(30+j, can.height/10*n);
   line.graphics.lineTo(30, can.height/10*n);
  }
   line.graphics.endStroke();

        function startGame() {
            stage.addChild(object);
            stage.addChild(object1);
            stage.addChild(object2);
            stage.addChild(object3);
            stage.addChild(object4);
            for(i=0; i<=k; i++){
            stage.addChild(objectArray[i]);
            }

            createjs.Ticker.addEventListener("tick", handleTick);
              function handleTick(event) {
              drop();
              bottom();
              right();
              left();
              drop1();
              bottom1();
              right1();
              left1();
              drop2();
              bottom2();
              right2();
              left2();
              drop3();
              bottom3();
              right3();
              left3();
              drop4();
              bottom4();
              right4();
              left4();

              stage.update();
            }
        }

  function drop(){
  if ( object.y>=can.height|| speedY==5|| object.y<=0){
      object.x += 0;
      object.y +=1;
      speedY=5;
   }
 }
  function bottom(){
   if (object.y>=can.height|| speedY==-5){  // <----- here
     speedY=5;
     object.y =0.5;
     object.x +=0.5;
     document.getElementById("object").textContent = "3k";
   }
 }

   function right(){
   if (object.x>=can.width ||speedY==10  ){  // <----- here
     speedY=10;
     object.y -=1;
     object.x -=1;
   }
 }
 function left(){
   if (0>=object.x ||speedY==30  ){  // <----- here
     speedY=30;
     object.y -=0.5;
     object.x +=0.5;
   }
 }
  function drop1(){
  if ( object1.y>=can.height|| speedY1==5|| object1.y<=0){
      object1.x -= 0.5;
      object1.y +=2;
      speedY1=5;
   }
 }
  function bottom1(){
   if (object1.y>=can.height|| speedY1==-5){  // <----- here
     speedY1=-5;
     object1.y -=2;
     object1.x -=0.5;
   }
 }

   function right1(){
   if (object1.x>=can.width ||speedY1==10  ){  // <----- here
     speedY1=10;
     object1.y -=1;
     object1.x -=1.5;
   }
 }
 function left1(){
   if (0>=object1.x ||speedY1==30  ){  // <----- here
     speedY1=30;
     object1.y -=1.5;
     object1.x +=1;
   }
 }
  function drop2(){
  if ( object2.y>=can.height|| speedY2==5|| object2.y<=0){
      object2.x += 0;
      object2.y +=1;
      speedY2=5;
   }
 }
  function bottom2(){
   if (object2.y>=can.height|| speedY2==-5){  // <----- here
     speedY2=-5;
     object2.y -=1;
     object2.x +=5;
   }
 }

   function right2(){
   if (object2.x>=can.width ||speedY2==10  ){  // <----- here
     speedY2=10;
     object2.y -=6;
     object2.x -=5;
   }
 }
 function left2(){
   if (0>=object2.x ||speedY2==30  ){  // <----- here
     speedY2=30;
     object2.y -=6;
     object2.x +=5;
   }
 }
  function drop3(){
  if ( object3.y>=can.height|| speedY3==5|| object3.y<=0){
      object3.x += 0.5;
      object3.y +=0.2;
      speedY3=5;
   }
 }
  function bottom3(){
   if (object3.y>=can.height|| speedY3==-5){  // <----- here
     speedY3=-5;
     object3.y -=4;
     object3.x -=2;
   }
 }
   function right3(){
   if (object3.x>=can.width ||speedY3==10  ){  // <----- here
     speedY3=10;
     object3.y -=0.5;
     object3.x -=0.5;
   }
 }
 function left3(){
   if (0>=object3.x ||speedY3==30  ){  // <----- here
     speedY3=30;
     object3.y -=0.5;
     object3.x +=0.5;
   }
 }
  function drop4(){
  if ( object4.y>=can.height|| speedY4==5|| object4.y<=0){
      object4.x += 0;
      object4.y +=0.25;
      speedY4=5;
   }
 }
  function bottom4(){
   if (object4.y>=can.height|| speedY4==-5){  // <----- here
     speedY4=-5;
     object4.y -=0.3;
     object4.x +=1;
   }
 }
   function right4(){
   if (object4.x>=can.width ||speedY4==10  ){  // <----- here
     speedY4=10;
     object4.y -=0.5;
     object4.x -=1;
   }
 }
 function left4(){
   if (0>=object4.x ||speedY4==30  ){  // <----- here
     speedY4=30;
     object4.y -=0.5;
     object4.x +=1;
   }
 }
</script>
<body onload="startGame();">
    <div >
  <canvas>This browser or document mode doesn't support canvas object.</canvas>
    </div>
</body></code>```

答:
Does this work for you?

⛵

            <canvas id="gameCanvas" width="300" height="300">Not supported</canvas>

```

Body:
I am trying to create an array of values using a for loop in JavaScript with multiple div id's with successive numbers (i.e. their values) denoting depth. The issue that I am running into is that I can't add the DOM element, i.e. 'text by ship here' successfully to the stage.  I added // to show different sections where I am stuck. In particular, I believe I am stuck on the for loop part of the code below //Trying to create a div array here with id's q0, q1, q2, ..., q3 and have used different functions such as for div[0].setAttribute("id", "q0") to be able to connect it with the create.jsDOMElement to add this text to the stage. Any help would be extremely appreciated! My apologies in advance if the code is too long. I have tried to express it succinctly.

⛵

<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>

  <canvas>This browser or document mode doesn't support canvas object.</canvas>

I have been able to make some progress on this. I am now running into the issue with the numbers needing to appear relative to the pixel 0, 0 on the Canvas/screen now, i.e. see the word relative.

 I have some text here, and I need the numbers to appear relative to the Canvas/screen.

 |- - - - -| (1.5 mph)

<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>

  <canvas>This browser or document mode doesn't support canvas object.</canvas>

Body:
Does this work for you?

<html>
    <script type="text/javascript" src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body { margin: 0; }
        #gameCanvas { background-color: lightblue; }
        .canvasHolder1 { position: relative; }
        .ui { position: absolute; top: 0; left: 0;  pointer-events: none;}
        .ui-element { position: relative; display: inline-block; margin-left: 4px; }
    </style>
    <body onload="startGame();">
        <div class="canvasHolder1">
            <div id="ship">⛵ </div>
            <div class="ui"></div>
            <canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
        </div>

        <script type="text/javascript">
            const stage = new createjs.Stage("gameCanvas");
            const ship = document.getElementById("ship");
            const ui = document.querySelector(".ui");
            const canvas = document.getElementById("gameCanvas");
            const canvasHolder = document.querySelector('.canvasHolder1');

            var divs = [];
            const texts = [ 'My Ship', 'Pos X', 'Pos Y', 'Other' ];

            for (i = 0; i <= 3; i++) {
                const newDiv = document.createElement("type");
                newDiv.id = `q${i}`;
                newDiv.className = `ui-element`;
                newDiv.innerHTML = texts[i];
                ui.appendChild(newDiv);
                divs.push(newDiv);
            }

            const textXPosition = divs[1];
            const textYPosition = divs[2];
            const textProgress = divs[3];

            canvas.addEventListener('mousemove', (evt) => {
                textXPosition.innerHTML = evt.pageX;
                textYPosition.innerHTML = evt.pageY;
            });

            var objectArray = [];
            objectArray.push(new createjs.DOMElement(divs[0]));
            const myFirstText = objectArray[0];
            const myFirstTextWidth = parseInt(myFirstText.htmlElement.offsetWidth);

            var shipJS = new createjs.DOMElement(ship);

            function applyPosition(posObject) {
                shipJS.x = posObject.x;
                shipJS.y = posObject.y;

                myFirstText.x = posObject.x - (myFirstTextWidth / 2);
                myFirstText.y = posObject.y - 15;
            }

            const shipPosition = {
                x: canvas.width / 3,
                y: 50
            };
            applyPosition(shipPosition);

            let looperCount = -1;
            const step = 0.02;
            const distance = canvas.width / 3;

            function handleTick(event) {
                if (looperCount >= 1) { looperCount = -1; }
                looperCount += step;
                const progress = Math.PI * looperCount;
                textProgress.innerHTML = parseInt(((looperCount + 1) / 2) * 100 )+'%';

                applyPosition({
                    x: (Math.cos(progress) * distance) + (distance * 1.5),
                    y: (Math.sin(progress) * distance) + (distance * 1.5)
                });
                stage.update();
            }

            function startGame() {
                stage.addChild(shipJS);
                stage.addChild(myFirstText);

                createjs.Ticker.addEventListener("tick", handleTick);

            }
        </script>
    </body>
</html>


问:
Pass parameter in method
I have this code

```<code>var txt;

function change(){
    txt = "@Utils.GeneratePass()";
    document.getElementById("password_field").value = txt;
}

function changeToHash(txt){
      alert(window.txt);
      var password = "@Utils.Hash(txt)";
      document.getElementById("password_field").value = password;
}
</code>```

In method @Utils.Hash i need pass one string, and i want put the value of txt.
But i got the error "The name 'txt' does not exist in the current context.

答:
You cannot pass js variable to C# code,you can try to pass @Utils.GeneratePass() to @Utils.Hash():

```<code>var txt;

function change(){
    txt = "@Utils.GeneratePass()";
    document.getElementById("password_field").value = txt;
}

function changeToHash(txt){
      alert(window.txt);
      var password = "@Utils.Hash(Utils.GeneratePass())";
      document.getElementById("password_field").value = password;
}
</code>```

Title: Pass parameter in method

Body:
I have this code

var txt;

function change(){
    txt = "@Utils.GeneratePass()";
    document.getElementById("password_field").value = txt;
}

function changeToHash(txt){
      alert(window.txt);
      var password = "@Utils.Hash(txt)";
      document.getElementById("password_field").value = password;
}

In method @Utils.Hash i need pass one string, and i want put the value of txt.
But i got the error "The name 'txt' does not exist in the current context.

Body:
You cannot pass js variable to C# code,you can try to pass @Utils.GeneratePass() to @Utils.Hash():

var txt;

function change(){
    txt = "@Utils.GeneratePass()";
    document.getElementById("password_field").value = txt;
}

function changeToHash(txt){
      alert(window.txt);
      var password = "@Utils.Hash(Utils.GeneratePass())";
      document.getElementById("password_field").value = password;
}