问:
I have select element on my page with 3 options. I need to show a different form below the select input when selected. How can I do it using PHP?
For example I have 3 choices in select input:
I can select Fruit, Furniture or Movie.

When I select one of them, the form needs to show up below.

For every choice there need to be a different form.

Can anyone help me, how to make it work?

I know how to create forms and everything, but I don't know how they can be changed when the value of select is changed.

I am doing a project using HTML, CSS, JS and PHP.

答:
function myFunction(val) {
    document.getElementById('frutas').style.display = "none";
    document.getElementById('moveis').style.display = "none";
    document.getElementById('filmes').style.display = "none";

    document.getElementById(val).style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="">
    <select name="" id="" onchange="myFunction(this.value)">
        <option value="">--selection--</option>
        <option value="frutas">Frutas</option>
        <option value="moveis">Móveis</option>
        <option value="filmes">Filmes</option>
    </select>
</form>

<div>
    <div id="frutas" style="display: none;">
        Você escolheu frutas
    </div>
    <div id="moveis" style="display: none;">
        Você escolheu moveis
    </div>
    <div id="filmes" style="display: none;">
        Você escolheu filmes
    </div>
</div></code>```

I hope I helped you

Body:
function myFunction(val) {
    document.getElementById('frutas').style.display = "none";
    document.getElementById('moveis').style.display = "none";
    document.getElementById('filmes').style.display = "none";

    document.getElementById(val).style.display = "block";
}

<form action="">
    <select name="" id="" onchange="myFunction(this.value)">
        <option value="">--selection--</option>
        <option value="frutas">Frutas</option>
        <option value="moveis">Móveis</option>
        <option value="filmes">Filmes</option>
    </select>
</form>

<div>
    <div id="frutas" style="display: none;">
        Você escolheu frutas
    </div>
    <div id="moveis" style="display: none;">
        Você escolheu moveis
    </div>
    <div id="filmes" style="display: none;">
        Você escolheu filmes
    </div>
</div>

I hope I helped you


来源: stackexchange

问:
How to limit Google Cloud Platform "BigQuery Metadata Viewer" permission?
I have 10 tables under my dataset. I need to create "BigQuery Metadata Viewer" permission but would like to neglect 2 tables under my dataset. So that BigQuery Metadata Viewer policy only will be able to access 8 tables.

I see that there is "condition" tab but could not figure out how to apply such a condition here.

答:
You can use the GRANT statement using the role bigquery.metadataViewer or dataviewer.You can set this role to table level, the user will have permission to a specific table, and won’t see listed tables. In this case, you need to know the name tables.

Take a look to this example:

```<code>GRANT `roles/bigquery.metadataViewer`
ON TABLE `my_dataset._my_table`
TO "user:user@domain.com"
</code>```

Additionally, you can  set this role at dataset level, this will grant access to read and list all the tables from the dataset.

Here’s an example:

```<code>GRANT `roles/bigquery.metadataViewer`
ON schema `project_name.dataset_name`
TO "user:mail@mail.com"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use the GRANT statement using the role bigquery.metadataViewer or dataviewer.You can set this role to table level, the user will have permission to a specific table, and won’t see listed tables. In this case, you need to know the name tables.

Take a look to this example:

GRANT `roles/bigquery.metadataViewer`
ON TABLE `my_dataset._my_table`
TO "user:user@domain.com"

Additionally, you can  set this role at dataset level, this will grant access to read and list all the tables from the dataset.

Here’s an example:

GRANT `roles/bigquery.metadataViewer`
ON schema `project_name.dataset_name`
TO "user:mail@mail.com"


问:
Tweepy API v2 "NoneType"
```<code>import tweepy

client = tweepy.Client(consumer_key='REPLACE_ME',
                       consumer_secret='REPLACE_ME',
                       access_token='REPLACE_ME',
                       access_token_secret='REPLACE_ME')

# Replace the text with whatever you want to Tweet about
response = client.create_tweet(text='hello world')

print(response)
</code>```

I am currently trying to work with this template code, but this is the error that I am currently getting:

```<code>TypeError: Consumer key must be string or bytes, not NoneType
</code>```

I'm not sure how this counts as a NoneType error, the Consumer Key, Consumer Secret, Access Token, and Access Token Secret are all in quotations so they should be a string.

Thank you!

答:
You can try something like this if you want to post a tweet.</p>
```<code>import tweepy
consumerKey = 'REPLACE_ME'
consumerSecret = 'REPLACE_ME'
accessToken = 'REPLACE_ME'
accessTokenSecret = 'REPLACE_ME'

auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)

api = tweepy.API(auth)

status = api.update_status(status="Hello world!")
</code>```

Title: Tweepy API v2 "NoneType"

Body:
import tweepy

client = tweepy.Client(consumer_key='REPLACE_ME',
                       consumer_secret='REPLACE_ME',
                       access_token='REPLACE_ME',
                       access_token_secret='REPLACE_ME')

# Replace the text with whatever you want to Tweet about
response = client.create_tweet(text='hello world')

print(response)

I am currently trying to work with this template code, but this is the error that I am currently getting:

TypeError: Consumer key must be string or bytes, not NoneType

I'm not sure how this counts as a NoneType error, the Consumer Key, Consumer Secret, Access Token, and Access Token Secret are all in quotations so they should be a string.

Thank you!

Body:
You can try something like this if you want to post a tweet.

import tweepy
consumerKey = 'REPLACE_ME'
consumerSecret = 'REPLACE_ME'
accessToken = 'REPLACE_ME'
accessTokenSecret = 'REPLACE_ME'

auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)

api = tweepy.API(auth)

status = api.update_status(status="Hello world!")


问:
Wpf ListBox with ComboBox databinding problem Dictionary
In my view is a Listbox with a DataTemplate. The DataTemplate defines 2 columns, one for a TextBlock and one for a ComboBox.

The ListBox:

```<code><ListBox ItemsSource="{Binding SelectedSensorProperty.ValueList}" Margin="5" Grid.Row="0"
                ScrollViewer.VerticalScrollBarVisibility="Visible">
</code>```

The ComboBox is defined as follows:

```<code><ComboBox MinWidth="150"
          ItemsSource="{Binding Path=DataContext.SelectedSensorProperty.PossibleValuesList,
             RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
          SelectedValuePath="Key"
          DisplayMemberPath="Value"
          SelectedValue="{Binding Path=Value, Mode=OneWay}"
          Grid.Column="1"
          Margin="2,0,0,0"/>
</code>```

My ViewModel contains a variable SelectedSensorProperty of type SensorProperty.

```<code>public class SensorProperty
{
    public string Name { get; set; }

    // key = index value, value = index text
    public Dictionary<string, string> PossibleValuesList { get; set; }

    // key = feature value, value = index value
    public Dictionary<string, string> ValueList { get; set; }

    public SensorProperty()
    {
        ValueList = new Dictionary<string, string>();
    }
}
</code>```

Suppose ValueList contains three KeyValue pairs, then 3 comboxes are shown. The problem is that the selected combobox values are not written to the ValueList. Setting the binding of the combobox to TwoWay gives an error saying the Dictionary is readonly. How to solve this?

答: You either need to bind the ValuesList ListBox to the selected item of the PossibleValuesList, or catch the SelectionChanged event of the PossibleValuesList and then update the ValuesList dictionary. In both cases though, you need the dictionaries to notify the UI when something changed in them. That can be done by implementing the INotifyPropertyChanged interface, or the dictionaries to be an ObservableCollection instead.</p>

Body:
In my view is a Listbox with a DataTemplate. The DataTemplate defines 2 columns, one for a TextBlock and one for a ComboBox.

The ListBox:

<ListBox ItemsSource="{Binding SelectedSensorProperty.ValueList}" Margin="5" Grid.Row="0"
                ScrollViewer.VerticalScrollBarVisibility="Visible">

The ComboBox is defined as follows:

<ComboBox MinWidth="150"
          ItemsSource="{Binding Path=DataContext.SelectedSensorProperty.PossibleValuesList,
             RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
          SelectedValuePath="Key"
          DisplayMemberPath="Value"
          SelectedValue="{Binding Path=Value, Mode=OneWay}"
          Grid.Column="1"
          Margin="2,0,0,0"/>

My ViewModel contains a variable SelectedSensorProperty of type SensorProperty.

public class SensorProperty
{
    public string Name { get; set; }

    // key = index value, value = index text
    public Dictionary<string, string> PossibleValuesList { get; set; }

    // key = feature value, value = index value
    public Dictionary<string, string> ValueList { get; set; }

    public SensorProperty()
    {
        ValueList = new Dictionary<string, string>();
    }
}

Suppose ValueList contains three KeyValue pairs, then 3 comboxes are shown. The problem is that the selected combobox values are not written to the ValueList. Setting the binding of the combobox to TwoWay gives an error saying the Dictionary is readonly. How to solve this?


问:
How to save lisp interaction history for future re-load?
I am using portacle as my Common Lisp environment. When I save my file it saves the entire REPL including the CL-USER>. This results in compilation error when I try to load the file.

I want to save the code and resume from where I left off. I have been writing code at REPL, saving the work in file from the buffer by using key-chords C-x C-s. But this is breaking the continuity of the project. Please suggest a way to do this.

答:
In portacle:

make sure that the REPL-window is the active one

click: File -> save as, enter "repl.log" as name

with any editor:

make a copy named xyz.lisp of repl.log

edit xyz.lisp, removing everything not a function-  or variable definition.

in restarted portacle:

switch with (ctrl-X O) to the scratch-buffer

load xyz.lisp  (ctrl-X ctrl-F), to a buffer

with (ctrl-C ctrl-K) compile and load it to the
REPL-buffer.

ContentLicense: CC BY-SA 3.0


问:
code coverage in squish for JAVA
I am using Squish for JAVA. I was wondering whether is it possible to test the code coverage of the Application Under Test(AUT) using Squish(for JAVA). Any help would be much appreciated.

Best regards,
Amal

答:
You may use JaCoco with Squish.
See Squish's JaCoCo article here.</p>

