问:
Why the RefreshView not updated my child element when I refresh?
Here's my xaml file.

```<code>    <RefreshView  x:Name="myRefreshView" Refreshing="myRefreshView_RefreshingAsync" RefreshColor="#b52b2b">
          <ScrollView>
             <StackLayout>
                 <Label Text="{Binding firstName }" />
            </StackLayout>
         </ScrollView>
 </RefreshView>
</code>```

Here's my .cs file which has a function

```<code>namespace Health.Views

    {
        public partial class LandingPage : ContentPage
        {

            public string firstName { set; get; }

            public LandingPage()
            {

                firstName = "Mary";
                this.BindingContext = this;

            }

             async void myRefreshView_RefreshingAsync(Object sender, System.EventArgs e)
             {
                 await Task.Delay(3000);
                 firstName = "John";
                 myRefreshView.IsRefreshing = false;
             }
         }
    }
</code>```

The problem is when I refresh, the name is not change to "John".  Not sure what else I have to add.

答:
You need to implement INotifyPropertyChanged.</p>
```<code>public class LandingPage : ContentPage, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _firstName;
    public string firstName {
        get{return _firstName;}
        set
        {
            _firstName = value;
            OnPropertyChanged("firstName");
        } }

    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}
</code>```

Body:
Here's my xaml file.

    <RefreshView  x:Name="myRefreshView" Refreshing="myRefreshView_RefreshingAsync" RefreshColor="#b52b2b">
          <ScrollView>
             <StackLayout>

            </StackLayout>
         </ScrollView>
 </RefreshView>

Here's my .cs file which has a function

namespace Health.Views

    {
        public partial class LandingPage : ContentPage
        {

            public string firstName { set; get; }

            public LandingPage()
            {

                firstName = "Mary";
                this.BindingContext = this;

            }

             async void myRefreshView_RefreshingAsync(Object sender, System.EventArgs e)
             {
                 await Task.Delay(3000);
                 firstName = "John";
                 myRefreshView.IsRefreshing = false;
             }
         }
    }

The problem is when I refresh, the name is not change to "John".  Not sure what else I have to add.

Body:
You need to implement INotifyPropertyChanged.

public class LandingPage : ContentPage, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _firstName;
    public string firstName {
        get{return _firstName;}
        set
        {
            _firstName = value;
            OnPropertyChanged("firstName");
        } }

    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}


来源: stackexchange

问:
Is there a way to speed up handling large CSVs and dataframes in python?
I'm handling some CSV files with sizes in the range 1Gb to 2Gb. It takes 20-30 minutes just to load the files into a pandas dataframe, and 20-30 minutes more for each operation I perform, e.g. filtering the dataframe by column names, printing dataframe.head(), etc. Sometimes it also lags my computer when I try to use another application while I wait. I'm on a 2019 Macbook Pro, but I imagine it'll be the same for other devices.

I have tried using modin, but the data manipulations are still very slow.

Is there any way for me to work more efficiently?

Thanks in advance for the responses.

答:
Consider using polars. It is typically orders of magnitudes faster than pandas. Here are some benchmarks backing that claim.

If you really want full performance, consider using the lazy API. All the filters you describe can maybe even be done at scan level. We can also parralellize over all files easily with pl.collect_all().

ContentLicense: CC BY-SA 4.0


问:
How to divide screen evenly in 3?
I'm already using this calculation:

```<code>size = act.getWindow().getDecorView().getWidth()/3;

int dip = (int)TypedValue.applyDimension(
                 TypedValue.COMPLEX_UNIT_DIP,
                 size,
                 r.getDisplayMetrics()
          );
</code>```

However, my images are way too big. What do I need to do?

答:
A simple way would be to the layout weight when defining the your XML:

```<code> <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical">

     <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        weight="1" />

     <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        weight="1" />

     <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        weight="1" />

  </LinearLayout>
</code>```

You can also use the ScaleType property to change how the image is scaled, hope this helps!

ContentLicense: CC BY-SA 3.0

Title: How to divide screen evenly in 3?

Body:
I'm already using this calculation:

size = act.getWindow().getDecorView().getWidth()/3;

int dip = (int)TypedValue.applyDimension(
                 TypedValue.COMPLEX_UNIT_DIP,
                 size,
                 r.getDisplayMetrics()
          );

However, my images are way too big. What do I need to do?

Body:
A simple way would be to the layout weight when defining the your XML:

 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical">

     <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        weight="1" />

     <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        weight="1" />

     <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        weight="1" />

  </LinearLayout>

You can also use the ScaleType property to change how the image is scaled, hope this helps!


问:
Is there a way to get corresponding index value in a 2nd array using the 1st array as a reference in Javascript?
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

```<code>function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}
</code>```

答:
Essentially what you're looking to do is get the index of the input s in your str array, and return the item at the same index in your int array. You could accomplish this with just the one loop:

```<code>function word(s) {
    let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
    let int = [1,2,3,4,5,6,7,8,9,0];

    for (let j = 0; j < int.length; j++){
        if (s === str[j]){
         return int[j]
        }
    }
}
</code>```

Of course, this is reliant upon the order of values matching up in your str and int arrays.

Body:
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}

Body:
Essentially what you're looking to do is get the index of the input s in your str array, and return the item at the same index in your int array. You could accomplish this with just the one loop:

function word(s) {
    let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
    let int = [1,2,3,4,5,6,7,8,9,0];

    for (let j = 0; j < int.length; j++){
        if (s === str[j]){
         return int[j]
        }
    }
}

Of course, this is reliant upon the order of values matching up in your str and int arrays.


问:
nested array object property return undefined typeError in react redux
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

```<code>"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}
</code>```

i want to exhibit this post detail in frontend and here is the code:

```<code>export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (
        <div>
            <h1>Post Detail</h1>
            <div>
                <h2>{title}</h2>
                <i>posted in {created}</i>
                 <li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
                 ))}</li>
                <p>{content}</p>
            </div>
        </div>
    );
}
</code>```

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance

答:
You have provided your object with creater,

```<code>"creator": {
  "_id": "61cd99efa0b8d616a7a53ce1",
  "createdAt": "2021-12-30T11:37:19.041Z",
  "updatedAt": "2022-01-06T14:35:48.801Z",
  "__v": 0,
  "bio": "user bio",
  "name": "username"
},
</code>```

map method is only works with Array. But Here You have used with Object

```<code><div>
   <h1>Post Detail</h1>
   <div>
     <h2>{title}</h2>
     <i>posted in {created}</i>
     <li>Created by {creator.map((m,i)=>(
         <b key={i}>{m.name}</b>
         ))}
     </li>
     <p>{content}</p>
    </div>
</div>
</code>```

You can replace Your code with

```<code><div>
  <h1>Post Detail</h1>
  <div>
    <h2>{title}</h2>
    <i>posted in {created}</i>
    <li><b>Created by {creator.name}</b></li>
    <p>{content}</p>
  </div>
</div>
</code>```

Body:
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}

i want to exhibit this post detail in frontend and here is the code:

export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (

Post Detail

{title}

                posted in {created}

Created by {creator.map((m,i)=>(
{m.name}
                 ))}

{content}

    );
}

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance

Body:
You have provided your object with creater,

"creator": {
  "_id": "61cd99efa0b8d616a7a53ce1",
  "createdAt": "2021-12-30T11:37:19.041Z",
  "updatedAt": "2022-01-06T14:35:48.801Z",
  "__v": 0,
  "bio": "user bio",
  "name": "username"
},

map method is only works with Array. But Here You have used with Object

<div>
   <h1>Post Detail</h1>
   <div>
     <h2>{title}</h2>
     <i>posted in {created}</i>
     <li>Created by {creator.map((m,i)=>(
         <b key={i}>{m.name}</b>
         ))}
     </li>
     <p>{content}</p>
    </div>
</div>

You can replace Your code with

<div>
  <h1>Post Detail</h1>
  <div>
    <h2>{title}</h2>
    <i>posted in {created}</i>
    <li><b>Created by {creator.name}</b></li>
    <p>{content}</p>
  </div>
</div>


问:
How to get sum and count in MongoDB?

I want to list Names, loan amount and number of loans that are Completed.

Thanks alot!!! Appreciate it.

答:
try:

https://mongoplayground.net/p/So-XDro3k2M

total_loan_amount = amount from all loans without check for status

all_names = all names without check for status

number_completed = total number of Completed loans

```<code>db.collection.aggregate([
  {
    $group: {
      _id: null,
      total_loan_amount: {
        $sum: "$loan_amount"
      },
      "all_names": {
        $push: "$name"
      },
      "statuses": {
        $push: "$status"
      }
    }
  },
  {
    $project: {
      "_id": 0,
      "all_names": 1,
      "total_loan_amount": 1,
      "number_completed": {
        "$size": "$statuses"
      }
    }
  }
])
</code>```

response:

```<code>[
  {
    "all_names": [
      "John Tan",
      "Mary Lee",
      "Yuyu Lee",
      "Joseph Lee"
    ],
    "number_completed": 4,
    "total_loan_amount": 1.41132004e+08
  }
]
</code>```

Title: How to get sum and count in MongoDB?