Title: code coverage in squish for JAVA


问:
keyframe animation not playing after clicking link
I have a full screen drop down menu that goes up and down the screen when the user interacts with the menu button. I didn't like that the full screen menu animates when the page loads so I set the opacity of the menu to 0 so that you wouldn't see the animation when the page loads. I created an onclick event that sets the opacity to 1 when the user clicks on the menu. that solved the issue of seeing the animation when the user loads the index page. here's the code for how I did it:

HTML

```<code><div class="menu">
    <input type="checkbox" class="toggler" onclick="document.getElementById('overlay').style.opacity='1'">

    <div class="icon">
        <div></div>
    </div>

    <div class="overlay" id="overlay">

        <nav>
            <div id="nav-links"></div>
        </nav>
    </div>
</div>
</code>```

CSS

```<code>@keyframes slideDown {
0% {
    transform: translateY(-100%)
    }

100% {
    transform: translateY(0%)
    }
}

@keyframes slideUp {
0% {
    transform: translateY(0%)
    }

100% {
    transform: translateY(-100%);
    }
}

.overlay {
position: fixed;
background: var(--taupe-color);
opacity: 0;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}

.menu .toggler:checked ~ .overlay {
animation: slideDown 2s forwards;
}

.menu .toggler:not(:checked) ~ .overlay {
animation: slideUp 2s forwards;
}
</code>```

The only issue now is that when the user clicks on a link to navigate to another page from the menu, the menu no longer animates up. My guess is that on page load, the opacity over the overlay menu is set back to 0 so we can't see the animation actually happening on the other pages. My only idea to fix this is to duplicate the overlay class for the other pages and give it a different name but set the opacity to 1. I'm wondering if there is a better solution than the one I came up with. Ideally, the animation only happens when a link is clicked in the menu or when the menu button is toggled.

EDIT
is there a way to have the menu animate only when the user clicks the menu button or clicks one of the nav links in the menu?

答:
I would suggest maybe adding a class to turn the opacity to 1 upon clicking?

I'm not sure if this is what you are looking for, but here is Codepen that I believe does what you're looking for:

@keyframes slideDown {
0% {
    transform: translateY(-100%)
    }

100% {
    transform: translateY(0%)
    }
}

@keyframes slideUp {
0% {
    transform: translateY(0%)
    }

100% {
    transform: translateY(-100%);
    }
}

.overlay {
position: fixed;
background: var(--taupe-color);
opacity: 0;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}

.active {
  opacity:1;
}

.menu .toggler:checked ~ .overlay {
animation: slideDown 2s forwards;
}

.menu .toggler:not(:checked) ~ .overlay {
animation: slideUp 2s forwards;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
    <input type="checkbox" class="toggler" onclick="document.getElementById('overlay').classList.add('active')">

    <div class="icon">
        <div></div>
    </div>

    <div class="overlay" id="overlay">

        <nav>
            <div id="nav-links"></div>
          TESTTTTTTTTTTTT
        </nav>
    </div>
</div></code>```

Body:
I have a full screen drop down menu that goes up and down the screen when the user interacts with the menu button. I didn't like that the full screen menu animates when the page loads so I set the opacity of the menu to 0 so that you wouldn't see the animation when the page loads. I created an onclick event that sets the opacity to 1 when the user clicks on the menu. that solved the issue of seeing the animation when the user loads the index page. here's the code for how I did it:

HTML

    <input type="checkbox" class="toggler" onclick="document.getElementById('overlay').style.opacity='1'">

CSS

@keyframes slideDown {
0% {
    transform: translateY(-100%)
    }

100% {
    transform: translateY(0%)
    }
}

@keyframes slideUp {
0% {
    transform: translateY(0%)
    }

100% {
    transform: translateY(-100%);
    }
}

.overlay {
position: fixed;
background: var(--taupe-color);
opacity: 0;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}

.menu .toggler:checked ~ .overlay {
animation: slideDown 2s forwards;
}

.menu .toggler:not(:checked) ~ .overlay {
animation: slideUp 2s forwards;
}

The only issue now is that when the user clicks on a link to navigate to another page from the menu, the menu no longer animates up. My guess is that on page load, the opacity over the overlay menu is set back to 0 so we can't see the animation actually happening on the other pages. My only idea to fix this is to duplicate the overlay class for the other pages and give it a different name but set the opacity to 1. I'm wondering if there is a better solution than the one I came up with. Ideally, the animation only happens when a link is clicked in the menu or when the menu button is toggled.

EDIT
is there a way to have the menu animate only when the user clicks the menu button or clicks one of the nav links in the menu?

Body:
I would suggest maybe adding a class to turn the opacity to 1 upon clicking?

I'm not sure if this is what you are looking for, but here is Codepen that I believe does what you're looking for:

@keyframes slideDown {
0% {
    transform: translateY(-100%)
    }

100% {
    transform: translateY(0%)
    }
}

@keyframes slideUp {
0% {
    transform: translateY(0%)
    }

100% {
    transform: translateY(-100%);
    }
}

.overlay {
position: fixed;
background: var(--taupe-color);
opacity: 0;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}

.active {
  opacity:1;
}

.menu .toggler:checked ~ .overlay {
animation: slideDown 2s forwards;
}

.menu .toggler:not(:checked) ~ .overlay {
animation: slideUp 2s forwards;
}

<div class="menu">
    <input type="checkbox" class="toggler" onclick="document.getElementById('overlay').classList.add('active')">

    <div class="icon">
        <div></div>
    </div>

    <div class="overlay" id="overlay">

        <nav>
            <div id="nav-links"></div>
          TESTTTTTTTTTTTT
        </nav>
    </div>
</div>


问:
“Robo 3T” cannot be opened because the developer cannot be verified
I have installed the Robo 3T using the Homebrew tool.

```<code>brew install --cask robo-3t
</code>```

after installing I am getting pop-up windows asking on macOS.

“Robo 3T” cannot be opened because the developer cannot be verified.

答:
This worked for me:

Finder > Applications > Robo3t > right click (two fingers) > Open

Body:
I have installed the Robo 3T using the Homebrew tool.

brew install --cask robo-3t

after installing I am getting pop-up windows asking on macOS.

“Robo 3T” cannot be opened because the developer cannot be verified.


问:
How to select a cell based on the current month in excel
I'm looking for some excel help.
I am trying to make a total cell that changes the value selected based on what month it currently is. Basically in the image the left cell indicates the $ amount for that month and that $ amount is in the cells on the right.

For example I want the total cell (not shown in the screenshot) to show 15363.21 from March 1 to 31st, and then change to 15388.81 on April 1st.

I have done some research but can't get this to work for me.

Pretending month is march Pretending month is April

答:
It seems like you are asking for a lookup: "find the single cell in Column A that contains the current month and year, then return the corresponding single cell in Column F."

There are several ways to do this, but assuming your Excel version supports XLOOKUP, the code to place inside your total cell could be:

```<code>=XLOOKUP(1,(MONTH($A$4:$A$11)=MONTH(TODAY()))*(YEAR($A$4:$A$11)=YEAR(TODAY())),$F$4:$F$11)
</code>```

Body:
It seems like you are asking for a lookup: "find the single cell in Column A that contains the current month and year, then return the corresponding single cell in Column F."

There are several ways to do this, but assuming your Excel version supports XLOOKUP, the code to place inside your total cell could be:

=XLOOKUP(1,(MONTH($A$4:$A$11)=MONTH(TODAY()))*(YEAR($A$4:$A$11)=YEAR(TODAY())),$F$4:$F$11)


问:
Operation returned an invalid status code 'NotFound' DotNet Core
I am working on DOT 5.0 Version. (CORE MVC Application).

While uploading my file in Azure (During Encoding) Facing an Error.

```<code>Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName,
                                            outputAssetName, uploadedAsset.Description);
</code>```
```<code>private static async Task<Asset> CreateOutputAssetAsync(IAzureMediaServicesClient client,
            string resourceGroupName, string accountName, string assetName, string assetDescription)
        {
            // Check if an Asset already exists
            Asset outputAsset = await client.Assets.GetAsync(resourceGroupName, accountName, assetName);
string outputAssetName = assetName;
Asset asset = new Asset()
            {
                Description = "Encoded-" + assetDescription,
                StorageAccountName = "MyStoarestorage"
           };
           return await client.Assets.CreateOrUpdateAsync(resourceGroupName, accountName, outputAssetName, asset);
        }
</code>```

The line await the client.Assets.GetAsync failed.
Did I have missed any packages?
Follow the below URL and Install it.
(https://learn.microsoft.com/en-us/azure/media-services/latest/configure-connect-dotnet-howto).

Please Suggest.
Note:- SAME CODE IS WORKING FINE IN MY DESKTOP APPLICATION And UPLOAD VIDEO WITH ENCODING IN AZURE. but When to apply the SAME CODE .NET 5.0 CORE MVC Application some how it is not working

答:
In Microsoft.Azure.Manangement.Media version 5.0, we have a breaking change for get functions trying to retrieve non-existing assets (source):

All calls returning 404 Not found raises an ErrorResponseException instead of returning null. This change was make to be consistent with other Azure SDKs.

Can you check if you are using an older version of the library in your desktop application? That might be the reason for the difference in behavior.

Body:
I am working on DOT 5.0 Version. (CORE MVC Application).

While uploading my file in Azure (During Encoding) Facing an Error.

Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName,
                                            outputAssetName, uploadedAsset.Description);

private static async Task<Asset> CreateOutputAssetAsync(IAzureMediaServicesClient client,
            string resourceGroupName, string accountName, string assetName, string assetDescription)
        {
            // Check if an Asset already exists
            Asset outputAsset = await client.Assets.GetAsync(resourceGroupName, accountName, assetName);
string outputAssetName = assetName;
Asset asset = new Asset()
            {
                Description = "Encoded-" + assetDescription,
                StorageAccountName = "MyStoarestorage"
           };
           return await client.Assets.CreateOrUpdateAsync(resourceGroupName, accountName, outputAssetName, asset);
        }

The line await the client.Assets.GetAsync failed.
Did I have missed any packages?
Follow the below URL and Install it.
(https://learn.microsoft.com/en-us/azure/media-services/latest/configure-connect-dotnet-howto).

Please Suggest.
Note:- SAME CODE IS WORKING FINE IN MY DESKTOP APPLICATION And UPLOAD VIDEO WITH ENCODING IN AZURE. but When to apply the SAME CODE .NET 5.0 CORE MVC Application some how it is not working


问:
ReactJS how to close select dropdown on state change
I have doubts how to close the select dropdown on screen orientation change. For now I have  the listener that handles the state when the orientation is changed:

```<code>const [orientation, setOrientation] = useState('portrait');

useEffect(() => {
    window.addEventListener('orientationchange', setScreenOrientation)
    return () => {
      document.removeEventListener('orientationchange', setScreenOrientation)
    }
  }, [])

const setScreenOrientation = () => {
    if(window.matchMedia("(orientation: portrait)").matches){
      console.log('orientation: portrait');
      setOrientation('portrait');
    }

    if(window.matchMedia("(orientation: landscape)").matches){
      console.log('orientation: landscape');
      setOrientation('landscape');
    }
  }

 return (<Dropdown
          options={data}
          center
          onSelect={handleSelect}
          value={data.store_id}
          selected="key"
          screenOrientation={screenOrientation}
        />)
</code>```

Dropdown component

```<code>import React, { useEffect } from 'react';
import classnames from 'classnames';
import styles from './styles.module.scss';

export const Dropdown = ({
  options,
  center,
  onSelect,
  value,
  selected,
  screenOrientation
}) => {

  return (
    <div
      className={classnames(
        styles.dropdown
      )}
    >
      <select
        onChange={onSelect}
        value={value}
      >
        {options &&
          Object.entries(options)
            .map(([k, v]) => (
              <option
                key={v}
                value={selected === 'key' ? k : v}
              >
                {v}
              </option>
            ))}
      </select>
    </div>
  );
};
</code>```

But I don't know how to imlement this functionality when the screen is changed to close the dropdown if it's opened?

Thanks in advance.

答:
Use the orientation variable in the bracket</p>
```<code>    useEffect(() => {
        window.addEventListener('orientationchange', setScreenOrientation)
        return () => {
             document.removeEventListener('orientationchange', setScreenOrientation)
     }
     }, [orientation])
</code>```

Body:
I have doubts how to close the select dropdown on screen orientation change. For now I have  the listener that handles the state when the orientation is changed:

const [orientation, setOrientation] = useState('portrait');

useEffect(() => {
    window.addEventListener('orientationchange', setScreenOrientation)
    return () => {
      document.removeEventListener('orientationchange', setScreenOrientation)
    }
  }, [])

const setScreenOrientation = () => {
    if(window.matchMedia("(orientation: portrait)").matches){
      console.log('orientation: portrait');
      setOrientation('portrait');
    }

    if(window.matchMedia("(orientation: landscape)").matches){
      console.log('orientation: landscape');
      setOrientation('landscape');
    }
  }

 return (<Dropdown
          options={data}
          center
          onSelect={handleSelect}
          value={data.store_id}
          selected="key"
          screenOrientation={screenOrientation}
        />)

Dropdown component

import React, { useEffect } from 'react';
import classnames from 'classnames';
import styles from './styles.module.scss';

export const Dropdown = ({
  options,
  center,
  onSelect,
  value,
  selected,
  screenOrientation
}) => {

  return (

      <select
        onChange={onSelect}
        value={value}
      >
        {options &&
          Object.entries(options)
            .map(([k, v]) => (
              <option
                key={v}
                value={selected === 'key' ? k : v}
              >
                {v}
              </option>
            ))}
      </select>

  );
};

But I don't know how to imlement this functionality when the screen is changed to close the dropdown if it's opened?

Thanks in advance.

Body:
Use the orientation variable in the bracket

    useEffect(() => {
        window.addEventListener('orientationchange', setScreenOrientation)
        return () => {
             document.removeEventListener('orientationchange', setScreenOrientation)
     }
     }, [orientation])


问:
In Java Swing (using swingx) how to sort rows in one table in same order as another table
I have a table with x num of rows, I have a second table with the same number of rows but different columns and metadata, they have different table models. but each row represents the same object (a song).

I want to synchronize row sorting between the two tables so for example if I sort on column 2 of table 1 then rows of the table will be sorted in the same order. But currently, I just have sorted by matching sort keys so sort on the same column (but because different data get different results)

e.g

Starting point

```<code>Table 1
1    tom
2    jane
3    fred
4    steve
5    jim

Table 2
1    oranges
2    apples
3    pears
4    lemons
5    plums
</code>```

If I sort by table 1, column 2 Ascending I want to get

```<code>Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
5    plums
3    pears
4    lemons
1    oranges
</code>```

but I get

```<code>Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
4    lemons
1    oranges
3    pears
5    plums
</code>```

My sorting is done by calling setSortKeys() on table 2 to the getSortKeys() of table 1 and vice versa. I can see why it doesn't work, I am telling table 2 to sort by column 2 ascending the same as table 1 but of course these columns have different data in each table. But I can't work out a way to get table 2 to sort to the final order of table 1 instead.

One solution would be for both tables to share the same table model and just show the columns relevant to their table, but that would require a major rework of the code, so I am hoping for a more specific solution just to resolve the sorting issue.

I am using Java 11, and swingx latest version 1.6.4 (i know very old)  but this delegates sorting to standard Java (earlier version that I was previously using had its own sorting) so not really a swingx question.

The real world situation, within my application is as follows, each row represents a song, and the tabs show metadata for that song. the tabs under the edit menu all share same model and all work using the setSortKeys() method described above. So here i have sorted on Mood Aggressive column

Edit metadata tab

and if I go to another tab, we see the rows are sorted in same order

Another Edit metadata tab, sorted same order

but if I go to the Edit ID3 tab, we see the rows have been sorted in different order.

ID3 Edit tab sorted different order

This is because ID3 Edit tab shows the metadata in different format (ID3) and has different table model so column x represent in the model stores different data.

Note because all models store the rowno in first column, sorting my the rowno column works for all tabs.

So from a user point of view they are just viewing different tabs of the same table, and therefore would expect sort to be consistent for the tabs

答:
I came up with the following approach which translates rowIndex for the second table using rowSorter of the first table.

```<code>    TableOneModel tableOneData = new TableOneModel( /* omitted */ );
    JTable tableOne = new JTable(tableOneData);
    TableRowSorter<TableOneModel> sorterOne = new TableRowSorter<>(tableOneData);
    tableOne.setRowSorter(sorterOne);

    TableTwoModel tableTwoData = new TableTwoModel(
            /* omitted */,
            sorterOne);
    JTable tableTwo = new JTable(tableTwoData);