Body:
try:

https://mongoplayground.net/p/So-XDro3k2M

total_loan_amount = amount from all loans without check for status

all_names = all names without check for status

number_completed = total number of Completed loans

db.collection.aggregate([
  {
    $group: {
      _id: null,
      total_loan_amount: {
        $sum: "$loan_amount"
      },
      "all_names": {
        $push: "$name"
      },
      "statuses": {
        $push: "$status"
      }
    }
  },
  {
    $project: {
      "_id": 0,
      "all_names": 1,
      "total_loan_amount": 1,
      "number_completed": {
        "$size": "$statuses"
      }
    }
  }
])

response:

[
  {
    "all_names": [
      "John Tan",
      "Mary Lee",
      "Yuyu Lee",
      "Joseph Lee"
    ],
    "number_completed": 4,
    "total_loan_amount": 1.41132004e+08
  }
]


问:
AJAX & Disabled JavaScript. Do you worry?
I'm new to PHP, AJAX, and databases.

But I want to know what experiences programmers think and do.

When using AJAX, do you worry about users who have JavaScript disabled?

Do you have a backup solution? Or is the number of those who have JavaScript disabled so small that it isn't a concern?

Wow I got a lot of opinions, which is good, but I think it's important for me to clarify a bit.

I'm asking specifically in terms of AJAX in websites.

When it comes to JavaScript in my websites, I work with the goal of using it to ENHANCE the experience of the user, but ensure that the core of the site will still function for users with JavaScript disabled.
But from my understanding of AJAX, it IS the core functionality is it not? It communicates with the server or database the way PHP does. So how do you make a fallback for that? Or do you?

Again, if I'm mistaken about the role of AJAX, please forgive and enlighten me.

答:
They key is to understand the viewers you are targeting.  If your site is plenty useful without javascript, then it may be worth the extra effort to make a reasonable experience when javascript is disabled.  You would have to understand the functionality of your site and targetted viewership to know whether that extra effort was worth it or not.  There is no single correct answer here.

If your site isn't very useful when javascript is disabled, then it may not be worth the extra effort to try to do anything beyond tell the users that javascript is required.  Why put in a bunch of extra effort (and a lot of extra testing) if those viewers won't be loyal to your site and be regular visitors anyway because the user experience will be fairly undesirable.

So, the answer is it depends a lot on what your site does, who your competition is and who your viewers are.  Though people on SO like to argue with me in this regard (out of the purity of every web site should work for all - I think), it is getting harder and harder to justify the business case for the extra work for making many sites work without javascript these days.  It, of course, depends upon the specifics of your site, competition and viewers.  In my book, it is by no means a given that you should make every site work without javascript enabled.

If you Google, you can find articles that discuss how many users have Javascript disabled.  This Yahoo article from mid 2010 says that they saw .25% - 2% of users with JS disabled.

As for Ajax specifically, there is no like replacement or fallback without Javascript.  If you have a design that depends upon using Ajax for communicating with your server, then that design will require Javascript - period.  Your only alternative would be to have a non-Ajax design (a more traditional page request from your server with one URL for one static page) that could be served instead that did not use Ajax.  If your other design used and depended upon Ajax, this non-Ajax design would be a significantly different design and implementation.


问:
How to access calendar in MacOS screensaver?
Is it possible to access calendar events in screen saver? I am able to request permission in the application. But some API is not prompting in the case of the screensaver.

I didn't find any documentation around it.

I used the following code to requesting calendar events:

```<code>func requestPermissionForCalendar()
{
    var eventStore = EKEventStore()

    eventStore.requestAccess(to: EKEntityType.event) { granted, error in

        if granted{
            print("Permission granted")
        }else{
            print("The app is not permitted to access reminders, make sure to grant permission in the settings and try again")
        }
    }
}
</code>```

答:
Couple of things, first, a screen saver is completely passive in macOS. Any prompt for anything will be disregarded when it's running fullscreen, as a screensaver.

In general, the proper way to do this with a screensaver is to ask for permission in the configurationSheet (the screen saver options). The user will get prompted there, and can allow or deny you. I do use this for example to request the user location.

Once allowed in System Preferences, your screensaver when running in screensaver mode will get access. I suggest you test your code first in the configuration sheet as this is much easier.

Additional note, ScreenSavers on macOS since Catalina are sandboxed by an application extension provided by Apple, and that extension has a limited list of entitlements (see a list here https://github.com/glouel/ScreenSaverMinimal).

I'm not particularly familiar with EKEventStore, but if it requires a specific entitlement to make it work, you'll be stuck as you can't add any entitlement yourself, everything depends on legacyScreenSaver.appex.

Body:
Is it possible to access calendar events in screen saver? I am able to request permission in the application. But some API is not prompting in the case of the screensaver.

I didn't find any documentation around it.

I used the following code to requesting calendar events:

func requestPermissionForCalendar()
{
    var eventStore = EKEventStore()

    eventStore.requestAccess(to: EKEntityType.event) { granted, error in

        if granted{
            print("Permission granted")
        }else{
            print("The app is not permitted to access reminders, make sure to grant permission in the settings and try again")
        }
    }
}


问:
How to create azure vmss machine as azuredevops agent
I was trying to setup Azure virtual machine scaleset as build agetent for on AzureDevops server. Just to confirm whether the AzureDevops server will support VMSS? What permission is required to create the vmss based build agent and is there any automation for the same?</p>

答: Azure DevOps Server doesn't support Azure VM ScaleSets natively for pipelines agents. That is a Azure DevOps Service feature.</p>


问:
Webpack script errors in PowerShell, but not CMD.exe
I'm trying to set up CI/CD via GitHub actions and workflows.  When running a build script via Windows PowerShell (with elevation), Webpack fails with the following error:

[webpack-cli] TypeError: The 'compilation' argument must be an
instance of Compilation

at Function.getCompilationHooks (d:\dev\theApp\node_modules\webpack\lib\javascript\JavascriptModulesPlugin.js:138:10)

at d:\dev\theApp\node_modules\terser-webpack-plugin\dist\index.js:566:67

at _next30 (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10),

:44:1)

at _next8 (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10),

:97:1)

at Hook.eval [as call] (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10),

:117:1)

at Hook.CALL_DELEGATE [as _call] (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\Hook.js:14:14)

at Compiler.newCompilation (d:\Dev\theApp\node_modules\webpack\lib\Compiler.js:1044:26)

at d:\Dev\theApp\node_modules\webpack\lib\Compiler.js:1088:29

at Hook.eval [as callAsync] (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10),

:6:1)

at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\Hook.js:18:14)

This does not occur when run from an elevated instance of CMD.exe.  Setting the shell parameter for the step in the GitHub workflow to "cmd" still fails as the runner service uses PowerShell to launch cmd.exe with the command as an argument.

npm script from file package.json

"build": "webpack --config webpack.prod.js",

File Webpack.common.js

```<code>const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.(m?js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false,
        },
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
          },
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader',
        ],
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.svg$/,
        loader: 'svg-inline-loader',
      },
    ],
  },
  entry: './src/index.jsx',
  output: {
    path: __dirname + '/../dist/theApp',
    chunkFilename: '[chunkhash].[name].bundle.js',
    publicPath: '/',
    filename: '[name].js',
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'TheApp',
      filename: 'default.aspx',
      template: './default.html',
    }),
  ],
  resolve: {
    extensions: ['.js', '.jsx', '.es6'],
  },
};
</code>```

File webpack.prod.js

```<code>const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const TerserPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = merge(common, {
  mode: 'production',
  plugins: [
    new CleanWebpackPlugin(),
  ],
  optimization: {
    splitChunks: {
      chunks: 'async',
      minSize: 100000,
      minRemainingSize: 50000,
      maxSize: 500000,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 5,
      automaticNameDelimiter: '~',
      enforceSizeThreshold: 500000,
      cacheGroups: {
        utils: {
          minChunks: 1,
          test: /[\\/]node_modules[\\/](moment|lodash)[\\/]/,
          name: 'utils',
          chunks: 'all',
          priority: 0,
        },
        defaultVendors: {
          minChunks: 1,
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
        },
        default: {
          minChunks: 1,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
    minimize: true,
    minimizer: [
      new TerserPlugin({
        test: /\.js(\?.*)?$/i,
      }),
    ],
  },
});
</code>```

答:
I also encountered this error with Webpack. I solved the problem by adding camelCase letters into the path to the directory in which the command is executed.

The problem is not with Webpack, but with Windows, specifically with PowerShell and the way case sensitivity is handled. The error is not returned if you use another command prompt.

Let's take the following case:

I develop an application in the directory:

C:\Users\username\Desktop\myApp
```
<p>I compile the assets of this application with Webpack. The <em>Compilation</em> type error is triggered if I execute the <code>npm run dev</code> command in <code>c:\users\username\desktop\myapp</code> because Webpack can't find the node_modules folder. To fix the error, you just have to run your command into the right directory with also camelCase letters.</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\username\Desktop\myApp> npm run dev
</code>```

Webpack should find the node_modules folder and you won't have any more errors.

Body:
I'm trying to set up CI/CD via GitHub actions and workflows.  When running a build script via Windows PowerShell (with elevation), Webpack fails with the following error:

[webpack-cli] TypeError: The 'compilation' argument must be an
instance of Compilation

at Function.getCompilationHooks (d:\dev\theApp\node_modules\webpack\lib\javascript\JavascriptModulesPlugin.js:138:10)

at d:\dev\theApp\node_modules\terser-webpack-plugin\dist\index.js:566:67

at _next30 (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10),

:44:1)

at _next8 (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10),

:97:1)

at Hook.eval [as call] (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10),

:117:1)

at Hook.CALL_DELEGATE [as _call] (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\Hook.js:14:14)

at Compiler.newCompilation (d:\Dev\theApp\node_modules\webpack\lib\Compiler.js:1044:26)

at d:\Dev\theApp\node_modules\webpack\lib\Compiler.js:1088:29

at Hook.eval [as callAsync] (eval at create (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10),

:6:1)

at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (d:\Dev\theApp\node_modules\webpack\node_modules\tapable\lib\Hook.js:18:14)

This does not occur when run from an elevated instance of CMD.exe.  Setting the shell parameter for the step in the GitHub workflow to "cmd" still fails as the runner service uses PowerShell to launch cmd.exe with the command as an argument.

npm script from file package.json

"build": "webpack --config webpack.prod.js",

File Webpack.common.js

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.(m?js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false,
        },
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
          },
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader',
        ],
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.svg$/,
        loader: 'svg-inline-loader',
      },
    ],
  },
  entry: './src/index.jsx',
  output: {
    path: __dirname + '/../dist/theApp',
    chunkFilename: '[chunkhash].[name].bundle.js',
    publicPath: '/',
    filename: '[name].js',
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'TheApp',
      filename: 'default.aspx',
      template: './default.html',
    }),
  ],
  resolve: {
    extensions: ['.js', '.jsx', '.es6'],
  },
};

File webpack.prod.js