</code>```

The model for the first table, TableOneModel, is a subclass of AbstractTableModel implementing the required methods:

```<code>private static class TableOneModel extends AbstractTableModel {
    private final String[] columnNames;
    private final Object[][] data;

    public TableOneModel(String[] columnNames, Object[][] data) {
        this.columnNames = columnNames;
        this.data = data;
    }

    public int getRowCount() { return data.length; }

    public int getColumnCount() { return columnNames.length; }

    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }
}
</code>```

The model for second table, TableTwoModel, stores the reference to the rowSorter of the first table to do the translation of row indexes:

```<code>private static class TableTwoModel extends TableOneModel
        implements RowSorterListener {

    private final RowSorter<? extends TableModel> otherSorter;

    public TableTwoModel(String[] columnNames, Object[][] data,
                         RowSorter<? extends TableModel> sorter) {
        super(columnNames, data);
        this.otherSorter = sorter;
        installListeners();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return super.getValueAt(
                otherSorter.convertRowIndexToModel(rowIndex),
                columnIndex);
    }

    private void installListeners() {
        otherSorter.addRowSorterListener(this);
    }

    @Override
    public void sorterChanged(RowSorterEvent e) {
        fireTableDataChanged();
    }
}
</code>```

When the sorting order of the first table changes, the second table model calls fireTableDataChanged() to notify the view it needs to update all the data.

Edit: As Paul mentioned in the comment, the sort order of the second table should also change the first table. So the sync should work both ways.

In the updated version, both tables use TableTwoModel and the first table identifies itself as the leading one. (Just as I've been writing the update, I realised this wasn't necessary.) Thus, the implementation of TableTwoModel remains basically unchanged. I changed sorterChanged in TableTwoModel to call fireTableDataChanged() only for SORTED event type that is when the sorting of the table is complete. It's a little optimisation.

The tricky part was to sync/reset RowSorter of the tables. However, the solution proved to be pretty simple. This is achieved by installing RowSorterListener to each row sorter. If the event type is SORT_ORDER_CHANGED and the list of sort keys of this RowSorter is non-empty, the sort keys of the other are set to null. Thus, only one table is sorted and the other follows the sort order of the sorted one.

Body:
I have a table with x num of rows, I have a second table with the same number of rows but different columns and metadata, they have different table models. but each row represents the same object (a song).

I want to synchronize row sorting between the two tables so for example if I sort on column 2 of table 1 then rows of the table will be sorted in the same order. But currently, I just have sorted by matching sort keys so sort on the same column (but because different data get different results)

e.g

Starting point

Table 1
1    tom
2    jane
3    fred
4    steve
5    jim

Table 2
1    oranges
2    apples
3    pears
4    lemons
5    plums

If I sort by table 1, column 2 Ascending I want to get

Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
5    plums
3    pears
4    lemons
1    oranges

but I get

Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
4    lemons
1    oranges
3    pears
5    plums

My sorting is done by calling setSortKeys() on table 2 to the getSortKeys() of table 1 and vice versa. I can see why it doesn't work, I am telling table 2 to sort by column 2 ascending the same as table 1 but of course these columns have different data in each table. But I can't work out a way to get table 2 to sort to the final order of table 1 instead.

One solution would be for both tables to share the same table model and just show the columns relevant to their table, but that would require a major rework of the code, so I am hoping for a more specific solution just to resolve the sorting issue.

I am using Java 11, and swingx latest version 1.6.4 (i know very old)  but this delegates sorting to standard Java (earlier version that I was previously using had its own sorting) so not really a swingx question.

The real world situation, within my application is as follows, each row represents a song, and the tabs show metadata for that song. the tabs under the edit menu all share same model and all work using the setSortKeys() method described above. So here i have sorted on Mood Aggressive column

Edit metadata tab

and if I go to another tab, we see the rows are sorted in same order

Another Edit metadata tab, sorted same order

but if I go to the Edit ID3 tab, we see the rows have been sorted in different order.

ID3 Edit tab sorted different order

This is because ID3 Edit tab shows the metadata in different format (ID3) and has different table model so column x represent in the model stores different data.

Note because all models store the rowno in first column, sorting my the rowno column works for all tabs.

So from a user point of view they are just viewing different tabs of the same table, and therefore would expect sort to be consistent for the tabs

Body:
I came up with the following approach which translates rowIndex for the second table using rowSorter of the first table.

    TableOneModel tableOneData = new TableOneModel( /* omitted */ );
    JTable tableOne = new JTable(tableOneData);
    TableRowSorter<TableOneModel> sorterOne = new TableRowSorter<>(tableOneData);
    tableOne.setRowSorter(sorterOne);

    TableTwoModel tableTwoData = new TableTwoModel(
            /* omitted */,
            sorterOne);
    JTable tableTwo = new JTable(tableTwoData);

The model for the first table, TableOneModel, is a subclass of AbstractTableModel implementing the required methods:

private static class TableOneModel extends AbstractTableModel {
    private final String[] columnNames;
    private final Object[][] data;

    public TableOneModel(String[] columnNames, Object[][] data) {
        this.columnNames = columnNames;
        this.data = data;
    }

    public int getRowCount() { return data.length; }

    public int getColumnCount() { return columnNames.length; }

    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }
}

The model for second table, TableTwoModel, stores the reference to the rowSorter of the first table to do the translation of row indexes:

private static class TableTwoModel extends TableOneModel
        implements RowSorterListener {

    private final RowSorter<? extends TableModel> otherSorter;

    public TableTwoModel(String[] columnNames, Object[][] data,
                         RowSorter<? extends TableModel> sorter) {
        super(columnNames, data);
        this.otherSorter = sorter;
        installListeners();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return super.getValueAt(
                otherSorter.convertRowIndexToModel(rowIndex),
                columnIndex);
    }

    private void installListeners() {
        otherSorter.addRowSorterListener(this);
    }

    @Override
    public void sorterChanged(RowSorterEvent e) {
        fireTableDataChanged();
    }
}

When the sorting order of the first table changes, the second table model calls fireTableDataChanged() to notify the view it needs to update all the data.

Edit: As Paul mentioned in the comment, the sort order of the second table should also change the first table. So the sync should work both ways.

In the updated version, both tables use TableTwoModel and the first table identifies itself as the leading one. (Just as I've been writing the update, I realised this wasn't necessary.) Thus, the implementation of TableTwoModel remains basically unchanged. I changed sorterChanged in TableTwoModel to call fireTableDataChanged() only for SORTED event type that is when the sorting of the table is complete. It's a little optimisation.

The tricky part was to sync/reset RowSorter of the tables. However, the solution proved to be pretty simple. This is achieved by installing RowSorterListener to each row sorter. If the event type is SORT_ORDER_CHANGED and the list of sort keys of this RowSorter is non-empty, the sort keys of the other are set to null. Thus, only one table is sorted and the other follows the sort order of the sorted one.


问:
Custom Liferay DDMFormFieldType won't appear in Rules Dataprovider Inputs
I wrote a custom Liferay 7.3 DDMFormFieldType which is mostly a text input field. I used the 7.3 blade example component and slightly modified the generated Soy template.
Basically, everything works fine. I can use my field inside a Liferay Forms. But I can't use this field inside a FormRule as Input parameter for dataproviders.
I thinks this is maybe due to a type mismatch (dataprovider input type is 'text'), but I don't know how to configure this for my fieldtype. What do I need to code in my custom fieldtype, so that it can be used for dataprovider inputs?

答: I am having a similar issue too. I have found that liferay is looking for specific hard-coded field types such as select, checkbox etc. I don't know if this was fixed in 7.4.</p>


问:
Make an array with every character on keyboard
I want to make an array containing all the letters and numbers on the keyboard (+ !, @, #, $, %, &, etc.) via code, without declaring it. Is there any way to do this in js?</p>

答:
This will give characters that are displayable on the screen.</p>
```<code>let characters = [];

for (let i=32; i<127; i++)
  characters.push( String.fromCharCode(i) );
</code>```

Body:
This will give characters that are displayable on the screen.

let characters = [];

for (let i=32; i<127; i++)
  characters.push( String.fromCharCode(i) );


问:
Can I loop multiple lines of code and save each output?
I'm testing the accuracy of linear regression models with training and test data, and I would like to be able to run the code 100 times and save the MAPE output in a table or file so I can have a decent error% for the training model. How do I loop the code from the line of sample_size to the line of MAPE and keep each output?</p>
```<code>library('tidyverse')
library("ggplot2")
library("readxl")
library("writexl")
library('dplyr')
library('Rmisc')
library('cowplot')
library('purrr')
library('caTools')
library('MLmetrics')
##2008 Set
Bird<-c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10)
Age<-c(10,17,27,10,17,28,10,17,27,10,17,27,10,17,28,10,17,28,10,17,28,10,17,28,10,17,28,11,18,28)
Wing<-c(39,63,98,34,61,99,34,48,80,30,37,65,35,51,71,40,55,79,34,47,77,36,55,84,35,55,88,36,59,74)
Set08<-data.frame(Bird, Age, Wing) %>%
  group_by(Bird)
Set08$Bird<-as.factor((Set08$Bird))
Set08

sample_size = floor(0.7*nrow(Set08))

picked = sample(seq_len(nrow(Set08)),size = sample_size)

Training =Set08[picked,]
Training
Test =Set08[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

MAPE(error$actual, error$calculated)

</code>```

答:
If you want to do it as a loop, this should give you a vector of the 100 results:</p>
```<code>results<-list()
for (i in 1:100){

sample_size = floor(0.7*nrow(Set08))

picked = sample(seq_len(nrow(Set08)),size = sample_size)

Training =Set08[picked,]
Training
Test =Set08[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

results[[i]] <- MAPE(error$actual, error$calculated)

}

list_of_results <- unlist(results)
</code>```

Body:
I'm testing the accuracy of linear regression models with training and test data, and I would like to be able to run the code 100 times and save the MAPE output in a table or file so I can have a decent error% for the training model. How do I loop the code from the line of sample_size to the line of MAPE and keep each output?

library('tidyverse')
library("ggplot2")
library("readxl")
library("writexl")
library('dplyr')
library('Rmisc')
library('cowplot')
library('purrr')
library('caTools')
library('MLmetrics')
##2008 Set
Bird<-c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10)
Age<-c(10,17,27,10,17,28,10,17,27,10,17,27,10,17,28,10,17,28,10,17,28,10,17,28,10,17,28,11,18,28)
Wing<-c(39,63,98,34,61,99,34,48,80,30,37,65,35,51,71,40,55,79,34,47,77,36,55,84,35,55,88,36,59,74)
Set08<-data.frame(Bird, Age, Wing) %>%
  group_by(Bird)
Set08$Bird<-as.factor((Set08$Bird))
Set08

sample_size = floor(0.7*nrow(Set08))

picked = sample(seq_len(nrow(Set08)),size = sample_size)

Training =Set08[picked,]
Training
Test =Set08[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

MAPE(error$actual, error$calculated)

Body:
If you want to do it as a loop, this should give you a vector of the 100 results:

results<-list()
for (i in 1:100){

sample_size = floor(0.7*nrow(Set08))

picked = sample(seq_len(nrow(Set08)),size = sample_size)

Training =Set08[picked,]
Training
Test =Set08[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

results[[i]] <- MAPE(error$actual, error$calculated)

}

list_of_results <- unlist(results)


问:
Run python script on Database event
I'm running a python script that makes modifications in a specific database.
I want to run a second script once there is a modification in my database (local server).

Is there anyway to do that?

Any help would be very appreciated.
Thanks!

答:
And if what you need is to keep the python script running and listen to changes in a certain table.

You can create a listener table ex. 'trigger_table' in your database with only one value.

Create a trigger that will change the value in the 'trigger_table' table every time a change occurs in some table.

And last create a python script that will check this table if the value has been changed every n-seconds (depending how fast you need updates) taking into consideration that its only one value and you have a good internet connection (If the database is online), everything should be running quite fast. And execute a function when the value has been changed.

Create MqSQL trigger: https://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx

This is the SQL Code (Btw I am working with MS SQL but you should get the idea about how it should be set-up):

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER dbo.new
   ON  dbo.rc
   AFTER INSERT,DELETE,UPDATE
AS

--Declare the variable and set the value from the change_table
DECLARE @PurchaseName AS CHAR(1)
SELECT @PurchaseName = _check
FROM dev.dbo.change_table
WHERE _check_1 IS NOT NULL

IF @PurchaseName = 'Y'
BEGIN
  -- If the condition is TRUE then execute the following statement
  UPDATE dev.dbo.change_table SET _check = 'N' WHERE _check_1 IS NOT NULL
END
ELSE
BEGIN
   -- If the condition is False then execute the following statement
    UPDATE dev.dbo.change_table SET _check = 'Y' WHERE _check_1 IS NOT NULL
END
GO

```
<p>The change_table has only two columns and one row- see the picture below.</p>
<p>change_table picture</p>
<p>This is the python code:</p>
<pre class="lang-py prettyprint-override"><code>import pyodbc
import pandas as pd

# Connect to SQL Server
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=<YOUR SERVER>;DATABASE=<YOUR DATABASE>;UID=<YOUR USER ID>;PWD=<YOUR PASSWORD>')
previous_value = ""
while True:
    current_value = str(pd.read_sql_query('SELECT _check FROM change_table',cnxn)['_check'].tolist()[0])
    if current_value != previous_value:
        prev_value = current_value
        #Write your code here
</code>```

The SQL code above will change the value in the change_table on every INSERT, UPDATE or DELETE in the 'rc' table, while the python code will check the value 8 times every second to see if a change has happen.
Btw that 8 times per second is on a 100MB/s optic internet and the server is on the other side of the Earth, sooo... it should do the job.

Title: Run python script on Database event

Body:
And if what you need is to keep the python script running and listen to changes in a certain table.

You can create a listener table ex. 'trigger_table' in your database with only one value.

Create a trigger that will change the value in the 'trigger_table' table every time a change occurs in some table.

And last create a python script that will check this table if the value has been changed every n-seconds (depending how fast you need updates) taking into consideration that its only one value and you have a good internet connection (If the database is online), everything should be running quite fast. And execute a function when the value has been changed.

Create MqSQL trigger: https://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx

This is the SQL Code (Btw I am working with MS SQL but you should get the idea about how it should be set-up):

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER dbo.new
   ON  dbo.rc
   AFTER INSERT,DELETE,UPDATE
AS

--Declare the variable and set the value from the change_table
DECLARE @PurchaseName AS CHAR(1)
SELECT @PurchaseName = _check
FROM dev.dbo.change_table
WHERE _check_1 IS NOT NULL

IF @PurchaseName = 'Y'
BEGIN
  -- If the condition is TRUE then execute the following statement
  UPDATE dev.dbo.change_table SET _check = 'N' WHERE _check_1 IS NOT NULL
END
ELSE
BEGIN
   -- If the condition is False then execute the following statement
    UPDATE dev.dbo.change_table SET _check = 'Y' WHERE _check_1 IS NOT NULL
END
GO

The change_table has only two columns and one row- see the picture below.

change_table picture

This is the python code:

import pyodbc
import pandas as pd

# Connect to SQL Server
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=<YOUR SERVER>;DATABASE=<YOUR DATABASE>;UID=<YOUR USER ID>;PWD=<YOUR PASSWORD>')
previous_value = ""
while True:
    current_value = str(pd.read_sql_query('SELECT _check FROM change_table',cnxn)['_check'].tolist()[0])
    if current_value != previous_value:
        prev_value = current_value
        #Write your code here

The SQL code above will change the value in the change_table on every INSERT, UPDATE or DELETE in the 'rc' table, while the python code will check the value 8 times every second to see if a change has happen.
Btw that 8 times per second is on a 100MB/s optic internet and the server is on the other side of the Earth, sooo... it should do the job.


问:
Is there a way to theoretically concatenate two names to make a variable name that is already defined?
The objective of this code is basically to create dynamically named variables automatically at runtime, more specifically lists then loop through range of values based on how many lists I have then display them out as such. It seems to work when I define the variable I'm printing out as such

```<code>listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

print(my_list0)
</code>```

But when I try to loop through them so that I can display them it doesn't seem to work, giving me an error NameError: name 'my_list' is not defined

```<code>listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

for i in range(listNum):
    print(f"{my_list}+{i}")
</code>```

What may I be missing, because i'm trying to concatenate my_list with the value in the range so it can print out the variable that is there?

答:
Dictionary keys are pretty much "variable names you can create at runtime":

human_knowledge = {}

for _ in range(5):
    name = input("What is your name? ")
    quest = input("What is your quest? ")
    colour = input("What is your favourite colour? ")

    human_knowledge[name + quest] = colour
```

Body:
The objective of this code is basically to create dynamically named variables automatically at runtime, more specifically lists then loop through range of values based on how many lists I have then display them out as such. It seems to work when I define the variable I'm printing out as such

listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

print(my_list0)

But when I try to loop through them so that I can display them it doesn't seem to work, giving me an error NameError: name 'my_list' is not defined

listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

for i in range(listNum):
    print(f"{my_list}+{i}")

What may I be missing, because i'm trying to concatenate my_list with the value in the range so it can print out the variable that is there?


问:
JavaScript: Generating a random number with user input from a prompt box (number guess game)
The user has to guess a randomly generated number based on the highest value THEY input into a prompt box. Example (from 1 to ?)
I have to use a prompt and the value cannot be a decimal or string.
I'm not sure how to validate that or just not allow the user to input an invalid entry.

I am having issues reusing the number they input in the function for random number generation let num = Math.floor(Math.random() * inputMaxNumber + 1); in the game. I tried converting the value from a string to a number but that didn't work either.
This is what I have so far:

//prompt for max number the user inputs
function maxNumber() {

    let inputMaxNumber = prompt ("Enter the maximum number the game can pick", " #");
    if ( inputMaxNumber > 1) {
        document.getElementById("maxNumber").innerHTML = "Guess a number between 1 and " + inputMaxNumber;

        }
    else {
        alert("You must enter a positive whole number greater than 1");
    }

    console.log(inputMaxNumber);

}

inputMaxNumber = Number(document.getElementById("maxNumber").value); //converts this to a number from a string

// array that stores guesses
var numGuessArray = []

//validates user input for guesses (no decimals, strings, or negative numbers)
function onlyNumbers(num){
    if ( /[^0-9]+/.test(num.value) ){
       num.value = num.value.replace(/[^0-9]*/g,"")
    }
 }

//get user input to use in random number generation

// random value generated based on user input (a) new variable is num
let num = Math.floor(Math.random() * inputMaxNumber + 1);

console.log(num);
//counts the number of guesses for correct guess
var guess = 1;

//store counts and numbers guess in an array (don't count invalid guesses)

function do_guess() {

    let guess = Number(document.getElementById("guess").value); //converts this to a number from a string

    let message = document.getElementById("message");

    //show on console
    console.log(guess);

    //hints about guess

    if(guess == num) { //correct guess with count
        message.innerHTML = "You got it and it took " + guess + " guess!";
    }
    else if (guess > num) { //number too high
         message.innerHTML = "No, try a lower number";
    }
    else {//number too low
        message.innerHTML = "No, try a higher number";
    }

    //you already guessed that number NO COUNT

}
//guess button used to guess
//use an array to keep track of the guess```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="container">
    <h1>Higher - Lower</h1>
        <p>Guess a number</p>
        <div class = "row">
            <div class ="col-lg-3 col-md-6">
                <form>
                <div class ="form-group">
                    <!-- This button triggers the prompt to allow the user to enter the max number-->
                    <input type ="button" value = "Click To Start" onclick = "maxNumber()";/>
                </div>

                <div class ="form-group">
                    <label> Your Guess:</label>
                    <!-- Prevents user from inputing decimals with onkeyup-->
                    <input type ="text" onkeyup="onlyNumbers(this)" id="guess" class ="form-control">
                </div>

                <p id = "maxNumber" ></p><!--Outputs maximum number range the user selected-->
                <!--Button calls guess funciton when clicked-->
                <button type="button" class ="btn btn-primary" onclick = "do_guess()">Guess</button>
            </form>
        </div>
    </div>
        <p id="message"></p> <!--Where message will go-->
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script></code>```

答:
Inside function maxNumber() you define inputMaxNumber locally let inputMaxNumber = prompt(...); so its value is lost when the function execution ends.

Additionally, the code where you generate the random number is executed only once, upon page load let num = Math.floor(...);. It's not executed after user enters his choice for the maximum.

Solution:

define num globally

assign the random value to it inside maxNumber()

Body:
The user has to guess a randomly generated number based on the highest value THEY input into a prompt box. Example (from 1 to ?)
I have to use a prompt and the value cannot be a decimal or string.
I'm not sure how to validate that or just not allow the user to input an invalid entry.

I am having issues reusing the number they input in the function for random number generation let num = Math.floor(Math.random() * inputMaxNumber + 1); in the game. I tried converting the value from a string to a number but that didn't work either.
This is what I have so far:

//prompt for max number the user inputs
function maxNumber() {

    let inputMaxNumber = prompt ("Enter the maximum number the game can pick", " #");
    if ( inputMaxNumber > 1) {
        document.getElementById("maxNumber").innerHTML = "Guess a number between 1 and " + inputMaxNumber;

        }
    else {
        alert("You must enter a positive whole number greater than 1");
    }

    console.log(inputMaxNumber);

}

inputMaxNumber = Number(document.getElementById("maxNumber").value); //converts this to a number from a string

// array that stores guesses
var numGuessArray = []

//validates user input for guesses (no decimals, strings, or negative numbers)
function onlyNumbers(num){
    if ( /[^0-9]+/.test(num.value) ){
       num.value = num.value.replace(/[^0-9]*/g,"")
    }
 }

//get user input to use in random number generation

// random value generated based on user input (a) new variable is num
let num = Math.floor(Math.random() * inputMaxNumber + 1);

console.log(num);
//counts the number of guesses for correct guess
var guess = 1;

//store counts and numbers guess in an array (don't count invalid guesses)

function do_guess() {

    let guess = Number(document.getElementById("guess").value); //converts this to a number from a string

    let message = document.getElementById("message");

    //show on console
    console.log(guess);

    //hints about guess

    if(guess == num) { //correct guess with count
        message.innerHTML = "You got it and it took " + guess + " guess!";
    }
    else if (guess > num) { //number too high
         message.innerHTML = "No, try a lower number";
    }
    else {//number too low
        message.innerHTML = "No, try a higher number";
    }

    //you already guessed that number NO COUNT

}
//guess button used to guess
//use an array to keep track of the guess

Higher - Lower

Guess a number

                <form>

                    <input type ="button" value = "Click To Start" onclick = "maxNumber()";/>

                     Your Guess:

                    <input type ="text" onkeyup="onlyNumbers(this)" id="guess" class ="form-control">

                <button type="button" class ="btn btn-primary" onclick = "do_guess()">Guess</button>
            </form>


问:
Bulk move 20000 post_meta value to wp_content with mysql command
I have more than 1 million Wordpress article, I want to achieve the following effect through mysql:

copy the post_meta key value named views to wp_content field.

I know how to insert value from table wp_posts to table wp_postmeta, but how to move value from wp_postmeta to wp_posts?
I used code like this:

```<code>update `wp_posts` p join
       `wp_postmeta` m
       on p.id = m.post_id
    set p.post_content = m.views
    where p.post_status='publish' and m.views != '' limit 1;
</code>```

but get error messge:

ERROR 1054 (42S22): Unknown column 'm.views' in 'where clause'

how to fixed it ? thanks !

答:
```<code>    update `wp_posts` p join
    `wp_postmeta` m
    on p.ID = m.post_id
    set p.post_content = m.meta_value
    where p.post_status='publish'
            AND m.meta_key = 'views'
            AND m.meta_value != '';
</code>```

this works well , but take a long time

Body:
I have more than 1 million Wordpress article, I want to achieve the following effect through mysql:

copy the post_meta key value named views to wp_content field.

I know how to insert value from table wp_posts to table wp_postmeta, but how to move value from wp_postmeta to wp_posts?
I used code like this:

update `wp_posts` p join
       `wp_postmeta` m
       on p.id = m.post_id
    set p.post_content = m.views
    where p.post_status='publish' and m.views != '' limit 1;

but get error messge:

ERROR 1054 (42S22): Unknown column 'm.views' in 'where clause'

how to fixed it ? thanks !

Body:
    update `wp_posts` p join
    `wp_postmeta` m
    on p.ID = m.post_id
    set p.post_content = m.meta_value
    where p.post_status='publish'
            AND m.meta_key = 'views'
            AND m.meta_value != '';

this works well , but take a long time


问:
Multiple messages as Azure function Ouput parameter
It's quite simple to define a output parameter to be inserted in a queue but I have a function that will return multiple messages that I need to insert in a queue.

I'm doing this by adding to the queue directly in the function but I wonder if there is a way of passing multiple messages as an output parameter and what would be the best way to do it?

答:
This is how you do that in the different programming languages:

Azure Queue storage

C# Script

public static void Run(
    CustomQueueMessage input,
    ICollector<CustomQueueMessage> myQueueItems,
    ILogger log)
{
    myQueueItems.Add(input);
    myQueueItems.Add(new CustomQueueMessage { PersonName = "You", Title = "None" });
}
```
<p><strong>Javascript</strong></p>
<pre class="lang-js prettyprint-override"><code>module.exports = function(context) {
    context.bindings.myQueueItem = ["message 1","message 2"];
    context.done();
};
</code>```

PowerShell

```<code>using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$message = @("message1", "message2")
Push-OutputBinding -Name Msg -Value $message
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = 200
    Body = "OK"
})
</code>```

Python

import azure.functions as func
import typing

def main(req: func.HttpRequest, msg: func.Out[typing.List[str]]) -> func.HttpResponse:

    msg.set(['one', 'two'])

    return 'OK'
```
<h2>Azure Service Bus</h2>
<p><strong>C# Script</strong></p>
<pre class="lang-cs prettyprint-override"><code>public static async Task Run(TimerInfo myTimer, ILogger log, IAsyncCollector<string> outputSbQueue)
{
    string message = $"Service Bus queue messages created at: {DateTime.Now}";
    log.LogInformation(message);
    await outputSbQueue.AddAsync("1 " + message);
    await outputSbQueue.AddAsync("2 " + message);
}
</code>```

Javascript

module.exports = function (context, myTimer) {
    var message = 'Service Bus queue message created at ' + timeStamp;
    context.log(message);
    context.bindings.outputSbQueue = [];
    context.bindings.outputSbQueue.push("1 " + message);
    context.bindings.outputSbQueue.push("2 " + message);
    context.done();
};
```