const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const TerserPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = merge(common, {
  mode: 'production',
  plugins: [
    new CleanWebpackPlugin(),
  ],
  optimization: {
    splitChunks: {
      chunks: 'async',
      minSize: 100000,
      minRemainingSize: 50000,
      maxSize: 500000,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 5,
      automaticNameDelimiter: '~',
      enforceSizeThreshold: 500000,
      cacheGroups: {
        utils: {
          minChunks: 1,
          test: /[\\/]node_modules[\\/](moment|lodash)[\\/]/,
          name: 'utils',
          chunks: 'all',
          priority: 0,
        },
        defaultVendors: {
          minChunks: 1,
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
        },
        default: {
          minChunks: 1,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
    minimize: true,
    minimizer: [
      new TerserPlugin({
        test: /\.js(\?.*)?$/i,
      }),
    ],
  },
});

Body:
I also encountered this error with Webpack. I solved the problem by adding camelCase letters into the path to the directory in which the command is executed.

The problem is not with Webpack, but with Windows, specifically with PowerShell and the way case sensitivity is handled. The error is not returned if you use another command prompt.

Let's take the following case:

I develop an application in the directory:

C:\Users\username\Desktop\myApp

I compile the assets of this application with Webpack. The Compilation type error is triggered if I execute the npm run dev command in c:\users\username\desktop\myapp because Webpack can't find the node_modules folder. To fix the error, you just have to run your command into the right directory with also camelCase letters.

C:\Users\username\Desktop\myApp> npm run dev

Webpack should find the node_modules folder and you won't have any more errors.


问:
Eleventy: Create "View all posts in collection" link
I'm trying to build a site in Eleventy. The site has blog posts in two collections: A and B. When I'm reading a post in the collection A, I'd like to have a link after the post content that says, "View all A posts". And when I'm reading a post in collection B, I'd like to see a "View all B posts" link.

The blog posts share the same _includes template post.html. In that template, I should be able to create an if statement in nunjucks that goes something like this:

```<code>{% if post in collections.A %}<a href="/a">View all A posts</a>
{% elif post in collections.B %}<a href="/b">View all B posts</a>
{% endif %}
</code>```

That code snippet doesn't work though. Any ideas?

答:
I got answer there https://www.webstoemp.com/blog/multilingual-sites-eleventy/

module.exports = function (eleventyConfig) {
  eleventyConfig.addCollection("posts_en", function (collection) {
    return collection.getFilteredByGlob("./src/en/posts/*.md");
  });
};

module.exports = function (eleventyConfig) {
  eleventyConfig.addCollection("posts_fr", function (collection) {
    return collection.getFilteredByGlob("./src/fr/posts/*.md");
  });
};
```

Body:
I'm trying to build a site in Eleventy. The site has blog posts in two collections: A and B. When I'm reading a post in the collection A, I'd like to have a link after the post content that says, "View all A posts". And when I'm reading a post in collection B, I'd like to see a "View all B posts" link.

The blog posts share the same _includes template post.html. In that template, I should be able to create an if statement in nunjucks that goes something like this:

{% if post in collections.A %}View all A posts
{% elif post in collections.B %}View all B posts
{% endif %}

That code snippet doesn't work though. Any ideas?


问:
WiX: How to prevent a registry value from being removed on uninstall?
I want to assert that a certain registry value exists after installation, so I added the following component:

```<code><Component Id="RegistryEntryContextMenuOdt" Guid="4BA5BA24-4F65-4BDF-99EB-CB4B947F31A9" DiskId="1" KeyPath="yes">
    <RegistryKey Id="RegKeyOdt" Root="HKCR" Action="create" Key=".odt">
      <RegistryValue Type="string" Value="openDocument.WriterDocument.1" />
    </RegistryKey>
</Component>
</code>```

The key/value might already be set before the installation. However, I want that the value is set to my specific value, i.e. that it will be overwritten with my value.

My problem is now that this value is always removed when my product is uninstalled. However, I only want the value to be removed if it was added by my installer. If my installer just modified the value, the previous value should be restored (or, if this is not possible, my value should remain untouched).

Please note that the key itself is not removed on uninstall. This seems to work correctly because I specified Action="create" on the RegistryKey element.

Is there maybe a similar setting for RegistryValue which will create the value but not remove it on install?

UPDATE: Both registry keys under HKCR are machine wide settinge, i.e. they originate from the HKLM\SOFTWARE\Classes branch of the registry.

答:
You can make sure that your component is only installed when the registry entry does not exist by making use of the NeverOverwrite attribute of the Component element. From the wix documentation for NeverOverwrite:

If this attribute is set to 'yes', the
  installer does not install or
  reinstall the component if a key path
  file or a key path registry entry for
  the component already exists.

You may also need to set the KeyPath attribute on the Registry element to yes to make it unambiguous that the registry entry is the component key path.

If you do want to set the registry value even if it already exists, but you don't want to remove it on uninstall, then you can use the Permanent attribute of the Component element instead.

OwnerDisplayName: divo

ContentLicense: CC BY-SA 2.5

Body:
I want to assert that a certain registry value exists after installation, so I added the following component:

<Component Id="RegistryEntryContextMenuOdt" Guid="4BA5BA24-4F65-4BDF-99EB-CB4B947F31A9" DiskId="1" KeyPath="yes">
    <RegistryKey Id="RegKeyOdt" Root="HKCR" Action="create" Key=".odt">
      <RegistryValue Type="string" Value="openDocument.WriterDocument.1" />
    </RegistryKey>
</Component>

The key/value might already be set before the installation. However, I want that the value is set to my specific value, i.e. that it will be overwritten with my value.

My problem is now that this value is always removed when my product is uninstalled. However, I only want the value to be removed if it was added by my installer. If my installer just modified the value, the previous value should be restored (or, if this is not possible, my value should remain untouched).

Please note that the key itself is not removed on uninstall. This seems to work correctly because I specified Action="create" on the RegistryKey element.

Is there maybe a similar setting for RegistryValue which will create the value but not remove it on install?

UPDATE: Both registry keys under HKCR are machine wide settinge, i.e. they originate from the HKLM\SOFTWARE\Classes branch of the registry.

LastEditorDisplayName: divo

OwnerDisplayName: wcoenen


问:
Pass Data even if it gets blocked From SQL
I have some data to escape sql check. Heres my code to check sql if its valid or not valid.

```<code>SELECT *
FROM tb_event
WHERE (time_start BETWEEN '$dateTimeStart' AND '$dateTimeFinish'
   OR time_finish BETWEEN '$dateTimeStart' AND '$dateTimeFinish')
</code>```

The code above will check all values if valid then it will be released.
But i have some field for name = position.. If the position is head of office. The system will check that the results are valid even though there are the same dates.

Example :

I will input date from 2022-02-06 to 2022-02-08

Table event to check :

```<code>ID | name | date_start | date_finish | position
1  | Ani  | 2022-02-06 | 2022-02-08  | head of office
2  | BAY  | 2022-02-06 | 2022-02-08  | staff
3  | CIE  | 2022-02-06 | 2022-02-08  | staff
4  | DON  | 2022-02-04 | 2022-02-05  | staff
5  | EVY  | 2022-02-04 | 2022-02-05  | staff
</code>```

The table I expect to appear

```<code>ID | name | date_start | date_finish | position
1  | Ani  | 2022-02-06 | 2022-02-08  | head of office
4  | DON  | 2022-02-04 | 2022-02-05  | staff
5  | EVY  | 2022-02-04 | 2022-02-05  | staff
</code>```

Because other is staff and the date already exists .

Body:
I have some data to escape sql check. Heres my code to check sql if its valid or not valid.

SELECT *
FROM tb_event
WHERE (time_start BETWEEN '$dateTimeStart' AND '$dateTimeFinish'
   OR time_finish BETWEEN '$dateTimeStart' AND '$dateTimeFinish')

The code above will check all values if valid then it will be released.
But i have some field for name = position.. If the position is head of office. The system will check that the results are valid even though there are the same dates.

Example :

I will input date from 2022-02-06 to 2022-02-08

Table event to check :

ID | name | date_start | date_finish | position
1  | Ani  | 2022-02-06 | 2022-02-08  | head of office
2  | BAY  | 2022-02-06 | 2022-02-08  | staff
3  | CIE  | 2022-02-06 | 2022-02-08  | staff
4  | DON  | 2022-02-04 | 2022-02-05  | staff
5  | EVY  | 2022-02-04 | 2022-02-05  | staff

The table I expect to appear

ID | name | date_start | date_finish | position
1  | Ani  | 2022-02-06 | 2022-02-08  | head of office
4  | DON  | 2022-02-04 | 2022-02-05  | staff
5  | EVY  | 2022-02-04 | 2022-02-05  | staff

Because other is staff and the date already exists .

Body:
You don't mention the database so I'll assume you are using PostgreSQL. You can do:

SELECT *
FROM t
WHERE (date_start BETWEEN '2022-02-06' AND '2022-02-08'
   OR date_finish BETWEEN '2022-02-06' AND '2022-02-08')
   OR position = 'head of office'

Result:

 id  name  date_start                date_finish               position
 --- ----- ------------------------- ------------------------- --------------
 1   Ani   2022-02-06T00:00:00.000Z  2022-02-08T00:00:00.000Z  head of office
 2   BAY   2022-02-06T00:00:00.000Z  2022-02-08T00:00:00.000Z  staff
 3   CIE   2022-02-06T00:00:00.000Z  2022-02-08T00:00:00.000Z  staff

See running example at DB Fiddle.


问:
how to set innodb_strict_mode = 0 in phpmyadmin or xammp
How can to set innodb_strict_mode = 0 in phpmyadmin because i'm having a problem in MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB.

I got this error when i set 96 entities in my table with a random datatypes consisting of int, varchar, text and date.

```<code>--
-- Table structure for table `tbl_student`
--

CREATE TABLE `tbl_student` (
  `s_id` int(11) NOT NULL,
  `ss_id` varchar(20) DEFAULT NULL,
  `sfname` varchar(50) DEFAULT NULL,
  `smname` varchar(50) DEFAULT NULL,
  `slname` varchar(50) DEFAULT NULL,
  `snext` varchar(10) DEFAULT NULL,
  `sdbirth` varchar(10) DEFAULT NULL,
  `sgender` varchar(10) DEFAULT NULL,
  `saddress` text DEFAULT NULL,
  `szcode` varchar(10) DEFAULT NULL,
  `scontact` varchar(20) DEFAULT NULL,
  `semail` varchar(50) DEFAULT NULL,
  `sctship` varchar(20) DEFAULT NULL,
  `scivilstat` varchar(20) DEFAULT NULL,
  `spbirth` text DEFAULT NULL,
  `sdisability` varchar(20) DEFAULT NULL,
  `s4psno` varchar(20) DEFAULT NULL,
  `spwdid` varchar(20) DEFAULT NULL,
  `srappsship` text DEFAULT NULL,
  `srappnas` text DEFAULT NULL,
  `sbos` text DEFAULT NULL,
  `ssskills` text DEFAULT NULL,
  `stwinterest` text DEFAULT NULL,
  `ssdfile` varchar(10) DEFAULT NULL,
  `sgfname` varchar(50) DEFAULT NULL,
  `sgmname` varchar(50) DEFAULT NULL,
  `sglname` varchar(50) DEFAULT NULL,
  `sgnext` varchar(10) DEFAULT NULL,
  `sglstatus` varchar(10) DEFAULT NULL,
  `sgeduc` varchar(30) DEFAULT NULL,
  `sgcontact` varchar(20) DEFAULT NULL,
  `sgaddress` text DEFAULT NULL,
  `sgoccu` varchar(30) DEFAULT NULL,
  `sgcompany` varchar(30) DEFAULT NULL,
  `sffname` varchar(50) DEFAULT NULL,
  `sfmname` varchar(50) DEFAULT NULL,
  `sflname` varchar(50) DEFAULT NULL,
  `sfnext` varchar(10) DEFAULT NULL,
  `sflstatus` varchar(10) DEFAULT NULL,
  `sfeduc` varchar(30) DEFAULT NULL,
  `sfcontact` varchar(20) DEFAULT NULL,
  `sfaddress` text DEFAULT NULL,
  `sfoccu` varchar(30) DEFAULT NULL,
  `sfcompany` varchar(30) DEFAULT NULL,
  `smfname` varchar(50) DEFAULT NULL,
  `smmname` varchar(50) DEFAULT NULL,
  `smlname` varchar(50) DEFAULT NULL,
  `smnext` varchar(10) DEFAULT NULL,
  `smlstatus` varchar(10) DEFAULT NULL,
  `smeduc` varchar(30) DEFAULT NULL,
  `smcontact` varchar(20) DEFAULT NULL,
  `smaddress` text DEFAULT NULL,
  `smoccu` varchar(30) DEFAULT NULL,
  `smcompany` varchar(30) DEFAULT NULL,
  `snsibling` varchar(10) DEFAULT NULL,
  `spcyincome` varchar(50) DEFAULT NULL,
  `spschname` text DEFAULT NULL,
  `spsaddress` text DEFAULT NULL,
  `spstype` varchar(20) DEFAULT NULL,
  `spscourse` varchar(50) DEFAULT NULL,
  `spsyrlvl` varchar(20) DEFAULT NULL,
  `spsgwa` int(10) DEFAULT NULL,
  `spsraward` text DEFAULT NULL,
  `spsdawardrceive` date DEFAULT NULL,
  `scsintend` text DEFAULT NULL,
  `scsadd` text DEFAULT NULL,
  `scschooltype` varchar(20) DEFAULT NULL,
  `sccourse` varchar(50) DEFAULT NULL,
  `sccourseprio` varchar(50) DEFAULT NULL,
  `scsyrlvl` varchar(20) DEFAULT NULL,
  `spass` varchar(100) DEFAULT NULL,
  `sdsprc` varchar(20) DEFAULT NULL,
  `sdsprcstat` varchar(20) DEFAULT NULL,
  `sdspgm` varchar(20) DEFAULT NULL,
  `sdspgmstat` varchar(20) DEFAULT NULL,
  `sdspcr` varchar(20) DEFAULT NULL,
  `sdspcrstat` varchar(20) DEFAULT NULL,
  `sdstbytpic` varchar(20) DEFAULT NULL,
  `sdstbytpicstat` varchar(20) DEFAULT NULL,
  `sdsbrgyin` varchar(20) DEFAULT NULL,
  `sdsbrgyinstat` varchar(20) DEFAULT NULL,
  `sdscef` varchar(20) DEFAULT NULL,
  `sdscefstat` varchar(20) DEFAULT NULL,
  `sdspsa` varchar(20) DEFAULT NULL,
  `sdspsastat` varchar(20) DEFAULT NULL,
  `sdsobr` varchar(20) NOT NULL,
  `sdsobrstat` varchar(20) NOT NULL,
  `student_profile_image` varchar(100) DEFAULT NULL,
  `s_added_on` date DEFAULT NULL,
  `s_applied_on` date DEFAULT NULL,
  `s_verification_code` varchar(100) DEFAULT NULL,
  `s_email_verify` varchar(10) DEFAULT NULL,
  `s_account_status` varchar(20) DEFAULT NULL,
  `s_grant_stat` varchar(20) NOT NULL,
  `s_scholar_stat` varchar(20) NOT NULL,
  `s_scholarship_type` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
</code>```

Here are my entities in my table. I tried to change something to data types and number I can't change and nothing happens.

答:
You can set innodb_strict_mode to OFF with the SQL statement

```<code>SET innodb_strict_mode=OFF;
</code>```

But that's kind of like catching and ignoring exceptions: all you're doing is concealing serious errors from your application.

The row-length limit in MySQL / MariaDB / InnoDB is a hard limit. If you try to exceed it your INSERT and UPDATE statements will fail.

You said your requirement is to extend a table with a few extra columns. And, in doing that you've hit the row-length limit. It happens (Remarks about the programmer who came before you removed ... this is a family-friendly web site.)

What can you do?

An easy fix: Change the table's CHARSET from utf8mb4 to utf8. That way you need three, rather than four bytes, per VARCHAR character. But utf8 is deprecated: it can't represent emojis and some other characters.

Next possible fix. Identify the VARCHAR columns that don't need Unicode. sdbirth? s_verification_code? student_profile_image? Declare those colums with

```<code>CHARACTER SET latin1 COLLATE latin1_bin
</code>```

If you make this change to s_verification_code and student_profile_image you'll save 600 bytes-- one byte per character rather than four, for two 100-character columns. That's enough that you can probably finish this task and pass off this table to your (unsuspecting) successor.

Another idea Change some of your VARCHAR() columns to TEXT columns. But beware! this slows down queries.  If your application has mostly SELECT * queries in it you probably don't want to do this. If it has mostly SELECT column, column, column queries this is probably OK.

A slightly harder fix:  Reduce the width of some of your fields. Does every personal name have to be stored as VARCHAR(50)? Will VARCHAR(30) do the trick? Do you need 10 characters for gender?  Can you represent date-of-birth with a DATE datatype? It will take three bytes rather than the 40 (VARCHAR(10)) it now uses.

The right fix Rework your app so some of that data (contact information, etc) for each student lives in different tables.  Or, create a new table for the new data you're adding.

Body:
How can to set innodb_strict_mode = 0 in phpmyadmin because i'm having a problem in MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB.

I got this error when i set 96 entities in my table with a random datatypes consisting of int, varchar, text and date.

--
-- Table structure for table `tbl_student`
--

CREATE TABLE `tbl_student` (
  `s_id` int(11) NOT NULL,
  `ss_id` varchar(20) DEFAULT NULL,
  `sfname` varchar(50) DEFAULT NULL,
  `smname` varchar(50) DEFAULT NULL,
  `slname` varchar(50) DEFAULT NULL,
  `snext` varchar(10) DEFAULT NULL,
  `sdbirth` varchar(10) DEFAULT NULL,
  `sgender` varchar(10) DEFAULT NULL,
  `saddress` text DEFAULT NULL,
  `szcode` varchar(10) DEFAULT NULL,
  `scontact` varchar(20) DEFAULT NULL,
  `semail` varchar(50) DEFAULT NULL,
  `sctship` varchar(20) DEFAULT NULL,
  `scivilstat` varchar(20) DEFAULT NULL,
  `spbirth` text DEFAULT NULL,
  `sdisability` varchar(20) DEFAULT NULL,
  `s4psno` varchar(20) DEFAULT NULL,
  `spwdid` varchar(20) DEFAULT NULL,
  `srappsship` text DEFAULT NULL,
  `srappnas` text DEFAULT NULL,
  `sbos` text DEFAULT NULL,
  `ssskills` text DEFAULT NULL,
  `stwinterest` text DEFAULT NULL,
  `ssdfile` varchar(10) DEFAULT NULL,
  `sgfname` varchar(50) DEFAULT NULL,
  `sgmname` varchar(50) DEFAULT NULL,
  `sglname` varchar(50) DEFAULT NULL,
  `sgnext` varchar(10) DEFAULT NULL,
  `sglstatus` varchar(10) DEFAULT NULL,
  `sgeduc` varchar(30) DEFAULT NULL,
  `sgcontact` varchar(20) DEFAULT NULL,
  `sgaddress` text DEFAULT NULL,
  `sgoccu` varchar(30) DEFAULT NULL,
  `sgcompany` varchar(30) DEFAULT NULL,
  `sffname` varchar(50) DEFAULT NULL,
  `sfmname` varchar(50) DEFAULT NULL,
  `sflname` varchar(50) DEFAULT NULL,
  `sfnext` varchar(10) DEFAULT NULL,
  `sflstatus` varchar(10) DEFAULT NULL,
  `sfeduc` varchar(30) DEFAULT NULL,
  `sfcontact` varchar(20) DEFAULT NULL,
  `sfaddress` text DEFAULT NULL,
  `sfoccu` varchar(30) DEFAULT NULL,
  `sfcompany` varchar(30) DEFAULT NULL,
  `smfname` varchar(50) DEFAULT NULL,
  `smmname` varchar(50) DEFAULT NULL,
  `smlname` varchar(50) DEFAULT NULL,
  `smnext` varchar(10) DEFAULT NULL,
  `smlstatus` varchar(10) DEFAULT NULL,
  `smeduc` varchar(30) DEFAULT NULL,
  `smcontact` varchar(20) DEFAULT NULL,
  `smaddress` text DEFAULT NULL,
  `smoccu` varchar(30) DEFAULT NULL,
  `smcompany` varchar(30) DEFAULT NULL,
  `snsibling` varchar(10) DEFAULT NULL,
  `spcyincome` varchar(50) DEFAULT NULL,
  `spschname` text DEFAULT NULL,
  `spsaddress` text DEFAULT NULL,
  `spstype` varchar(20) DEFAULT NULL,
  `spscourse` varchar(50) DEFAULT NULL,
  `spsyrlvl` varchar(20) DEFAULT NULL,
  `spsgwa` int(10) DEFAULT NULL,
  `spsraward` text DEFAULT NULL,
  `spsdawardrceive` date DEFAULT NULL,
  `scsintend` text DEFAULT NULL,
  `scsadd` text DEFAULT NULL,
  `scschooltype` varchar(20) DEFAULT NULL,
  `sccourse` varchar(50) DEFAULT NULL,
  `sccourseprio` varchar(50) DEFAULT NULL,
  `scsyrlvl` varchar(20) DEFAULT NULL,
  `spass` varchar(100) DEFAULT NULL,
  `sdsprc` varchar(20) DEFAULT NULL,
  `sdsprcstat` varchar(20) DEFAULT NULL,
  `sdspgm` varchar(20) DEFAULT NULL,
  `sdspgmstat` varchar(20) DEFAULT NULL,
  `sdspcr` varchar(20) DEFAULT NULL,
  `sdspcrstat` varchar(20) DEFAULT NULL,
  `sdstbytpic` varchar(20) DEFAULT NULL,
  `sdstbytpicstat` varchar(20) DEFAULT NULL,
  `sdsbrgyin` varchar(20) DEFAULT NULL,
  `sdsbrgyinstat` varchar(20) DEFAULT NULL,
  `sdscef` varchar(20) DEFAULT NULL,
  `sdscefstat` varchar(20) DEFAULT NULL,
  `sdspsa` varchar(20) DEFAULT NULL,
  `sdspsastat` varchar(20) DEFAULT NULL,
  `sdsobr` varchar(20) NOT NULL,
  `sdsobrstat` varchar(20) NOT NULL,
  `student_profile_image` varchar(100) DEFAULT NULL,
  `s_added_on` date DEFAULT NULL,
  `s_applied_on` date DEFAULT NULL,
  `s_verification_code` varchar(100) DEFAULT NULL,
  `s_email_verify` varchar(10) DEFAULT NULL,
  `s_account_status` varchar(20) DEFAULT NULL,
  `s_grant_stat` varchar(20) NOT NULL,
  `s_scholar_stat` varchar(20) NOT NULL,
  `s_scholarship_type` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Here are my entities in my table. I tried to change something to data types and number I can't change and nothing happens.

Body:
You can set innodb_strict_mode to OFF with the SQL statement

SET innodb_strict_mode=OFF;

But that's kind of like catching and ignoring exceptions: all you're doing is concealing serious errors from your application.

The row-length limit in MySQL / MariaDB / InnoDB is a hard limit. If you try to exceed it your INSERT and UPDATE statements will fail.

You said your requirement is to extend a table with a few extra columns. And, in doing that you've hit the row-length limit. It happens (Remarks about the programmer who came before you removed ... this is a family-friendly web site.)

What can you do?

An easy fix: Change the table's CHARSET from utf8mb4 to utf8. That way you need three, rather than four bytes, per VARCHAR character. But utf8 is deprecated: it can't represent emojis and some other characters.

Next possible fix. Identify the VARCHAR columns that don't need Unicode. sdbirth? s_verification_code? student_profile_image? Declare those colums with

CHARACTER SET latin1 COLLATE latin1_bin

If you make this change to s_verification_code and student_profile_image you'll save 600 bytes-- one byte per character rather than four, for two 100-character columns. That's enough that you can probably finish this task and pass off this table to your (unsuspecting) successor.

Another idea Change some of your VARCHAR() columns to TEXT columns. But beware! this slows down queries.  If your application has mostly SELECT * queries in it you probably don't want to do this. If it has mostly SELECT column, column, column queries this is probably OK.

A slightly harder fix:  Reduce the width of some of your fields. Does every personal name have to be stored as VARCHAR(50)? Will VARCHAR(30) do the trick? Do you need 10 characters for gender?  Can you represent date-of-birth with a DATE datatype? It will take three bytes rather than the 40 (VARCHAR(10)) it now uses.

The right fix Rework your app so some of that data (contact information, etc) for each student lives in different tables.  Or, create a new table for the new data you're adding.


问:
Does Python have a ternary conditional operator?
Is there a ternary conditional operator in Python?</p>

答:
There are multiple ways. The simplest one is to use the condition inside the "print" method.

You can use

```<code>print("Twenty" if number == 20 else "Not twenty")
</code>```

Which is equivalent to:

```<code>if number == 20:
    print("Twenty")
else:
    print("Not twenty")
</code>```

In this way, more than two statements are also possible to print. For example:

```<code>if number == 20:
    print("Twenty")
elif number < 20:
    print("Lesser")
elif 30 > number > 20:
    print("Between")
else:
    print("Greater")
</code>```

can be written as:

```<code>print("Twenty" if number == 20 else "Lesser" if number < 20 else "Between" if 30 > number > 20 else "Greater")
</code>```

OwnerDisplayName: koldfyre

LastEditorDisplayName: Vinko Vrsalovic

Body:
There are multiple ways. The simplest one is to use the condition inside the "print" method.

You can use

print("Twenty" if number == 20 else "Not twenty")

Which is equivalent to:

if number == 20:
    print("Twenty")
else:
    print("Not twenty")

In this way, more than two statements are also possible to print. For example:

if number == 20:
    print("Twenty")
elif number < 20:
    print("Lesser")
elif 30 > number > 20:
    print("Between")
else:
    print("Greater")

can be written as:

print("Twenty" if number == 20 else "Lesser" if number < 20 else "Between" if 30 > number > 20 else "Greater")


问:
Having trouble loading a javascript (images don't load)
I downloaded a calendar javascript. My working directory is /user. I put the script into /user/js/calendar. In my HTML located at user/, I have...

```<code><script language="JavaScript" src="js/calendar/calendar_us.js"></script>
<link rel="stylesheet" href="js/calendar/calendar.css">
</code>```

The .js and .css load, and I see the calendar form, but the images under user/js/calendar/img do not load when it's displayed on the browser.

The image reference code in the downloaded javascript is below

```<code><img src="' + this.a_tpl.imgpath + 'next_year.gif" />
</code>```

this.a_tpl.imgpath is 'img/'. Is there something I need to add or modify in my HTML or in the .js file to make correct relative reference to the files in user/js/calendar/img?

答:
The image tag is trying to load the image from /user/img/next_year.gif. Either move the images there, or add the path to the code:

```<code><img src="js/calendar/' + this.a_tpl.imgpath + 'next_year.gif" />
</code>```

Note that image tags will load images relative to where the page was loaded from, while images used in a stylesheet will load images relative to where the style sheet file was loaded from.

Body:
I downloaded a calendar javascript. My working directory is /user. I put the script into /user/js/calendar. In my HTML located at user/, I have...

<link rel="stylesheet" href="js/calendar/calendar.css">

The .js and .css load, and I see the calendar form, but the images under user/js/calendar/img do not load when it's displayed on the browser.

The image reference code in the downloaded javascript is below

this.a_tpl.imgpath is 'img/'. Is there something I need to add or modify in my HTML or in the .js file to make correct relative reference to the files in user/js/calendar/img?

Body:
The image tag is trying to load the image from /user/img/next_year.gif. Either move the images there, or add the path to the code:

<img src="js/calendar/' + this.a_tpl.imgpath + 'next_year.gif" />

Note that image tags will load images relative to where the page was loaded from, while images used in a stylesheet will load images relative to where the style sheet file was loaded from.


问:
Php not able to connect to MySQL workbench when using IP as host, but works fine when using localhost
This is the error I get when using php code

"mysql_connect($host,$user,$password)", where $host="IP_of_my_system" :

```<code>Warning: mysql_connect(): Host 'xxx' is not allowed to connect to this MySQL server in C:\xampp\htdocs\mysqltest\insert.php on line 4
</code>```

But when using localhost instead of IP, it works fine.

Why is this behavior?

答: I had a similar problem and only worked solution is creating a new user with same specification as old user. Strange, but hope it helps someone else with the same problem.</p>

Body:
This is the error I get when using php code

"mysql_connect($host,$user,$password)", where $host="IP_of_my_system" :

Warning: mysql_connect(): Host 'xxx' is not allowed to connect to this MySQL server in C:\xampp\htdocs\mysqltest\insert.php on line 4

But when using localhost instead of IP, it works fine.

Why is this behavior?


问:
passing data to spreadsheet together apps script
this two function works together in on HTML code i want to append data to last row in spreadsheet together
i tried to get last row and column but ssume if delayed alittle bit it will replace in another record , so how can i pass all outputs so it can be appended in on row.

result i'm seeking

Html Code

```<code>    <html>
      <head>
        <base target="_top">
      </head>
      <body>

        <button id = "find-me">Show my location</button><br/>
        <p id = "status"></p>
        <a id = "map-link" target="_blank"></a>
  <p id = "1"></p>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
    integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
  </script>
  <script>
    $(document).ready(function() {
       google.script.run.withSuccessHandler(function (datareturned) {

        alert(datareturned)
        $('#1').text(datareturned)
      }).getuser_email();
  });
          function geoFindMe() {

            const status = document.querySelector('#status');
            const mapLink = document.querySelector('#map-link');

            mapLink.href = '';
            mapLink.textContent = '';

            function success(position) {

              const latitude  = position.coords.latitude;
              const longitude = position.coords.longitude;

              google.script.run.saveCoordinates(latitude,longitude);

              status.textContent = '';
              mapLink.href = 'https://www.openstreetmap.org/#map=18/' + `${latitude}\/${longitude}`;
              mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
            }

            function error() {
              status.textContent = 'Unable to retrieve your location';
            }

            if(!navigator.geolocation) {
              status.textContent = 'Geolocation is not supported by your browser';
            } else {
              status.textContent = 'Locating…';
              navigator.geolocation.getCurrentPosition(success, error);
            }

          }

             document.querySelector('#find-me').addEventListener('load', geoFindMe);
                window.onload = geoFindMe
           </script>
          </body>
    </html>
</code>```
```<code>
    function saveCoordinates(latitude,longitude){
        const sheet = SpreadsheetApp.getActiveSheet();
    const rowContents = [latitude+","+longitude];
    var lastRow = sheet.getLastRow();
    var lastColumn = sheet.getLastColumn();
    var lastCell = sheet.getRange(lastRow, lastColumn);
      sheet.appendRow(rowContents);

    }
function getuser_email(){
   const email = Session.getActiveUser().getEmail();
     return email;
</code>```

答:
I thought your question was how to make both functions respond synchronously.  You mentioned delay which I thought was delay in getting data from one or the other function.

To put the latitude and longitude into a new row you could simply do this.

```<code>function saveCoordinates(latitude,longitude){
  const sheet = SpreadsheetApp.getActiveSheet();
  const rowContents = [latitude,longitude];
  sheet.appendRow(rowContents);
}
</code>```

Body:
this two function works together in on HTML code i want to append data to last row in spreadsheet together
i tried to get last row and column but ssume if delayed alittle bit it will replace in another record , so how can i pass all outputs so it can be appended in on row.

result i'm seeking

Html Code

        <base target="_top">

        <button id = "find-me">Show my location</button>

    function saveCoordinates(latitude,longitude){
        const sheet = SpreadsheetApp.getActiveSheet();
    const rowContents = [latitude+","+longitude];
    var lastRow = sheet.getLastRow();
    var lastColumn = sheet.getLastColumn();
    var lastCell = sheet.getRange(lastRow, lastColumn);
      sheet.appendRow(rowContents);

    }
function getuser_email(){
   const email = Session.getActiveUser().getEmail();
     return email;

Body:
I thought your question was how to make both functions respond synchronously.  You mentioned delay which I thought was delay in getting data from one or the other function.

To put the latitude and longitude into a new row you could simply do this.

function saveCoordinates(latitude,longitude){
  const sheet = SpreadsheetApp.getActiveSheet();
  const rowContents = [latitude,longitude];
  sheet.appendRow(rowContents);
}


问:
Why extra query running in eloquent
Following is my controller code which is cause running useless query first then

```<code>        $users = Interest::with('users')->
        whereIn('id',Auth::user()->interests->pluck('id'))
        ->take(5)->get();
</code>```

query log from laravel dev bar

I wonder why extra query before real one

答:
I think you can use this way no extra query will be execute

```<code>        $interest_ids = Interest::addSelect('id')->whereHas('users', function ($query){
            $query->where('user_id', Auth::id());
        })->get()->pluck('id');

        return User::wherehas('interests', function($query) use($interest_ids){
            $query->whereIn('interest_id', $interest_ids);
        })->take(5)->get();

</code>```

According to your eloquent it seems you are try get other user with same interest and i believe this can be done in your way but it will load multiple queries because of eager loading which is not optimal only according to your case so i think i my way you can have only two queries one for loading interest ids and one for get other user

Title: Why extra query running in eloquent

Body:
Following is my controller code which is cause running useless query first then

        $users = Interest::with('users')->
        whereIn('id',Auth::user()->interests->pluck('id'))
        ->take(5)->get();

query log from laravel dev bar

I wonder why extra query before real one

Body:
I think you can use this way no extra query will be execute

        $interest_ids = Interest::addSelect('id')->whereHas('users', function ($query){
            $query->where('user_id', Auth::id());
        })->get()->pluck('id');

        return User::wherehas('interests', function($query) use($interest_ids){
            $query->whereIn('interest_id', $interest_ids);
        })->take(5)->get();

According to your eloquent it seems you are try get other user with same interest and i believe this can be done in your way but it will load multiple queries because of eager loading which is not optimal only according to your case so i think i my way you can have only two queries one for loading interest ids and one for get other user


问:
Toit Getting "Out of memory" error while posting to HTTP API
I am tryng to scan BLE devices and once I find some particular vendor, post some data to HTTP server.
For this purpose I'm using two different ESP32 devkits and Toit platform.

My code is very simple:

```<code>import ble
import http
import net
import device

main:
  bd := ble.Device.default

  bd.scan: | bleDevice/ble.RemoteDevice |
    print "Device detected " + bleDevice.address.stringify;
    if bleDevice.data.manufacturer_data.size == 13 and bleDevice.data.manufacturer_data[0] == 0x9a and bleDevice.data.manufacturer_data[1] == 0x08 :
      print "Teltonika sensor"
      post bleDevice

post sensor:
  network := net.open
  client := http.Client network
  json_payload := {
    "t": (sensor.data.manufacturer_data[4].to_float * 256 + sensor.data.manufacturer_data[5].to_float) / 100,
    "h": sensor.data.manufacturer_data[6].to_float,
    "tower" : device.name, // ESP32 Tower name
    "mac" : sensor.address.stringify,
    "sensor" : sensor.data.name
  }

  client.post_json --host="ingest.XXXXXXXXX.eu" --path="/" json_payload
</code>```

However, I often see exception:

```<code>    EXCEPTION error.
    Out of memory
    0: tcp_connect_              system/modules/tcp.toit:176:3
    1: TcpSocket.connect         system/modules/tcp.toit:136:12
    2: TcpSocket.connect         system/modules/tcp.toit:132:12
    3: WifiNetworkInterface.tcp_connect system/components/wifi.toit:98:7
    4: NetworkInterfaceResource.tcp_connect system/components/network.toit:91:26
    5: register_network.<lambda> system/components/network.toit:26:23
    6: RpcBroker.get_handler_.<block>.<lambda> tools/rpc.toit:81:17
    7: RpcBroker.process_handler.<block>.<block> tools/rpc.toit:122:27
    8: RpcBroker.process_handler.<block> tools/rpc.toit:120:43
    9: catch.<block>             <sdk>/core/exceptions.toit:114:10
    10: catch                     <sdk>/core/exceptions.toit:112:1
    11: catch                     <sdk>/core/exceptions.toit:87:10
    12: RpcBroker.process_handler tools/rpc.toit:120:5
    13: RpcBroker.listen_.<lambda> tools/rpc.toit:117:25
    14: TaskCache_.broker_task_   <sdk>/monitor.toit:434:14
    15: TaskCache_.run.<block>.<lambda> <sdk>/monitor.toit:430:42
</code>```

also:

```<code>EXCEPTION error.
FAILED TO CONNECT
  0: Network.connect           system/kernel/network.toit:101:5
  1: NetworkInterfaceResource.open system/components/network.toit:72:34
  2: register_network.<lambda> system/components/network.toit:16:29
  3: RpcBroker.process_handler.<block>.<block> tools/rpc.toit:122:27
  4: RpcBroker.process_handler.<block> tools/rpc.toit:120:43
  5: catch.<block>             <sdk>/core/exceptions.toit:114:10
  6: catch                     <sdk>/core/exceptions.toit:112:1
  7: catch                     <sdk>/core/exceptions.toit:87:10
  8: RpcBroker.process_handler tools/rpc.toit:120:5
  9: RpcBroker.listen_.<lambda> tools/rpc.toit:117:25
 10: TaskCache_.broker_task_   <sdk>/monitor.toit:434:14
 11: TaskCache_.run.<block>.<lambda> <sdk>/monitor.toit:430:42
</code>```

What is the problem here? Should it not use GC to control memory? Can I explicitly delete variables? Do I have to try/catch something here?

答:
TSL connections (especially the handshake) are very resource intensive.

Unfortunately, they sometimes push Toit programs over the limit.

As a user you should not need to do anything differently (unless you have big data structures or buffers lying around that aren't necessary).

The v1.6 release (released early February 2022) has lots of improvements with respect to memory, so hopefully this error should become much less frequent.

There is also work started on a better garbage collector, which will also improve the memory situation.

Update 2022-12-20:
Toit v2 (the open-source version) now has a significantly better garbage collector.

Also, I missed the fact that the client.post_json didn't do anything with the response. Ideally, the response should be drained to close the connection and release the associated resources/memory. The garbage collector will do this eventually by itself, but it might take longer than needed.

With the http-package v1.* you could do the following:

```<code>  response := client.post_json --host="ingest.XXXXXXXXX.eu" --path="/" json_payload
  while response.body.read: /* do nothing */
</code>```

Body:
I am tryng to scan BLE devices and once I find some particular vendor, post some data to HTTP server.
For this purpose I'm using two different ESP32 devkits and Toit platform.

My code is very simple:

import ble
import http
import net
import device

main:
  bd := ble.Device.default

  bd.scan: | bleDevice/ble.RemoteDevice |
    print "Device detected " + bleDevice.address.stringify;
    if bleDevice.data.manufacturer_data.size == 13 and bleDevice.data.manufacturer_data[0] == 0x9a and bleDevice.data.manufacturer_data[1] == 0x08 :
      print "Teltonika sensor"
      post bleDevice

post sensor:
  network := net.open
  client := http.Client network
  json_payload := {
    "t": (sensor.data.manufacturer_data[4].to_float * 256 + sensor.data.manufacturer_data[5].to_float) / 100,
    "h": sensor.data.manufacturer_data[6].to_float,
    "tower" : device.name, // ESP32 Tower name
    "mac" : sensor.address.stringify,
    "sensor" : sensor.data.name
  }

  client.post_json --host="ingest.XXXXXXXXX.eu" --path="/" json_payload

However, I often see exception:

    EXCEPTION error.
    Out of memory
    0: tcp_connect_              system/modules/tcp.toit:176:3
    1: TcpSocket.connect         system/modules/tcp.toit:136:12
    2: TcpSocket.connect         system/modules/tcp.toit:132:12
    3: WifiNetworkInterface.tcp_connect system/components/wifi.toit:98:7
    4: NetworkInterfaceResource.tcp_connect system/components/network.toit:91:26
    5: register_network.<lambda> system/components/network.toit:26:23
    6: RpcBroker.get_handler_.<block>.<lambda> tools/rpc.toit:81:17
    7: RpcBroker.process_handler.<block>.<block> tools/rpc.toit:122:27
    8: RpcBroker.process_handler.<block> tools/rpc.toit:120:43
    9: catch.<block>             <sdk>/core/exceptions.toit:114:10
    10: catch                     <sdk>/core/exceptions.toit:112:1
    11: catch                     <sdk>/core/exceptions.toit:87:10
    12: RpcBroker.process_handler tools/rpc.toit:120:5
    13: RpcBroker.listen_.<lambda> tools/rpc.toit:117:25
    14: TaskCache_.broker_task_   <sdk>/monitor.toit:434:14
    15: TaskCache_.run.<block>.<lambda> <sdk>/monitor.toit:430:42

also:

EXCEPTION error.
FAILED TO CONNECT
  0: Network.connect           system/kernel/network.toit:101:5
  1: NetworkInterfaceResource.open system/components/network.toit:72:34
  2: register_network.<lambda> system/components/network.toit:16:29
  3: RpcBroker.process_handler.<block>.<block> tools/rpc.toit:122:27
  4: RpcBroker.process_handler.<block> tools/rpc.toit:120:43
  5: catch.<block>             <sdk>/core/exceptions.toit:114:10
  6: catch                     <sdk>/core/exceptions.toit:112:1
  7: catch                     <sdk>/core/exceptions.toit:87:10
  8: RpcBroker.process_handler tools/rpc.toit:120:5
  9: RpcBroker.listen_.<lambda> tools/rpc.toit:117:25
 10: TaskCache_.broker_task_   <sdk>/monitor.toit:434:14
 11: TaskCache_.run.<block>.<lambda> <sdk>/monitor.toit:430:42

What is the problem here? Should it not use GC to control memory? Can I explicitly delete variables? Do I have to try/catch something here?

Body:
TSL connections (especially the handshake) are very resource intensive.

Unfortunately, they sometimes push Toit programs over the limit.

As a user you should not need to do anything differently (unless you have big data structures or buffers lying around that aren't necessary).

The v1.6 release (released early February 2022) has lots of improvements with respect to memory, so hopefully this error should become much less frequent.

There is also work started on a better garbage collector, which will also improve the memory situation.

Update 2022-12-20:
Toit v2 (the open-source version) now has a significantly better garbage collector.

Also, I missed the fact that the client.post_json didn't do anything with the response. Ideally, the response should be drained to close the connection and release the associated resources/memory. The garbage collector will do this eventually by itself, but it might take longer than needed.

With the http-package v1.* you could do the following:

  response := client.post_json --host="ingest.XXXXXXXXX.eu" --path="/" json_payload
  while response.body.read: /* do nothing */


问:
Create unique combinations regardless of subset size
I am doing a project that requires getting unique combinations in Python regardless of the subset size.

Lets say I have a list of sizes [1,2,2,3,4,5] and a size bound of 8. I want combinations that have all the elements and no repeat such that the sum of each combination should be less than or equal to 8. Another restriction is that the subtraction of the sum and the bound should be minimum.

For example in this case the answer should be [5,3] [4,2,2] [3,1] this way the total waste out of 8 will be 4 which is (3+1)-8=4.

答:
You could use a recursive function to "brute force" the packing combinations and get the best fit out of those:

```<code>def pack(sizes,bound,subset=[]):
    if not sizes:                   # all sizes used
        yield [subset]              # return current subset
        return
    if sizes and not subset:           # start new subset
        i,m = max(enumerate(sizes),key=lambda s:s[1])
        subset = [m]                   # using largest size
        sizes  = sizes[:i]+sizes[i+1:] # (to avoid repeats)
    used = sum(subset)
    for i,size in enumerate(sizes):    # add to current subset
        if subset and size>subset[-1]: # non-increasing order
            continue                   # (to avoid repeats)
        if used + size <= bound:
            yield from pack(sizes[:i]+sizes[i+1:],bound,subset+[size])
    if sizes:
        for p in pack(sizes,bound): # add more subsets
            yield [subset,*p]

def bestFit(sizes,bound):
    packs = pack(sizes,bound)
    return min(packs,key = lambda p : bound*len(p)-sum(sizes))
</code>```

output:

```<code>for p in pack([1,2,3,4,5],8):
    print(p,8*len(p)-sum(map(sum,p)))

[[5, 1], [4], [3, 2]] 9
[[5, 2, 1], [4, 3]] 1
[[5, 2], [4, 3, 1]] 1
[[5, 2], [4], [3, 1]] 9
[[5, 3], [4, 2, 1]] 1
[[5, 3], [4], [2, 1]] 9
[[5], [4, 1], [3, 2]] 9
[[5], [4, 2], [3, 1]] 9
[[5], [4, 3], [2, 1]] 9
[[5], [4], [3, 2, 1]] 9
[[5], [4], [3], [2, 1]] 17

print(*bestFit([1,2,3,4,5],8))
# [5, 2, 1] [4, 3]

print(*bestFit([1,2,3,4,5,6,7,8,9],18))
# [9, 1] [8, 4, 3, 2] [7, 6, 5]
</code>```

This will take exponentially longer as your list of sizes gets larger but it may be enough if you only have very small inputs

Body:
You could use a recursive function to "brute force" the packing combinations and get the best fit out of those:

def pack(sizes,bound,subset=[]):
    if not sizes:                   # all sizes used
        yield [subset]              # return current subset
        return
    if sizes and not subset:           # start new subset
        i,m = max(enumerate(sizes),key=lambda s:s[1])
        subset = [m]                   # using largest size
        sizes  = sizes[:i]+sizes[i+1:] # (to avoid repeats)
    used = sum(subset)
    for i,size in enumerate(sizes):    # add to current subset
        if subset and size>subset[-1]: # non-increasing order
            continue                   # (to avoid repeats)
        if used + size <= bound:
            yield from pack(sizes[:i]+sizes[i+1:],bound,subset+[size])
    if sizes:
        for p in pack(sizes,bound): # add more subsets
            yield [subset,*p]

def bestFit(sizes,bound):
    packs = pack(sizes,bound)
    return min(packs,key = lambda p : bound*len(p)-sum(sizes))

output:

for p in pack([1,2,3,4,5],8):
    print(p,8*len(p)-sum(map(sum,p)))

[[5, 1], [4], [3, 2]] 9
[[5, 2, 1], [4, 3]] 1
[[5, 2], [4, 3, 1]] 1
[[5, 2], [4], [3, 1]] 9
[[5, 3], [4, 2, 1]] 1
[[5, 3], [4], [2, 1]] 9
[[5], [4, 1], [3, 2]] 9
[[5], [4, 2], [3, 1]] 9
[[5], [4, 3], [2, 1]] 9
[[5], [4], [3, 2, 1]] 9
[[5], [4], [3], [2, 1]] 17

print(*bestFit([1,2,3,4,5],8))
# [5, 2, 1] [4, 3]

print(*bestFit([1,2,3,4,5,6,7,8,9],18))
# [9, 1] [8, 4, 3, 2] [7, 6, 5]

This will take exponentially longer as your list of sizes gets larger but it may be enough if you only have very small inputs


问:
Perl advice - Taking in a file and changing contents
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

```<code>  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4
</code>```

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

```<code>      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white
</code>```

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

答:
Using zigdon's suggestion</p>

```<code>#!/usr/bin/perl
use strict;
use warnings;
use 5.014;

my %param = (pet   => [qw/dog cat fish/],
             color => [qw/ red blue purple brown white/],
);

while (<DATA>) {
    if (/^(pet|color):\s*(\d)$/) {
        print "$1: $param{ $1 }[$2]\n";
    }
    else {
        print;
    }
}

__DATA__
id: 1
Relationship: ""
name: shelby
pet: 1
color:4
</code>```

Body:
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

Body:
Using zigdon's suggestion

#!/usr/bin/perl
use strict;
use warnings;
use 5.014;

my %param = (pet   => [qw/dog cat fish/],
             color => [qw/ red blue purple brown white/],
);

while (<DATA>) {
    if (/^(pet|color):\s*(\d)$/) {
        print "$1: $param{ $1 }[$2]\n";
    }
    else {
        print;
    }
}

__DATA__
id: 1
Relationship: ""
name: shelby
pet: 1
color:4


问:
I can't connect to mongodb with mongoose from manjaro
Previously running $ mongod on Ubuntu would open my mongodb shell. Now while using manjaro, running $ mongod would give me this:

```<code>{"t":{"$date":"2022-02-06T17:14:55.260+03:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2022-02-06T17:14:55.264+03:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}}
{"t":{"$date":"2022-02-06T17:14:55.265+03:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2022-02-06T17:14:55.265+03:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":37548,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"burka"}}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.5","gitVersion":"d65fd89df3fc039b5c55933c0f71d647a54510ae","openSSLVersion":"OpenSSL 1.1.1m  14 Dec 2021","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"ManjaroLinux","version":"21.2.3"}}}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"IllegalOperation: Attempted to create a lock file on a read-only directory: /data/db"}}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"REPL",     "id":4784900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"COMMAND",  "id":4784901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"SHARDING", "id":4784902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"NETWORK",  "id":20562,   "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"NETWORK",  "id":4784905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"-",        "id":20520,   "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisitions."}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"NETWORK",  "id":4784918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"SHARDING", "id":4784921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"ASIO",     "id":22582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress activity."}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"COMMAND",  "id":4784923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"-",        "id":4784931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"FTDC",     "id":4784926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":20565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":23138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}
</code>```

And i can't connect to mongodb shell using mongoose from nodejs either.
Anybody know how to fix this??
Here is my configuration file

```<code># mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /home/biruk/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