Reference:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-output

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-output

Body:
This is how you do that in the different programming languages:

Azure Queue storage

C# Script

public static void Run(
    CustomQueueMessage input,
    ICollector<CustomQueueMessage> myQueueItems,
    ILogger log)
{
    myQueueItems.Add(input);
    myQueueItems.Add(new CustomQueueMessage { PersonName = "You", Title = "None" });
}

Javascript

module.exports = function(context) {
    context.bindings.myQueueItem = ["message 1","message 2"];
    context.done();
};

PowerShell

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$message = @("message1", "message2")
Push-OutputBinding -Name Msg -Value $message
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = 200
    Body = "OK"
})

Python

import azure.functions as func
import typing

def main(req: func.HttpRequest, msg: func.Out[typing.List[str]]) -> func.HttpResponse:

    msg.set(['one', 'two'])

    return 'OK'

Azure Service Bus

C# Script

public static async Task Run(TimerInfo myTimer, ILogger log, IAsyncCollector<string> outputSbQueue)
{
    string message = $"Service Bus queue messages created at: {DateTime.Now}";
    log.LogInformation(message);
    await outputSbQueue.AddAsync("1 " + message);
    await outputSbQueue.AddAsync("2 " + message);
}

Javascript

module.exports = function (context, myTimer) {
    var message = 'Service Bus queue message created at ' + timeStamp;
    context.log(message);
    context.bindings.outputSbQueue = [];
    context.bindings.outputSbQueue.push("1 " + message);
    context.bindings.outputSbQueue.push("2 " + message);
    context.done();
};

Reference:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-output

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-output


问:
read fucntion in C uint_8 and char array buffer differences
in some code seen online, i saw that in read function in C, someone uses a uint8_t array for buffer insted of a char array buffer.
what are the differences?
thanks

答: So every char corresponds to a number(see ascii table here). I think people use this to avoid some problems(sorry I don't use c I come from c++)</p>


问:
How am I able to check which devices I'm interfacing with?
I work at a microwave technology company and part of my job is developing software to interface with the devices we use using Python, specifically PyVISA. I'm currently trying to write a program that interfaces with several different types of devices that have different command structures, so before executing the code, I want to be able to check which type of device is connected (all use GPIB addresses). How can I go about doing this? Right now I've been trying to send identity commands using nested try/except blocks as shown below because the different devices have different identify commands:

```<code>import pyvisa as visa

address = "GPIB0::6::INSTR"
rm = visa.ResourceManager()
device = rm.open_resource(address)

try:
    device.write("*IDN?")
    identity = device.read()
except visa.errors.VisaIOError:
    try:
        device.write("I")
        device.write("STB?")
        identity = device.read()
    except visa.errors.VisaIOError:
        try:
            device.write("ID?")
            identity = device.read()
        except visa.errors.VisaIOError:
            identity = "Unknown"

print(identity)
</code>```

The device I'm testing the code with requires the device.write("ID?") version of this command, however instead of returning the identity, it's returning the numerical error code. Is there a better way to implement this?

答:
I would remove the try/except block and see exactly where the device is failing. Since you are getting a numerical error code, I'm betting the error flow is as follows:

The script sends *IDN?

The device doesn't recognize this command and goes into an error state.

The script sends I

The device is already in an error state and doesn't respond.

The script queries STB?

The device reports the error it logged earlier.

The script interprets this response as the device name, even though it's the answer to the Status Byte query.

I find it's often better to write the identity function specifically for each device. For example: def identity_dev1() for a device that needs *IDN? and def identity_dev2() for a device that needs I and so on.

If you want a monolithic function that can do all of the above, you'll have to change the way you handle the status byte. Here's an example:

```<code>import pyvisa as visa

address = "GPIB0::6::INSTR"
rm = visa.ResourceManager()
device = rm.open_resource(address)

identity = None
try:
    device.write("*IDN?")
    identity = device.read()
except visa.errors.VisaIOError:
    device.write("*RST") # get rid of the error state and try something else
if not identity:
    try:
        device.write("ID?")
        identity = device.read()
    except visa.errors.VisaIOError:
        device.write("*RST") # get rid of error state
if not identity:
    identity = "Unknown"
</code>```

In general it's better to not do extra try/except behavior over GPIB communication. Trying the wrong command takes extra time and can put the instrument in an error state. In the code above, I use the *RST command to leave the error state, but this isn't guaranteed to work on all tools.
print(identity)

Body:
I work at a microwave technology company and part of my job is developing software to interface with the devices we use using Python, specifically PyVISA. I'm currently trying to write a program that interfaces with several different types of devices that have different command structures, so before executing the code, I want to be able to check which type of device is connected (all use GPIB addresses). How can I go about doing this? Right now I've been trying to send identity commands using nested try/except blocks as shown below because the different devices have different identify commands:

import pyvisa as visa

address = "GPIB0::6::INSTR"
rm = visa.ResourceManager()
device = rm.open_resource(address)

try:
    device.write("*IDN?")
    identity = device.read()
except visa.errors.VisaIOError:
    try:
        device.write("I")
        device.write("STB?")
        identity = device.read()
    except visa.errors.VisaIOError:
        try:
            device.write("ID?")
            identity = device.read()
        except visa.errors.VisaIOError:
            identity = "Unknown"

print(identity)

The device I'm testing the code with requires the device.write("ID?") version of this command, however instead of returning the identity, it's returning the numerical error code. Is there a better way to implement this?

Body:
I would remove the try/except block and see exactly where the device is failing. Since you are getting a numerical error code, I'm betting the error flow is as follows:

The script sends *IDN?

The device doesn't recognize this command and goes into an error state.

The script sends I

The device is already in an error state and doesn't respond.

The script queries STB?

The device reports the error it logged earlier.

The script interprets this response as the device name, even though it's the answer to the Status Byte query.

I find it's often better to write the identity function specifically for each device. For example: def identity_dev1() for a device that needs *IDN? and def identity_dev2() for a device that needs I and so on.

If you want a monolithic function that can do all of the above, you'll have to change the way you handle the status byte. Here's an example:

import pyvisa as visa

address = "GPIB0::6::INSTR"
rm = visa.ResourceManager()
device = rm.open_resource(address)

identity = None
try:
    device.write("*IDN?")
    identity = device.read()
except visa.errors.VisaIOError:
    device.write("*RST") # get rid of the error state and try something else
if not identity:
    try:
        device.write("ID?")
        identity = device.read()
    except visa.errors.VisaIOError:
        device.write("*RST") # get rid of error state
if not identity:
    identity = "Unknown"

In general it's better to not do extra try/except behavior over GPIB communication. Trying the wrong command takes extra time and can put the instrument in an error state. In the code above, I use the *RST command to leave the error state, but this isn't guaranteed to work on all tools.
print(identity)


问:
Getting notified when the page DOM has loaded (but before window.onload)
I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the window.onload event), but it's different for every browser.