</code>```

while running mongo works i cant connect to the shell using mongoose. it requires mongod to work somehow.

答:
This line say it all:

```<code>    {"t":{"$date":"2022-02-06T16:39:24.491+03:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file."}}
</code>```

Posible options:

Check if you are using the correct /etc/mongodb.conf file where you have the dbPath specified.

Check if you have the data path created and with coorect permissions.

Body:
Previously running $ mongod on Ubuntu would open my mongodb shell. Now while using manjaro, running $ mongod would give me this:

{"t":{"$date":"2022-02-06T17:14:55.260+03:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2022-02-06T17:14:55.264+03:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}}
{"t":{"$date":"2022-02-06T17:14:55.265+03:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2022-02-06T17:14:55.265+03:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2022-02-06T17:14:55.267+03:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":37548,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"burka"}}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.5","gitVersion":"d65fd89df3fc039b5c55933c0f71d647a54510ae","openSSLVersion":"OpenSSL 1.1.1m  14 Dec 2021","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"ManjaroLinux","version":"21.2.3"}}}
{"t":{"$date":"2022-02-06T17:14:55.268+03:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"IllegalOperation: Attempted to create a lock file on a read-only directory: /data/db"}}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"REPL",     "id":4784900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"COMMAND",  "id":4784901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"SHARDING", "id":4784902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2022-02-06T17:14:55.270+03:00"},"s":"I",  "c":"NETWORK",  "id":20562,   "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"NETWORK",  "id":4784905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"-",        "id":20520,   "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisitions."}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"NETWORK",  "id":4784918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"SHARDING", "id":4784921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"ASIO",     "id":22582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress activity."}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"COMMAND",  "id":4784923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":4784929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"-",        "id":4784931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"FTDC",     "id":4784926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":20565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2022-02-06T17:14:55.271+03:00"},"s":"I",  "c":"CONTROL",  "id":23138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}

And i can't connect to mongodb shell using mongoose from nodejs either.
Anybody know how to fix this??
Here is my configuration file

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /home/biruk/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

while running mongo works i cant connect to the shell using mongoose. it requires mongod to work somehow.

Body:
This line say it all:

    {"t":{"$date":"2022-02-06T16:39:24.491+03:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file."}}

Posible options:

Check if you are using the correct /etc/mongodb.conf file where you have the dbPath specified.

Check if you have the data path created and with coorect permissions.