Is there a definitive way to do this on all the browsers?

So far I know of:

DOMContentLoaded : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:

document.addEventListener( "DOMContentLoaded", [init function], false );

Deferred script: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.

Polling: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?

I'd like to be able to go without using document.write or external files.

This can be done simply via jQuery:

```<code>$(document).ready(function() { ... })
</code>```

but, I'm writing a JS library and can't count on jQuery always being there.

答:
Why not this:

```<code><body>
  <!-- various content -->
  <script type="text/javascript">
  <!--
    myInit();
  -->
  </script>
</body>
</code>```

If I understand things correctly, myInit is gonna get executed as soon as browser hit it in the page, which is last thing in a body.

OwnerDisplayName: levik

ContentLicense: CC BY-SA 2.5

Body:
I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the window.onload event), but it's different for every browser.

Is there a definitive way to do this on all the browsers?

So far I know of:

DOMContentLoaded : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:

document.addEventListener( "DOMContentLoaded", [init function], false );

Deferred script: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.

Polling: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?

I'd like to be able to go without using document.write or external files.

This can be done simply via jQuery:

$(document).ready(function() { ... })

but, I'm writing a JS library and can't count on jQuery always being there.

LastEditorDisplayName: levik

Body:
Why not this:

<body>
  <!-- various content -->
  <script type="text/javascript">
  <!--
    myInit();
  -->
  </script>
</body>

If I understand things correctly, myInit is gonna get executed as soon as browser hit it in the page, which is last thing in a body.

OwnerDisplayName: Slartibartfast


问:
What is the fastest way in C# to find a pattern in a group of files?
```<code>using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace regex
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Regex exp = new Regex(@"e(-)?m[a@]il(s)?|input|output|padr(ão|ões)|máquina(s)?|reconhecimento",
                            RegexOptions.IgnoreCase | RegexOptions.Compiled |
                            RegexOptions.Multiline  | RegexOptions.ExplicitCapture);

      for (int filecount = 0 ; filecount < 22 ; filecount++)
      {
        string file = "/home/files/file"+ string.Format("{0:0#}",filecount) + ".txt";
        StreamReader reader = new StreamReader(file);

        string text = reader.ReadToEnd();
        int c=0;

        MatchCollection matchList = exp.Matches(text);
        c = matchList.Count;

        Console.WriteLine("Reading " + file + " -> " + c + " matches");
      }
    }
  }
}
</code>```

If I comment out the line

```<code>c = matchList.Count;
</code>```

it is pretty fast. But I need to know the number of matches it has found.

Is this the fastest way to do this? For the group of files I have, it's taking me 14 seconds to parse every file. Perl takes 1 second to output exactly the same information.

PS: Each file (text file) has +/- 1Mb so it's ~20Mb to process.

Thanks ;)

答:
One thing that might be working against you here is that you are leaving your file connections open, that adds some un-necessary overhead.

Be sure to call reader.Close(); after doing the ReadToEnd();

OwnerDisplayName: Ricardo Mestre

Body:
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace regex
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Regex exp = new Regex(@"e(-)?m[a@]il(s)?|input|output|padr(ão|ões)|máquina(s)?|reconhecimento",
                            RegexOptions.IgnoreCase | RegexOptions.Compiled |
                            RegexOptions.Multiline  | RegexOptions.ExplicitCapture);

      for (int filecount = 0 ; filecount < 22 ; filecount++)
      {
        string file = "/home/files/file"+ string.Format("{0:0#}",filecount) + ".txt";
        StreamReader reader = new StreamReader(file);

        string text = reader.ReadToEnd();
        int c=0;

        MatchCollection matchList = exp.Matches(text);
        c = matchList.Count;

        Console.WriteLine("Reading " + file + " -> " + c + " matches");
      }
    }
  }
}

If I comment out the line

c = matchList.Count;

it is pretty fast. But I need to know the number of matches it has found.

Is this the fastest way to do this? For the group of files I have, it's taking me 14 seconds to parse every file. Perl takes 1 second to output exactly the same information.

PS: Each file (text file) has +/- 1Mb so it's ~20Mb to process.

Thanks ;)

LastEditorDisplayName: Alan M

OwnerDisplayName: Mitchel Sellers


问:
How to skip lines when reading a file with numpy.fromfile?
I am reading a .pksc file that contains coordinates and velocities of a large number of astronomical objects. I am doing the reading with

```<code>import numpy as np
f=open('halos_10x10.pksc')
data = np.fromfile(f,count=N*10,dtype=np.float32)
</code>```

The file can be found here. It is very large and I want to skip the first m objects (the first m lines corresponding to these objects, if there are lines in the file). How can I do this, I see nowhere an option for skipping? Optionally, it would be also nice to be able to skip the last k objects from the file. Tnx!

答:
The first thing to appreciate is that your PKSC file is binary and is one continuous string of bytes with no discernible breaks in the data.

Text files on the other hand have lines that are clearly delimited by some line-break character, so it's pretty easy to read a line at a time and ignore M lines at the front, then read the remaining number of lines you care about: REMAINING_LINES = ALL_LINES - M_LINES - K_LINES.

np.fromfile() reads the binary file an item at a time.

To do this, it needs the dtype= param to tell the reader how big an item is.  In the case of a PKSC file, we represent an item as a 32-bit integer, np.int32.

I searched and searched but could not find a spec for the file.  Fortunately the link you provided has a sample Python script for reading the file; and I also found a well-documented Python lib for dealing with these kinds of files (websk.py, linked below).

I've learned that the PKSC file has the following properties:

The first 3 items are header items:

the first header item is a count of the records of relevant data that follow the header items

each relevant data record contains 10 items

np.fromfile() also takes the count= param as an instruction of exactly how many items to read.

Here's how to read the 3 header items, get the total number of Halo records that follow, and read the first two records (10 items per record):

Nitems_per_record = 10

f = open('halos_10x10.pksc')

headers = np.fromfile(f, dtype=np.int32, count=3)
print(f'Headers: {headers}')
print(f'This file contains {headers[0]} records with Halo data')

record1 = np.fromfile(f, dtype=np.int32, count=Nitems_per_record)
print(f'First record:\n{record1}')

record2 = np.fromfile(f, dtype=np.int32, count=Nitems_per_record)
print(f'Second record:\n{record2}')
```
<pre class="lang-none prettyprint-override"><code>Headers: [2079516 2079516 2079516]
This file contains 2079516 records with Halo data
First record:
[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585  1086444250  1170064687 -1011110709 -1006510502]
Second record:
[ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]
</code>```

According to websky.py, the 2nd and 3rd header items also have relevant values, maybe you care about these too?  I've synthesized the following from that code:

RTHMAXin    = headers[1]
redshiftbox = headers[2]
```
<p>Reading more than one record at a time requires re-shaping the data.  To read 3 records:</p>
<pre class="lang-py prettyprint-override"><code>f = open('halos_10x10.pksc')

np.fromfile(f, dtype=np.int32, count=3)  # reading, but ignoring header items

three_records = np.fromfile(f, dtype=np.int32, count=3*Nitems_per_record)
print(f'Initial:\n{three_records}')

reshaped_records = np.reshape(three_records, (3, Nitems_per_record))
print(f'Re-shaped:\n{reshaped}')
</code>```

Initial:
[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585
  1086444250  1170064687 -1011110709 -1006510502  1170083367 -1013908122
 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354
 -1013985376 -1006510502  1169622353 -1009409432 -1006678295 -1045415727
 -1017794908 -1051267742  1084874393  1169623221 -1009509109 -1006675510]
Re-shaped:
[[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585  1086444250  1170064687 -1011110709 -1006510502]
 [ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]
 [ 1169622353 -1009409432 -1006678295 -1045415727 -1017794908 -1051267742  1084874393  1169623221 -1009509109 -1006675510]]
```
<h4>So, what about skipping?</h4>
<h5>Just trim the reshaped data</h5>
<p>The easiest thing to do would be read all the data and then trim from the front and back what you don't want:</p>
<pre class="lang-py prettyprint-override"><code>m = 1
k = 1 * -1
trimmed_records = reshaped_records[m:k]
print(f'Trimmed:\n{trimmed_records}')
</code>```

Trimmed:
[[ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]]
```
<p>I'm not sure why you want to skip, but that's the easiest to understand and implement.</p>
<p>If you're conern is memory, read on.</p>
<h5>Discard M records, read less <code>K+M</code> records</h5>
<p>The next option, as I see it, is to:</p>
<ol>
<li>take the record count (<code>A</code> records) from the first header</li>
<li>read and <em>ignore</em> <code>M</code> records</li>
<li>figure out how many <em>remaining</em> records you have to read, given that you've already read <code>M</code> records and want to stop at record <code>K</code>: <code>R = A - M - K</code></li>
</ol>
<p>You'll only save a little memory by ignoring <code>M</code> records; the data is still read and interpreted.  You'll definitely save on memory by not reading records <code>K</code> to the end:</p>
<pre class="lang-py prettyprint-override"><code>f = open('halos_10x10.pksc')
headers = np.fromfile(f, dtype=np.int32, count=3)

Arecords = headers[0]
Mrecords = 1_000_000
Krecords = 1_000_000

Nitems = Mrecords * Nitems_per_record
np.fromfile(f, dtype=np.int32, count=Nitems)

Rrecords = Arecords - Mrecords - Krecords  # Remaining records to read
Nitems = Rrecords * Nitems_per_record
data = np.fromfile(f, dtype=np.int32, count=Nitems)
data = np.reshape(data, (Rrecords, Nitems_per_record))

print(f'From {Arecords} to {Rrecords} records:\n{data.shape}')
</code>```

From 2079516 to 79516 records:
(79516, 10)
```

Body:
I am reading a .pksc file that contains coordinates and velocities of a large number of astronomical objects. I am doing the reading with

import numpy as np
f=open('halos_10x10.pksc')
data = np.fromfile(f,count=N*10,dtype=np.float32)

The file can be found here. It is very large and I want to skip the first m objects (the first m lines corresponding to these objects, if there are lines in the file). How can I do this, I see nowhere an option for skipping? Optionally, it would be also nice to be able to skip the last k objects from the file. Tnx!

Body:
The first thing to appreciate is that your PKSC file is binary and is one continuous string of bytes with no discernible breaks in the data.

Text files on the other hand have lines that are clearly delimited by some line-break character, so it's pretty easy to read a line at a time and ignore M lines at the front, then read the remaining number of lines you care about: REMAINING_LINES = ALL_LINES - M_LINES - K_LINES.

np.fromfile() reads the binary file an item at a time.

To do this, it needs the dtype= param to tell the reader how big an item is.  In the case of a PKSC file, we represent an item as a 32-bit integer, np.int32.

I searched and searched but could not find a spec for the file.  Fortunately the link you provided has a sample Python script for reading the file; and I also found a well-documented Python lib for dealing with these kinds of files (websk.py, linked below).

I've learned that the PKSC file has the following properties:

The first 3 items are header items:

the first header item is a count of the records of relevant data that follow the header items

each relevant data record contains 10 items

np.fromfile() also takes the count= param as an instruction of exactly how many items to read.

Here's how to read the 3 header items, get the total number of Halo records that follow, and read the first two records (10 items per record):

Nitems_per_record = 10

f = open('halos_10x10.pksc')

headers = np.fromfile(f, dtype=np.int32, count=3)
print(f'Headers: {headers}')
print(f'This file contains {headers[0]} records with Halo data')

record1 = np.fromfile(f, dtype=np.int32, count=Nitems_per_record)
print(f'First record:\n{record1}')

record2 = np.fromfile(f, dtype=np.int32, count=Nitems_per_record)
print(f'Second record:\n{record2}')

Headers: [2079516 2079516 2079516]
This file contains 2079516 records with Halo data
First record:
[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585  1086444250  1170064687 -1011110709 -1006510502]
Second record:
[ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]

According to websky.py, the 2nd and 3rd header items also have relevant values, maybe you care about these too?  I've synthesized the following from that code:

RTHMAXin    = headers[1]
redshiftbox = headers[2]

Reading more than one record at a time requires re-shaping the data.  To read 3 records:

f = open('halos_10x10.pksc')

np.fromfile(f, dtype=np.int32, count=3)  # reading, but ignoring header items

three_records = np.fromfile(f, dtype=np.int32, count=3*Nitems_per_record)
print(f'Initial:\n{three_records}')

reshaped_records = np.reshape(three_records, (3, Nitems_per_record))
print(f'Re-shaped:\n{reshaped}')

Initial:
[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585
  1086444250  1170064687 -1011110709 -1006510502  1170083367 -1013908122
 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354
 -1013985376 -1006510502  1169622353 -1009409432 -1006678295 -1045415727
 -1017794908 -1051267742  1084874393  1169623221 -1009509109 -1006675510]
Re-shaped:
[[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585  1086444250  1170064687 -1011110709 -1006510502]
 [ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]
 [ 1169622353 -1009409432 -1006678295 -1045415727 -1017794908 -1051267742  1084874393  1169623221 -1009509109 -1006675510]]

So, what about skipping?

Just trim the reshaped data

The easiest thing to do would be read all the data and then trim from the front and back what you don't want:

m = 1
k = 1 * -1
trimmed_records = reshaped_records[m:k]
print(f'Trimmed:\n{trimmed_records}')

Trimmed:
[[ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]]

I'm not sure why you want to skip, but that's the easiest to understand and implement.

If you're conern is memory, read on.

Discard M records, read less K+M records

The next option, as I see it, is to:

take the record count (A records) from the first header

read and ignore M records

figure out how many remaining records you have to read, given that you've already read M records and want to stop at record K: R = A - M - K

You'll only save a little memory by ignoring M records; the data is still read and interpreted.  You'll definitely save on memory by not reading records K to the end:

f = open('halos_10x10.pksc')
headers = np.fromfile(f, dtype=np.int32, count=3)

Arecords = headers[0]
Mrecords = 1_000_000
Krecords = 1_000_000

Nitems = Mrecords * Nitems_per_record
np.fromfile(f, dtype=np.int32, count=Nitems)

Rrecords = Arecords - Mrecords - Krecords  # Remaining records to read
Nitems = Rrecords * Nitems_per_record
data = np.fromfile(f, dtype=np.int32, count=Nitems)
data = np.reshape(data, (Rrecords, Nitems_per_record))

print(f'From {Arecords} to {Rrecords} records:\n{data.shape}')

From 2079516 to 79516 records:
(79516, 10)


问:
Page not found at /about/. The current path, about/, did not match any of these. Why can't django follow my URL path?
I'm sure this question has been asked many times before but I'm sure I'm doing everything exactly as the tutorial says and it's still not working. I can access the home page just fine but not the about page.

Here is screenshot of the error:

https://i.stack.imgur.com/oFNAJ.png

I have the URL path in my .urls file (file below)

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.homepage, name='main-home'),
    path('about/', views.about, name='main-about'),
]
</code>```

And in the .urls file I have referenced the .views file (below)

```<code>from django.shortcuts import render
from django.http import HttpResponse

def homepage(request):
    return HttpResponse('<h1>Home</h1>')

def about(request):
    return HttpResponse('<h1>About</h1>')
</code>```

I could be missing something blatantly obvious but I've been staring at this for hours now and still can't figure out why it can't find the page.

EDIT: I am referring to the app urls file in the main post. In case its useful, here is the project .urls file:

```<code>from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('homepage/', include('home.urls')),
]
</code>```

答:
Per your copied image, you're accessing localhost:8000/about, not loaclhost:8000/homepage/about, which I think if you were to visit right now would return your "about" view HttpResponse object.

The main site urls.py is referencing 'homepage/', so for anything with that prefix it will be looking at the additional path objects/parameters in your app urls.py.  Try:

```<code>from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home.urls')),
]
</code>```

Body:
I'm sure this question has been asked many times before but I'm sure I'm doing everything exactly as the tutorial says and it's still not working. I can access the home page just fine but not the about page.

Here is screenshot of the error:

https://i.stack.imgur.com/oFNAJ.png

I have the URL path in my .urls file (file below)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.homepage, name='main-home'),
    path('about/', views.about, name='main-about'),
]

And in the .urls file I have referenced the .views file (below)

from django.shortcuts import render
from django.http import HttpResponse

def homepage(request):
    return HttpResponse('
Home
')

def about(request):
    return HttpResponse('
About
')

I could be missing something blatantly obvious but I've been staring at this for hours now and still can't figure out why it can't find the page.

EDIT: I am referring to the app urls file in the main post. In case its useful, here is the project .urls file:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('homepage/', include('home.urls')),
]

Body:
Per your copied image, you're accessing localhost:8000/about, not loaclhost:8000/homepage/about, which I think if you were to visit right now would return your "about" view HttpResponse object.

The main site urls.py is referencing 'homepage/', so for anything with that prefix it will be looking at the additional path objects/parameters in your app urls.py.  Try:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home.urls')),
]


问:
Nothing happens when I try to render a cube using Away3D
when I try to render a cube using Away3D + Molehill, I only get a white default screen, I followed the instructions here: http://johnlindquist.com/2011/02/28/quickstart-for-molehill-and-away3d/

The only thing I did not do, was the part that talks about the patch, cuz If I do that I get errors like when I try to import the Sprite class, for example.

Im using FB 4.5.

Thanks!

This is my code:

```<code>package
{
    import away3d.containers.View3D;
    import away3d.materials.ColorMaterial;
    import away3d.primitives.Cube;

    import flash.display.Sprite;
    import flash.events.*;

    public class Molehill extends Sprite
    {
        private var view:View3D;
        private var cube:Cube;

        public function Molehill()
        {
            view = new View3D();
            addChild(view);

            var material:ColorMaterial = new ColorMaterial(0xFF0000);
            cube = new Cube(material);

            view.scene.addChild(cube);

            addEventListener(Event.ENTER_FRAME, onEnterFrame);

        }

        private function onEnterFrame(e:Event):void
        {
                cube.rotationY += 10;
        }
    }
}
</code>```

答:
Everything is OK in your code if you have added in onEnterFrame view.render();.

Make sure that you have set wmode to "direct" in html-template/index.template.html and that you have downloaded beta release of Flash Player.

Body:
when I try to render a cube using Away3D + Molehill, I only get a white default screen, I followed the instructions here: http://johnlindquist.com/2011/02/28/quickstart-for-molehill-and-away3d/

The only thing I did not do, was the part that talks about the patch, cuz If I do that I get errors like when I try to import the Sprite class, for example.

Im using FB 4.5.

Thanks!

This is my code:

package
{
    import away3d.containers.View3D;
    import away3d.materials.ColorMaterial;
    import away3d.primitives.Cube;

    import flash.display.Sprite;
    import flash.events.*;

    public class Molehill extends Sprite
    {
        private var view:View3D;
        private var cube:Cube;

        public function Molehill()
        {
            view = new View3D();
            addChild(view);

            var material:ColorMaterial = new ColorMaterial(0xFF0000);
            cube = new Cube(material);

            view.scene.addChild(cube);

            addEventListener(Event.ENTER_FRAME, onEnterFrame);

        }

        private function onEnterFrame(e:Event):void
        {
                cube.rotationY += 10;
        }
    }
}