问:
Repeating animation on SwiftUI Image
Given the following struct:

```<code>struct PeopleList : View {
    @State var angle: Double = 0.0
    @State var isAnimating = true

    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever()
    }

    var body: some View {
        Button(action: {}, label: {
            Image(systemName: "arrow.2.circlepath")
                .rotationEffect(Angle(degrees: self.isAnimating ? self.angle : 0.0))
                .onAppear {
                    withAnimation(self.foreverAnimation) {
                        self.angle += 10.0
                    }
                }
        })
    }
}
</code>```

I was hoping that the Image would rotate clockwise and repeat until self.isAnimating is false although it's only animated once.

答:
Here is possible solution for continuous progressing on appear & start/stop. Tested with Xcode 11.4 / iOS 13.4.

```<code>struct PeopleList : View {
    @State private var isAnimating = false
    @State private var showProgress = false
    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever(autoreverses: false)
    }

    var body: some View {
        Button(action: { self.showProgress.toggle() }, label: {
            if showProgress {
                Image(systemName: "arrow.2.circlepath")
                    .rotationEffect(Angle(degrees: self.isAnimating ? 360 : 0.0))
                    .animation(self.isAnimating ? foreverAnimation : .default)
                    .onAppear { self.isAnimating = true }
                    .onDisappear { self.isAnimating = false }
            } else {
                Image(systemName: "arrow.2.circlepath")
            }
        })
        .onAppear { self.showProgress = true }
    }
}
</code>```

Title: Repeating animation on SwiftUI Image

Body:
Given the following struct:

struct PeopleList : View {
    @State var angle: Double = 0.0
    @State var isAnimating = true

    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever()
    }

    var body: some View {
        Button(action: {}, label: {
            Image(systemName: "arrow.2.circlepath")
                .rotationEffect(Angle(degrees: self.isAnimating ? self.angle : 0.0))
                .onAppear {
                    withAnimation(self.foreverAnimation) {
                        self.angle += 10.0
                    }
                }
        })
    }
}

I was hoping that the Image would rotate clockwise and repeat until self.isAnimating is false although it's only animated once.

Body:
Here is possible solution for continuous progressing on appear & start/stop. Tested with Xcode 11.4 / iOS 13.4.

struct PeopleList : View {
    @State private var isAnimating = false
    @State private var showProgress = false
    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever(autoreverses: false)
    }

    var body: some View {
        Button(action: { self.showProgress.toggle() }, label: {
            if showProgress {
                Image(systemName: "arrow.2.circlepath")
                    .rotationEffect(Angle(degrees: self.isAnimating ? 360 : 0.0))
                    .animation(self.isAnimating ? foreverAnimation : .default)
                    .onAppear { self.isAnimating = true }
                    .onDisappear { self.isAnimating = false }
            } else {
                Image(systemName: "arrow.2.circlepath")
            }
        })
        .onAppear { self.showProgress = true }
    }
}


来源: stackexchange

问:
Unable to get provider com.google.android.gms.ads.MobileAdsInitProvider: java.lang.IllegalStateException
I update my Android Studio (3.2.1) and its sdk to the latest version. After that it required a manual update for Manifest by adding these tags:

```<code><application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@drawable/ic_launcher"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="AllowBackup,GoogleAppIndexingWarning">

    <meta-data
        android:name="com.google.android.gms.ads.APP_ID"
        android:value="ca-app-pub-#############"/>

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".NewActivity" />
    <activity android:name=".PreviewActivity" />
    <activity android:name=".EditActivity" />
    <activity
        android:name=".preferencesdata.AboutActivity"
        android:theme="@style/Theme.AppCompat.DayNight.NoActionBar" />
    <activity android:name=".preferencesdata.SettingsActivity"
        android:label="@string/settings">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </activity>
</application>
</code>```

whereby instead the app ID I put the real id of my app. The value has also been changed to the right Ad Unit id as shown here https://developers.google.com/admob/android/quick-start. I also called this function in the MainActivity.kt:

```<code>MobileAds.initialize(this, resources.getString(R.string.banner_ad_unit_id))
</code>```

However, the problem could not be solved. It still prints as follows:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.easyapps.cryptnote, PID: 3991
    java.lang.RuntimeException: Unable to get provider com.google.android.gms.ads.MobileAdsInitProvider: java.lang.IllegalStateException:

    ******************************************************************************
    * The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers    *
    * should follow the instructions LINK to add a valid  *
    * App ID inside the AndroidManifest. Google Ad Manager publishers should     *
    * follow instructions here: LINK.                           *
    ******************************************************************************

        at android.app.ActivityThread.installProvider(ActivityThread.java:5156)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.IllegalStateException:

    ******************************************************************************
    * The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers    *
    * should follow the instructions here: LINK to add a valid  *
    * App ID inside the AndroidManifest. Google Ad Manager publishers should     *
    * follow instructions here: LINK.                           *
    ******************************************************************************

        at com.google.android.gms.internal.ads.zzmn.attachInfo(Unknown Source)
        at com.google.android.gms.ads.MobileAdsInitProvider.attachInfo(Unknown Source)
        at android.app.ActivityThread.installProvider(ActivityThread.java:5153)
            ... 10 more
</code>```

Why does this happen? I tried to research the issue, but I can't find any solutions. It seems to be an a new still unsolved issue.

答:
If you haven't published your app, try the following

```<code> <meta-data
      android:name="com.google.android.gms.ads.AD_MANAGER_APP"
      android:value="true"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I update my Android Studio (3.2.1) and its sdk to the latest version. After that it required a manual update for Manifest by adding these tags:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@drawable/ic_launcher"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="AllowBackup,GoogleAppIndexingWarning">

    <meta-data
        android:name="com.google.android.gms.ads.APP_ID"
        android:value="ca-app-pub-#############"/>

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".NewActivity" />
    <activity android:name=".PreviewActivity" />
    <activity android:name=".EditActivity" />
    <activity
        android:name=".preferencesdata.AboutActivity"
        android:theme="@style/Theme.AppCompat.DayNight.NoActionBar" />
    <activity android:name=".preferencesdata.SettingsActivity"
        android:label="@string/settings">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </activity>
</application>

whereby instead the app ID I put the real id of my app. The value has also been changed to the right Ad Unit id as shown here https://developers.google.com/admob/android/quick-start. I also called this function in the MainActivity.kt:

MobileAds.initialize(this, resources.getString(R.string.banner_ad_unit_id))

However, the problem could not be solved. It still prints as follows:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.easyapps.cryptnote, PID: 3991
    java.lang.RuntimeException: Unable to get provider com.google.android.gms.ads.MobileAdsInitProvider: java.lang.IllegalStateException:

    ******************************************************************************
    * The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers    *
    * should follow the instructions LINK to add a valid  *
    * App ID inside the AndroidManifest. Google Ad Manager publishers should     *
    * follow instructions here: LINK.                           *
    ******************************************************************************

        at android.app.ActivityThread.installProvider(ActivityThread.java:5156)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.IllegalStateException:

    ******************************************************************************
    * The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers    *
    * should follow the instructions here: LINK to add a valid  *
    * App ID inside the AndroidManifest. Google Ad Manager publishers should     *
    * follow instructions here: LINK.                           *
    ******************************************************************************

        at com.google.android.gms.internal.ads.zzmn.attachInfo(Unknown Source)
        at com.google.android.gms.ads.MobileAdsInitProvider.attachInfo(Unknown Source)
        at android.app.ActivityThread.installProvider(ActivityThread.java:5153)
            ... 10 more

Why does this happen? I tried to research the issue, but I can't find any solutions. It seems to be an a new still unsolved issue.

Body:
If you haven't published your app, try the following

 <meta-data
      android:name="com.google.android.gms.ads.AD_MANAGER_APP"
      android:value="true"/>


问:
Two children with the same key in React component
I know that there are similar questions to this one, I've tried them both (1), (2) and didn't work for my case.

Having an array of objects on props:

```<code>this.props.items = [ { name: 'a', price: 10},
                     { name: 'b', price: 20},
                     { name: 'c', price: 10},
                     { name: 'd', price: 30},
                   ];
</code>```

I want to create a list with all the price options and put that unique values on a dropdown so I'm doing this:

```<code>  const priceOptions = [{ text: '', value: '' }];

  const prices = [
    ...new Set(this.props.items.map(item => item.price)),
  ];
  prices.forEach(price => {
    if (price) {
      priceOptions.push({
        key: price,
        text: price,
        value: price,
      });
    }
</code>```

this code throws the error:

Warning: Encountered two children with the same key,
  ellipsisItem-NaN. Keys should be unique so that components maintain
  their identity across updates. Non-unique keys may cause children to
  be duplicated and/or omitted — the behavior is unsupported and could
  change in a future version.

Don't know what does ellipsisItem mean, that variable is not in the project.

I've read on the other questions' answers that it should be used the index instead of the element. So I changed it to:

```<code>  const prices = [
    ...new Set(this.props.items.map(item => item.price)),
  ];
  prices.forEach((price, index) => {
    if (price) {
      priceOptions.push({
        key: index,
        text: price,
        value: price,
      });
    }
  });
</code>```

but it throws the same error.

It is possible that in the array of objects to have more objects with same price but on dropdown it should show only the unique values.

From 10, 20, 10, 30 to 10, 20, 30

UPDATE
I'm adding also where it is rendered.

```<code>return (
  <Layout>
     ...
     <Dropdown
        placeholder="Price"
        onChange={this.searchHandlerPrice}
        options={priceOptions}
     />
</code>```

and the searchHandlerPrice:

```<code>  searchHandlerPrice = (event, data) => {
    const { getItems } = this.props;
    geItems({
      name: this.props.query.name,
      price: data.value,
    });
  };
</code>```

and < Dropdown >:

```<code>import React from 'react';
import { Dropdown } from 'semantic-ui-react';

import './Dropdown.styles.scss';

export default ({placeholder, options, onChange}) => {
    return (
        <Dropdown className="hello-dropdown"
            placeholder={placeholder}
            search
            selection
            options={options}
            onChange={onChange}
            clearable
        />
    );
};
</code>```

答:
Not sure where the problem lies. However, I recreated this problem using MATERIAL UI's SELECT tag and everything seems to be working fine.

In App.js

```<code>class App extends React.Component {
  items = [
    { name: "a", price: 10 },
    { name: "b", price: 20 },
    { name: "c", price: 10 },
    { name: "d", price: 30 }
  ];

  render() {
    return (
      <div className="App">
        <Select items={this.items} />
      </div>
    );
  }
}

export default App;
</code>```

in Select.js

```<code>export default function SelectForm(props) {
  const classes = useStyles();
  const [price, setPrice] = React.useState("");
  const [uniquePrice, setUniquePrice] = React.useState([]);

  React.useEffect(() => {
    const newPrice = [...new Set(props.items.map(item => item.price))];
    setUniquePrice(newPrice);
  }, [props]);

  const handleChange = event => {
    setPrice(event.target.value);
  };

  return (
    <div className="App">
      <FormControl className={classes.formControl}>
        <InputLabel id="demo-simple-select-label">Price List</InputLabel>
        <Select value={price} onChange={handleChange}>
          {uniquePrice.map(price => (
            <MenuItem key={price} value={price}>
              {price}
            </MenuItem>
          ))}
        </Select>
        <p>Selected Value: {price}</p>
      </FormControl>
    </div>
  );
}
</code>```

Checkout the following codeSandbox

https://codesandbox.io/s/material-ui-dropdown-yybhq

Hope this helps

Body:
I know that there are similar questions to this one, I've tried them both (1), (2) and didn't work for my case.

Having an array of objects on props:

this.props.items = [ { name: 'a', price: 10},
                     { name: 'b', price: 20},
                     { name: 'c', price: 10},
                     { name: 'd', price: 30},
                   ];

I want to create a list with all the price options and put that unique values on a dropdown so I'm doing this:

  const priceOptions = [{ text: '', value: '' }];

  const prices = [
    ...new Set(this.props.items.map(item => item.price)),
  ];
  prices.forEach(price => {
    if (price) {
      priceOptions.push({
        key: price,
        text: price,
        value: price,
      });
    }

this code throws the error:

Warning: Encountered two children with the same key,
  ellipsisItem-NaN. Keys should be unique so that components maintain
  their identity across updates. Non-unique keys may cause children to
  be duplicated and/or omitted — the behavior is unsupported and could
  change in a future version.

Don't know what does ellipsisItem mean, that variable is not in the project.

I've read on the other questions' answers that it should be used the index instead of the element. So I changed it to:

  const prices = [
    ...new Set(this.props.items.map(item => item.price)),
  ];
  prices.forEach((price, index) => {
    if (price) {
      priceOptions.push({
        key: index,
        text: price,
        value: price,
      });
    }
  });

but it throws the same error.

It is possible that in the array of objects to have more objects with same price but on dropdown it should show only the unique values.

From 10, 20, 10, 30 to 10, 20, 30

UPDATE
I'm adding also where it is rendered.

return (
  <Layout>
     ...
     <Dropdown
        placeholder="Price"
        onChange={this.searchHandlerPrice}
        options={priceOptions}
     />

and the searchHandlerPrice:

  searchHandlerPrice = (event, data) => {
    const { getItems } = this.props;
    geItems({
      name: this.props.query.name,
      price: data.value,
    });
  };

and < Dropdown >:

import React from 'react';
import { Dropdown } from 'semantic-ui-react';

import './Dropdown.styles.scss';

export default ({placeholder, options, onChange}) => {
    return (
        <Dropdown className="hello-dropdown"
            placeholder={placeholder}
            search
            selection
            options={options}
            onChange={onChange}
            clearable
        />
    );
};

Body:
Not sure where the problem lies. However, I recreated this problem using MATERIAL UI's SELECT tag and everything seems to be working fine.

In App.js

class App extends React.Component {
  items = [
    { name: "a", price: 10 },
    { name: "b", price: 20 },
    { name: "c", price: 10 },
    { name: "d", price: 30 }
  ];

  render() {
    return (
      <div className="App">
        <Select items={this.items} />
      </div>
    );
  }
}

export default App;

in Select.js

export default function SelectForm(props) {
  const classes = useStyles();
  const [price, setPrice] = React.useState("");
  const [uniquePrice, setUniquePrice] = React.useState([]);

  React.useEffect(() => {
    const newPrice = [...new Set(props.items.map(item => item.price))];
    setUniquePrice(newPrice);
  }, [props]);

  const handleChange = event => {
    setPrice(event.target.value);
  };

  return (
    <div className="App">
      <FormControl className={classes.formControl}>
        <InputLabel id="demo-simple-select-label">Price List</InputLabel>
        <Select value={price} onChange={handleChange}>
          {uniquePrice.map(price => (
            <MenuItem key={price} value={price}>
              {price}
            </MenuItem>
          ))}
        </Select>
        <p>Selected Value: {price}</p>
      </FormControl>
    </div>
  );
}

Checkout the following codeSandbox

https://codesandbox.io/s/material-ui-dropdown-yybhq

Hope this helps


问:
Why does Flask look in two different directories for templates?
I'm working on my first Flask-based Python web app. It is working fine locally, but when I upload it, I have a problem with file paths.

The Flask app is currently looking for two different pages, at these addresses:

mysite.org/flaskapp/
mysite.org/flaskapp/about/

The links to the first (home) page work fine. But the link to the About page jumps up a directory, to mysite.org/about/ .

I've looked at lots of stackoverflow questions and other resources, and I've tried using the template_folder argument, but I haven't been able to convince the app to look in the right place for both files.

Here is the mapping from the root file in the application:

```<code>@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html', posts=posts)

@app.route('/about')
def about():
    return render_template('about.html', title='About')

if __name__ == '__main__':
    app.run(debug=True)
</code>```

And here is the relevant part of the html template:

```<code>          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
              <a class="nav-item nav-link" href=".">Home</a>
              <a class="nav-item nav-link" href="./about">About</a>
            </div>
</code>```

答:
I'm assuming you're using standard Jinja2 templating, which means instead of hardcoding URL paths in your templates you should be using url_for().

url_for() takes the endpoint's func name as an argument and returns the local path for the URL, which means it does all the hard work for you. When adding url_for() to your template, it would look like this:

```<code><div class="collapse navbar-collapse" id="navbarToggle">
    <div class="navbar-nav mr-auto">
        <a class="nav-item nav-link" href="{{ url_for('home') }}">Home</a>
        <a class="nav-item nav-link" href="{{ url_for('about') }}">About</a>
    </div>
</div>
</code>```

Body:
I'm working on my first Flask-based Python web app. It is working fine locally, but when I upload it, I have a problem with file paths.

The Flask app is currently looking for two different pages, at these addresses:

mysite.org/flaskapp/
mysite.org/flaskapp/about/

The links to the first (home) page work fine. But the link to the About page jumps up a directory, to mysite.org/about/ .

I've looked at lots of stackoverflow questions and other resources, and I've tried using the template_folder argument, but I haven't been able to convince the app to look in the right place for both files.

Here is the mapping from the root file in the application:

@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html', posts=posts)

@app.route('/about')
def about():
    return render_template('about.html', title='About')

if __name__ == '__main__':
    app.run(debug=True)

And here is the relevant part of the html template:

              Home
              About

Body:
I'm assuming you're using standard Jinja2 templating, which means instead of hardcoding URL paths in your templates you should be using url_for().

url_for() takes the endpoint's func name as an argument and returns the local path for the URL, which means it does all the hard work for you. When adding url_for() to your template, it would look like this:

<div class="collapse navbar-collapse" id="navbarToggle">
    <div class="navbar-nav mr-auto">
        <a class="nav-item nav-link" href="{{ url_for('home') }}">Home</a>
        <a class="nav-item nav-link" href="{{ url_for('about') }}">About</a>
    </div>
</div>


问:
What is the proper way to repeat a format string in Julia?
I have an array of floats x and would like to print the last row to screen as integers. The following code does not work and yields ArgumentError: @printf: first or second argument must be a format string. How can I print with a variable format string?

```<code>using Printf
@printf("%i "^length(x[end,:]), x[end,:]...)
</code>```

答:
Using @eval to compile a simple print statement every time is really a bad approach.  There's no functionality for dynamic format strings etc. because Julia has a wide range of other nice tools to achieve the same things:

```<code>julia> join(stdout, (round(Int, y) for y in x[end, :]), " ")
1 0 1
</code>```

And printing an array is really not what printf is made for (not even in C).

That is not to say that a printf function taking a runtime format string wouldn't be a nice thing, but see here for the reasoning behind making it a macro.  I've never missed printf, but in case you really do, there's Formatting.jl, which provides all functinality you can imagine.

Body:
I have an array of floats x and would like to print the last row to screen as integers. The following code does not work and yields ArgumentError: @printf: first or second argument must be a format string. How can I print with a variable format string?

using Printf
@printf("%i "^length(x[end,:]), x[end,:]...)

Body:
Using @eval to compile a simple print statement every time is really a bad approach.  There's no functionality for dynamic format strings etc. because Julia has a wide range of other nice tools to achieve the same things:

julia> join(stdout, (round(Int, y) for y in x[end, :]), " ")
1 0 1

And printing an array is really not what printf is made for (not even in C).

That is not to say that a printf function taking a runtime format string wouldn't be a nice thing, but see here for the reasoning behind making it a macro.  I've never missed printf, but in case you really do, there's Formatting.jl, which provides all functinality you can imagine.


问:
how do launchSettings.json and appSettings.json work?
When creating a new .NET Core project Rider generates me a launchSettings.json, appSettings.json and appSettings.Development.json file. .NET Core seems to be able to handle those configurations on its own, there is nothing I have to code myself. None of these files get ignored by version control.

.NET Core is new to me, I only know Node backends yet. In Node I would install the dotenv package, create a new .env file with the content PORT=3000, add .env files to my .gitignore and access the port via process.env.PORT in my code. Those configuration values only work for me because they are outside from version control.

Comparing the approaches there are some things I didn't understand:

.env files should stay outside from version control, but these files don't? What about sensitive information? Or should I just add them to the .gitignore manually?

Taken from here it's clearly recommended to avoid having
multiple config files.

In a twelve-factor app, env vars are granular controls, each fully
  orthogonal to other env vars. They are never grouped together as
  “environments”, but instead are independently managed for each deploy.
  This is a model that scales up smoothly as the app naturally expands
  into more deploys over its lifetime.

So wouldn't it be better to delete the appSettings.Development.json
file and stick with appSettings.json?

The launchSettings.json contains information about the application
configuration (e.g. "applicationUrl":
"https://localhost:5001;http://localhost:5000",) and gets picked up
by version control. What if I want to change the port or other
settings? And since you know it's a json file I won't be able to add
placeholders for env variables e.g. http://{{baseUrl}}:{{port}}.
How to deal with that?

The launchSettings.json profiles have a environmentVariables
section with the initial value "ASPNETCORE_ENVIRONMENT":
"Development" but what is the purpose of appSettings.json then?

I think things are easier than they look but this concept confuses me. Would someone mind explaining it?

答:
While I do not know of .env files my answers to the rest are as follow:

When you have appsettings.json and appsettings.development.json and you specify in your ASPNETCORE_ENVIRONMENT that you are running development the settings in appsettings.development.json should overwrite the ones in appsettings.json while the ones not overwritten will be read from appsettings.json.
I however almost always use an appsettings.json containing only {} and then use appsettings.production.json and appsettings.development.json to be explicit about what settings go where.

With regards to security I think the intention is to leave the addition of secrets to the CD system like Octopus deploy or teamcity that will then exchange placeholder secrets for real ones when deploying the solution.

Launchsettings.json only relates to running the project locally without publishing, whether this be via Rider or Visual studio, it tells the system whether or not to launch a browser and what url to find the app on, the ports are just defaults that can be overwritten in code where you then have to match the newly chosen ports in the launchsettings to have debugging work as intended.

I hope that makes sense.


问:
No provider for ControlContainer - Angular 5
I am converting a purchased, third-party template into an Angular 5 app, and just ran into an error. I am very new to Angular 5 (I know AngularJS well however) and don't understand what it's trying to tell me? It seems to be related to a button which shows/hides the top navbar.

Error Message (from browser):

```<code>Error: Template parse errors:
No provider for ControlContainer ("imalize-styl-2 btn btn-primary " (click)="toggleNavigation()"><i class="fa fa-bars"></i> </a>
      [ERROR ->]<form role="search" class="navbar-form-custom" method="post" action="#">
        <div class="form-gro"): ng:///AppModule/TopNavigationNavbarComponent.html@4:6
</code>```

component.html:

```<code><div class="row border-bottom">
  <nav class="navbar navbar-static-top" role="navigation" style="margin-bottom: 0">
    <div class="navbar-header">
      <a class="minimalize-styl-2 btn btn-primary " (click)="toggleNavigation()"><i class="fa fa-bars"></i> </a>
      <form role="search" class="navbar-form-custom" method="post" action="#">
        <div class="form-group">
          <input type="text" placeholder="Search for something..." class="form-control" name="top-search" id="top-search">
        </div>
      </form>
    </div>
    <ul class="nav navbar-top-links navbar-right">
      <li>
        <a href="#">
          <i class="fa fa-sign-out"></i> Log out
        </a>
      </li>
    </ul>
  </nav>
</div>
</code>```

component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { smoothlyMenu } from '../../../app.helpers';

declare var jQuery: any;

@Component({
  selector: 'app-top-navigation-navbar',
  templateUrl: './top-navigation-navbar.component.html',
  styleUrls: ['./top-navigation-navbar.component.less']
})
export class TopNavigationNavbarComponent implements OnInit {

  toggleNavigation(): void {
    jQuery('body').toggleClass('mini-navbar');
    smoothlyMenu();
  }

  constructor() { }

  ngOnInit() {
  }

}
</code>```

app.module.ts (this seems to be something a mentioned a lot when I google this, however it is not the Form throwing the error.)

```<code>...
import { ReactiveFormsModule, FormControl, FormsModule } from '@angular/forms';
...
</code>```

答:
If you are trying to display plain HTML form from an Angular component, use ngNoForm in <form> tag like this.

```<code><form ngNoForm>
...
</form>
</code>```

This should prevent Angular from throwing Control Container Error.

ContentLicense: CC BY-SA 3.0

Body:
I am converting a purchased, third-party template into an Angular 5 app, and just ran into an error. I am very new to Angular 5 (I know AngularJS well however) and don't understand what it's trying to tell me? It seems to be related to a button which shows/hides the top navbar.

Error Message (from browser):

Error: Template parse errors:
No provider for ControlContainer ("imalize-styl-2 btn btn-primary " (click)="toggleNavigation()">
      [ERROR ->]<form role="search" class="navbar-form-custom" method="post" action="#">
        <div class="form-gro"): ng:///AppModule/TopNavigationNavbarComponent.html@4:6

component.html:

      <form role="search" class="navbar-form-custom" method="post" action="#">

          <input type="text" placeholder="Search for something..." class="form-control" name="top-search" id="top-search">

      </form>

           Log out

component.ts

import { Component, OnInit } from '@angular/core';
import { smoothlyMenu } from '../../../app.helpers';

declare var jQuery: any;

@Component({
  selector: 'app-top-navigation-navbar',
  templateUrl: './top-navigation-navbar.component.html',
  styleUrls: ['./top-navigation-navbar.component.less']
})
export class TopNavigationNavbarComponent implements OnInit {

  toggleNavigation(): void {
    jQuery('body').toggleClass('mini-navbar');
    smoothlyMenu();
  }

  constructor() { }

  ngOnInit() {
  }

}

app.module.ts (this seems to be something a mentioned a lot when I google this, however it is not the Form throwing the error.)

...
import { ReactiveFormsModule, FormControl, FormsModule } from '@angular/forms';
...

Body:
If you are trying to display plain HTML form from an Angular component, use ngNoForm in <form> tag like this.

<form ngNoForm>
...
</form>

This should prevent Angular from throwing Control Container Error.


问:
C++ typecasting vs implicit constructor
I'm implementing a c++-class representing a fraction. Here goes my code.

```<code>class Fraction
{
    public:
        Fraction(char i);
        Fraction(int i);
        Fraction(short i);
        Fraction(long int l);
#ifdef __LP64__
        Fraction(long long l);
#endif
        Fraction(float f);
        Fraction(double d);
        Fraction(double x, double y);

        Fraction operator +() const;
        Fraction operator -() const;

        Fraction& operator +=(const Fraction& other);
        Fraction& operator -=(const Fraction& other);
        Fraction& operator *=(const Fraction& other);
        Fraction& operator /=(const Fraction& other);

        bool operator ==(const Fraction& other);
        bool operator !=(const Fraction& other);
        bool operator  >(const Fraction& other);
        bool operator  <(const Fraction& other);
        bool operator >=(const Fraction& other);
        bool operator <=(const Fraction& other);

        operator double();
        operator float();

        static void commonize(Fraction& a, Fraction& b);
        void shorten();

        double getNumerator();
        double getDenominator();

        friend Fraction operator +(Fraction const& a, Fraction const& b);
        friend Fraction operator -(Fraction const& a, Fraction const& b);
        friend Fraction operator *(Fraction const& a, Fraction const& b);
        friend Fraction operator /(Fraction const& a, Fraction const& b);
        friend ostream& operator <<( ostream& o, const Fraction f);

    protected:
        double numerator, denominator;

};
</code>```

I now have two little problems.
Now trying to call

```<code>Fraction a(1, 2);
cout << (3 + a) << endl;
</code>```

simply results in this error:

```<code>fractiontest.cpp:26: error: ambiguous overload for ‘operator+’ in ‘3 + a’
fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in>
fractiontest.cpp:26: note:                 operator+(int, float) <built-in>
</code>```

All I'd really want is this:

```<code>explicit operator double();
explicit operator float();
</code>```

But apparently, this doesn't work. I'd like these two cast-operators to be called iff I use the cast notation. For example Fraction f(1, 2); double d = (double)(f);

答:
By definition the conversion operators are implicit. You can't make them explicit.

The normal solution is named member functions to do the conversion. I think you could also create a specialized template method that would look just like a static_cast and call through to the explicit class method.

Title: C++ typecasting vs implicit constructor

Body:
I'm implementing a c++-class representing a fraction. Here goes my code.

class Fraction
{
    public:
        Fraction(char i);
        Fraction(int i);
        Fraction(short i);
        Fraction(long int l);
#ifdef __LP64__
        Fraction(long long l);
#endif
        Fraction(float f);
        Fraction(double d);
        Fraction(double x, double y);

        Fraction operator +() const;
        Fraction operator -() const;

        Fraction& operator +=(const Fraction& other);
        Fraction& operator -=(const Fraction& other);
        Fraction& operator *=(const Fraction& other);
        Fraction& operator /=(const Fraction& other);

        bool operator ==(const Fraction& other);
        bool operator !=(const Fraction& other);
        bool operator  >(const Fraction& other);
        bool operator  <(const Fraction& other);
        bool operator >=(const Fraction& other);
        bool operator <=(const Fraction& other);

        operator double();
        operator float();

        static void commonize(Fraction& a, Fraction& b);
        void shorten();

        double getNumerator();
        double getDenominator();

        friend Fraction operator +(Fraction const& a, Fraction const& b);
        friend Fraction operator -(Fraction const& a, Fraction const& b);
        friend Fraction operator *(Fraction const& a, Fraction const& b);
        friend Fraction operator /(Fraction const& a, Fraction const& b);
        friend ostream& operator <<( ostream& o, const Fraction f);

    protected:
        double numerator, denominator;

};

I now have two little problems.
Now trying to call

Fraction a(1, 2);
cout << (3 + a) << endl;

simply results in this error:

fractiontest.cpp:26: error: ambiguous overload for ‘operator+’ in ‘3 + a’
fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in>
fractiontest.cpp:26: note:                 operator+(int, float) <built-in>

All I'd really want is this:

explicit operator double();
explicit operator float();

But apparently, this doesn't work. I'd like these two cast-operators to be called iff I use the cast notation. For example Fraction f(1, 2); double d = (double)(f);


问:
AWS ElasticSearch Request not giving response in Postman
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html

I am following above document, to connect to my AWS Elastic Search via Postman.

What I want to achieve sent request & get the response.

I put all things related Authentication as well, still it is giving timeout error.

It is giving error 'Could not get any response'.

My Postman settings related to SSL is also correct

Sample URL :

```<code>https://vpc-abc-yqb7jfwa6tw6ebwzphynyfvaka.ap-southeast-1.es.amazonaws.com/elasticsearch_index/_search?source={"query":{"bool":{"should":[{"multi_match":{"query":"abc","fields":["name.suggestion"],"fuzziness":1}}]}},"size":10,"_source":["name"],"highlight":{"fields":{"name.suggestion":{}},"pre_tags":["\u003Cem\u003E"],"post_tags":["\u003C\/em\u003E"]}}&source_content_type=application/json
</code>```

答:
Since your ES domain is in the VPC, you can't access if from the internet. The use of security groups and "allowing port" is unfortunately not enough.

The following is written in the docs:

If you try to access the endpoint in a web browser, however, you might find that the request times out. To perform even basic GET requests, your computer must be able to connect to the VPC. This connection often takes the form of a VPN, managed network, or proxy server.

Some options to consider are:

Setup a bastion host in the VPC in its public subnet, and ssh tunnel connection from the ES to your local mac through the bastion host. This would be the easiest ad-hoc proxy solution mentioned in the docs.

Accessing the EC directly from the bastion host (e.g. remote desktop)

Setting up a proxy server to proxy all requests from the internet into the ES.

Body:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html

I am following above document, to connect to my AWS Elastic Search via Postman.

What I want to achieve sent request & get the response.

I put all things related Authentication as well, still it is giving timeout error.

It is giving error 'Could not get any response'.

My Postman settings related to SSL is also correct

Sample URL :

https://vpc-abc-yqb7jfwa6tw6ebwzphynyfvaka.ap-southeast-1.es.amazonaws.com/elasticsearch_index/_search?source={"query":{"bool":{"should":[{"multi_match":{"query":"abc","fields":["name.suggestion"],"fuzziness":1}}]}},"size":10,"_source":["name"],"highlight":{"fields":{"name.suggestion":{}},"pre_tags":["\u003Cem\u003E"],"post_tags":["\u003C\/em\u003E"]}}&source_content_type=application/json


问:
What is the best way to make clickable text in java?
This is for an application so I don't want a hyperlink. I first tried using a Jbutton without all of border/background stuff and then hooking up an actionListener to it but I couldn't get it to the point where I thought it looked nice.  I also tried using a JLabel and hooking up a mouse listener to that but I also couldn't get it to look right.

Basically I would like a way using swing to make a button exactly like a url link in an application.  What is the standard way of doing this?

答:
but I couldn't get it to the point where I thought it looked nice

You might want to go into greater detail on just what "looked nice" means.  I can see you solving this by either a JButton or a JLabel, but the key is perhaps not to look for another solution but to play with the settings of the button or the label til they look nice. If you can't find a nice solution, then post your code (an SSCCE would work best of all) and perhaps we can help you.


问:
How to split a string on multiple delimiters stored in a list?
I have a list of delimiters like

```<code>List<String> delimiters= Arrays.asList(",",".");
</code>```

If I have a string like "a.b,c".

How to split on all the delimiters?

答:
You can use replaceAll on the string first and convert it all to a fixed delimiter (your choice) like this - then you can split it based on that:</p>

```<code>String[] newArray = stringArray.replaceAll("[\\.]", ",").split(",");
</code>```

Body:
I have a list of delimiters like

List<String> delimiters= Arrays.asList(",",".");

If I have a string like "a.b,c".

How to split on all the delimiters?

Body:
You can use replaceAll on the string first and convert it all to a fixed delimiter (your choice) like this - then you can split it based on that:

String[] newArray = stringArray.replaceAll("[\\.]", ",").split(",");


问:
How to render DIV tag only on desktop devices (width > 1024)
How to render DIV tag only on desktop devices (width > 1024px)

I don't want to use CSS display:none
because elements still loading while using CSS

Could be done with a javascript to render DIV tag over desktop devices

```<code><div class="desktop">

    <h1> Test </h1>
    <p> Hello World this content load only for desktop devices </p>
    <img src="test.png" width="100" height="100">

</div>
</code>```

答:
Do:</p>

```<code><script>
    var screen_width = screen.width;
    if(screen_width<1024){
        document.querySelector(".desktop").remove();
    }
</script>
</code>```

Body:
How to render DIV tag only on desktop devices (width > 1024px)

I don't want to use CSS display:none
because elements still loading while using CSS

Could be done with a javascript to render DIV tag over desktop devices

 Test

 Hello World this content load only for desktop devices

Body:
Do:

<script>
    var screen_width = screen.width;
    if(screen_width<1024){
        document.querySelector(".desktop").remove();
    }
</script>


问:
react native : image is uploading using expo-image-picker but not uploading using react-native-image-picker
I have tried uploading images to node js server, It is working fine with expo-image-picker but it is not working in react-native-image-picker

by doing this I noticed that the URI between expo and react-native CLI is different

by using expo-image-picker the URI is

```<code>  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540satya89310%252Fembteen/ImagePicker/a05bf1a7-cef8-4cef-b73d-8fc330007927.jpg",
</code>```

this is working fine and the image is uploading on node js server

but by react-native-image-picker the URI is

```<code>"uri": "content://com.embteen.provider/root/storage/emulated/0/Pictures/images/image-12b4f263-5747-4404-a41e-1acf8926ea24.jpg"
</code>```

Which is not uploading the image.

What did I miss ?

答:
When you are using react-native-image-picker on android, you should use response.path instead response.uri to get the actual file path. check out docs

Don't forget to add file:/// to the beginning of response.path you get from android.

response.uri is not a persistent path and can't rely on it when uploading.

Body:
I have tried uploading images to node js server, It is working fine with expo-image-picker but it is not working in react-native-image-picker

by doing this I noticed that the URI between expo and react-native CLI is different

by using expo-image-picker the URI is

  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540satya89310%252Fembteen/ImagePicker/a05bf1a7-cef8-4cef-b73d-8fc330007927.jpg",

this is working fine and the image is uploading on node js server

but by react-native-image-picker the URI is

"uri": "content://com.embteen.provider/root/storage/emulated/0/Pictures/images/image-12b4f263-5747-4404-a41e-1acf8926ea24.jpg"

Which is not uploading the image.

What did I miss ?


问:
Is it possible to have two DataTables with the same name in XML?
I would like to have two datatables called bndbox to display 2 sets of coordinates as shown in the code above. But I got an error because bndbox already existed. I then created object in hopes to be able to hold bndbox with object1 and object2 but this did not work. Is there any way to get two datatables with the same name in a dataset? Or is this not possible? The ideal output would be this:

```<code><annotation>
    <folder>Kangaroo</folder>
    <filename>00151.jpg</filename>
    <size>
        <width>503</width>
        <height>488</height>
        <depth>3</depth>
    </size>
    <object>
        <bndbox>
            <ID>1</ID>
            <xmin>209</xmin>
            <ymin>186</ymin>
            <xmax>294</xmax>
            <ymax>217</ymax>
        </bndbox>
    </object>
    <object>
        <bndbox>
            <ID>1</ID>
            <xmin>301</xmin>
            <ymin>163</ymin>
            <xmax>348</xmax>
            <ymax>178</ymax>
        </bndbox>
    </object>
</annotation>
</code>```

答:
You need only one bndbox with multiple rows.  Try the Xml Linq code below</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            DataTable dt = new DataTable("BndBox");
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("xmin", typeof(int));
            dt.Columns.Add("ymin", typeof(int));
            dt.Columns.Add("xmax", typeof(int));
            dt.Columns.Add("ymax", typeof(int));

            foreach (XElement bndbox in doc.Descendants("bndbox"))
            {
                dt.Rows.Add(new object[] {
                    (int)bndbox.Element("ID"),
                    (int)bndbox.Element("xmin"),
                    (int)bndbox.Element("ymin"),
                    (int)bndbox.Element("xmax"),
                    (int)bndbox.Element("ymax")
                });
            }
        }
    }
}
</code>```

Body:
I would like to have two datatables called bndbox to display 2 sets of coordinates as shown in the code above. But I got an error because bndbox already existed. I then created object in hopes to be able to hold bndbox with object1 and object2 but this did not work. Is there any way to get two datatables with the same name in a dataset? Or is this not possible? The ideal output would be this:

<annotation>
    <folder>Kangaroo</folder>
    <filename>00151.jpg</filename>
    <size>
        <width>503</width>
        <height>488</height>
        <depth>3</depth>
    </size>
    <object>
        <bndbox>
            <ID>1</ID>
            <xmin>209</xmin>
            <ymin>186</ymin>
            <xmax>294</xmax>
            <ymax>217</ymax>
        </bndbox>
    </object>
    <object>
        <bndbox>
            <ID>1</ID>
            <xmin>301</xmin>
            <ymin>163</ymin>
            <xmax>348</xmax>
            <ymax>178</ymax>
        </bndbox>
    </object>
</annotation>

Body:
You need only one bndbox with multiple rows.  Try the Xml Linq code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            DataTable dt = new DataTable("BndBox");
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("xmin", typeof(int));
            dt.Columns.Add("ymin", typeof(int));
            dt.Columns.Add("xmax", typeof(int));
            dt.Columns.Add("ymax", typeof(int));

            foreach (XElement bndbox in doc.Descendants("bndbox"))
            {
                dt.Rows.Add(new object[] {
                    (int)bndbox.Element("ID"),
                    (int)bndbox.Element("xmin"),
                    (int)bndbox.Element("ymin"),
                    (int)bndbox.Element("xmax"),
                    (int)bndbox.Element("ymax")
                });
            }
        }
    }
}


问:
In chef remove a node from policy group
I have set the node policy groups

```<code> knife node policy set nodename 'xxxx' 'xxxx'
</code>```

If I want to remove the node from policy groups, how can I do that?

答:
I think you can just use empty strings for the policy group and name:

knife node policy set nodename '' ''
```

<p>If that does not work, you can edit the node and set <code>policy_name</code> and <code>policy_group</code> values to empty strings.</p>

<pre class="lang-sh prettyprint-override"><code>knide node edit nodename
</code>```

Title: In chef remove a node from policy group

Body:
I have set the node policy groups

 knife node policy set nodename 'xxxx' 'xxxx'

If I want to remove the node from policy groups, how can I do that?

Body:
I think you can just use empty strings for the policy group and name:

knife node policy set nodename '' ''

If that does not work, you can edit the node and set policy_name and policy_group values to empty strings.

knide node edit nodename


问:
Starting a Python subprocess with a disconnected stdin
I'm executing a program in Python that seems to explicitly check if stdin is being used, and if it does, it results in some undesirable behaviour whereby it outputs some garbage binary that I don't want. I specifically do not want the program to "see" any connected stdin for this reason. However, by default, subprocess.run() connects to the parent's stdin, and so if the parent process (for example pytest) has a stdin file, the test will fail.

For example say my test is this (samtools can be installed using conda install -c bioconda samtools):

import subprocess
def test_execute():
    print(subprocess.run(
        ['samtools', 'sort'],
        stdout=subprocess.PIPE,
        encoding='utf-8'
    ))
```

<p>If I run <code>pytest test.py -s</code>, the code works, because <code>-s</code> disconnects stdin. However, if I <code>pytest test.py</code>, the command outputs some garbage binary which causes the test to fail:</p>

```>       (result, consumed) = self._buffer_decode(data, self.errors, final)
E       UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

/media/michael/Storage2/miniconda/lib/python3.7/codecs.py:322: UnicodeDecodeError
```

Is there some way of forcing stdin to disconnect, so that regardless of my pytest flags, my subprocess will never detect a connected stdin?

Edit: from looking at the source code of my target program (samtools), it seems that it's using isatty() to check if it should produce output. So in this case it looks like I need to fool isatty().

答:
It turns out that this specific problem involves fooling the function isatty(), since this is what my subprocess is using to determine whether it should output binary or not. Thus, to solve this, I just need to connect stdin to a tty:

import subprocess
import pty # <--------------------------- Added

def test_execute():
    master, slave = pty.openpty() # <---- Added
    print(subprocess.run(
        ['samtools', 'sort'],
        stdout=subprocess.PIPE,
        stdin=slave, # <----------------- Added
        encoding='utf-8'
    ))
```

Now pytest test.py always succeeds, hooray!

Body:
I'm executing a program in Python that seems to explicitly check if stdin is being used, and if it does, it results in some undesirable behaviour whereby it outputs some garbage binary that I don't want. I specifically do not want the program to "see" any connected stdin for this reason. However, by default, subprocess.run() connects to the parent's stdin, and so if the parent process (for example pytest) has a stdin file, the test will fail.

For example say my test is this (samtools can be installed using conda install -c bioconda samtools):

import subprocess
def test_execute():
    print(subprocess.run(
        ['samtools', 'sort'],
        stdout=subprocess.PIPE,
        encoding='utf-8'
    ))

If I run pytest test.py -s, the code works, because -s disconnects stdin. However, if I pytest test.py, the command outputs some garbage binary which causes the test to fail:

>       (result, consumed) = self._buffer_decode(data, self.errors, final)
E       UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

/media/michael/Storage2/miniconda/lib/python3.7/codecs.py:322: UnicodeDecodeError

Is there some way of forcing stdin to disconnect, so that regardless of my pytest flags, my subprocess will never detect a connected stdin?

Edit: from looking at the source code of my target program (samtools), it seems that it's using isatty() to check if it should produce output. So in this case it looks like I need to fool isatty().

Body:
It turns out that this specific problem involves fooling the function isatty(), since this is what my subprocess is using to determine whether it should output binary or not. Thus, to solve this, I just need to connect stdin to a tty:

import subprocess
import pty # <--------------------------- Added

def test_execute():
    master, slave = pty.openpty() # <---- Added
    print(subprocess.run(
        ['samtools', 'sort'],
        stdout=subprocess.PIPE,
        stdin=slave, # <----------------- Added
        encoding='utf-8'
    ))

Now pytest test.py always succeeds, hooray!


问:
How to turn multiple vue components into one single npm package?
I was told by the project manager at the company I work for to take all the global components of a vue project we're working on and turning them into a single npm package that anyone working on the project can import and start using. essentially I have to take the global components and turn them into a component library like vuetify which is installed using npm and than imported from node modules directory.

I was wondering if you guys could point me in the right direction on how to achieve this. thanks in advance.

答:
So, regardless of the implementation, the main thing you need is following this guide on how to create an npm package
https://docs.npmjs.com/creating-and-publishing-private-packages

Then

You create an src folder.
In the src, you will create a folder named "components" with all your -duh- components.

In the src folder, you will also create an index.js file, from there you will export your components.

```<code>export { default as VDataTable } from './components/VDataTable.vue'
// ...etc
</code>```

Option1

If you use a bundler for your projects, and you know by a fact that all your codebases will use a bundler, you can simply create a folder with a package.json.

In your package.json then you will

```<code>  "module": "src/index.js",
  "main": "src/index.js"
</code>```

In this scenario, you are letting your main project bundler (which is using the package) transpile all the packages for you, (babel, single file components)

Option 2

In case you have absolutely no clue of the nature of the projects which can use your library you will need a bundler for your components.

An example can be Rollup.

I suggest these 2 guides.

https://rollupjs.org/

https://rollup-plugin-vue.vuejs.org/

Long story short, Rollup will transpile for you the files you requested (js and css), and you will have to make them available from your package.json

```<code>  "module": "src/dist/library.esm.js",
  "main": "src/library.common.js"
</code>```

And then you can release your package. Possibly privately or you might get fired :P

Body:
So, regardless of the implementation, the main thing you need is following this guide on how to create an npm package
https://docs.npmjs.com/creating-and-publishing-private-packages

Then

You create an src folder.
In the src, you will create a folder named "components" with all your -duh- components.

In the src folder, you will also create an index.js file, from there you will export your components.

export { default as VDataTable } from './components/VDataTable.vue'
// ...etc

Option1

If you use a bundler for your projects, and you know by a fact that all your codebases will use a bundler, you can simply create a folder with a package.json.

In your package.json then you will

  "module": "src/index.js",
  "main": "src/index.js"

In this scenario, you are letting your main project bundler (which is using the package) transpile all the packages for you, (babel, single file components)

Option 2

In case you have absolutely no clue of the nature of the projects which can use your library you will need a bundler for your components.

An example can be Rollup.

I suggest these 2 guides.

https://rollupjs.org/

https://rollup-plugin-vue.vuejs.org/

Long story short, Rollup will transpile for you the files you requested (js and css), and you will have to make them available from your package.json

  "module": "src/dist/library.esm.js",
  "main": "src/library.common.js"

And then you can release your package. Possibly privately or you might get fired :P


问:
Access a subclass from an interface
I have an arraylist of an interface named Component. There is another class named Frame that extends component as follows: Component (interface) > AbstractComponent (abstract class) > AbstractContainer (abstract class) > OrganizedContainer (class) > Frame (class)

Everything in the component arraylist goes to a renderer to be rendered. I want to be able to access the methods of the Frame object from the AbstractContainer class. Is this possible without declaring the method in the Component interface?

答:
A Class implements an interface. A Class extends another Class. An Interface extends another interface. This is the convention in java and I mentioned as in your question you have said your class extends the interface Component.

Frame<<concrete class>> extends OrganizedContainer extends AbstractContainer extends AbstractComponent implements Component<<interface>>

Now coming to your question. Is it possible from inside the AbstractContainer Class to access the method which are only defined in Frame ? Yes it is possible.
How ? In the parent just typecast the (Frame)this.methodInFrame() and to avoid some other sub class object being the currently referred by this, you need to use the instanceof operator. so its like

```<code> if(this instanceof Frame){
     (Frame)this.methodInFrame();
 }
</code>```

Is it a good practice ? No not at all, Super class should not be dependent on its sub classes. This increases coupling in your program and leads to maintenance issues. What if you have or plan to have or may have in future any more concrete sub classes ? When you modify the Frame your super classes needs to be modified and due to that your newly added subclasses may need modification. Also this leads to issues which may be runtime issues. when ever you use instanceof note that it is a code smell, you must have very good reason to use it.

Title: Access a subclass from an interface

Body:
A Class implements an interface. A Class extends another Class. An Interface extends another interface. This is the convention in java and I mentioned as in your question you have said your class extends the interface Component.

Frame<<concrete class>> extends OrganizedContainer extends AbstractContainer extends AbstractComponent implements Component<<interface>>

Now coming to your question. Is it possible from inside the AbstractContainer Class to access the method which are only defined in Frame ? Yes it is possible.
How ? In the parent just typecast the (Frame)this.methodInFrame() and to avoid some other sub class object being the currently referred by this, you need to use the instanceof operator. so its like

 if(this instanceof Frame){
     (Frame)this.methodInFrame();
 }

Is it a good practice ? No not at all, Super class should not be dependent on its sub classes. This increases coupling in your program and leads to maintenance issues. What if you have or plan to have or may have in future any more concrete sub classes ? When you modify the Frame your super classes needs to be modified and due to that your newly added subclasses may need modification. Also this leads to issues which may be runtime issues. when ever you use instanceof note that it is a code smell, you must have very good reason to use it.


问:
Unable to convert mp3 into PCM using AudioConverterFillComplexBuffer in AudioFileStreamOpen's AudioFileStream_PacketsProc callback
I have a AudioFileStream_PacketsProc callback set during an AudioFileStreamOpen which handles converting audio packets into PCM using AudioConverterFillComplexBuffer. The issue that I am having is that I am getting a -50 OSStatus (paramErr) after AudioConverterFillComplexBuffer is called. Below is a snippet of what parameters were used in AudioConverterFillComplexBuffer and how they were made:

```<code>        audioConverterRef = AudioConverterRef()

        // AudioConvertInfo is a struct that contains information
        // for the converter regarding the number of packets and
        // which audiobuffer is being allocated
        convertInfo? = AudioConvertInfo(done: false, numberOfPackets: numberPackets, audioBuffer: buffer,
            packetDescriptions: packetDescriptions)

        var framesToDecode: UInt32 = pcmBufferTotalFrameCount! - end

        var localPcmAudioBuffer = AudioBuffer()
        localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))

        var localPcmBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
        localPcmAudioBuffer = localPcmBufferList.mBuffers
        localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))
        localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!;
        localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

        var localPcmBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
        localPcmAudioBuffer = localPcmBufferList.mBuffers

        AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfo, &framesToDecode, &localPcmBufferList, nil)
</code>```

Does what could possibly be causing the param error?

Here is the full method for the callback if needed:

```<code>func handleAudioPackets(inputData: UnsafePointer<Void>, numberBytes: UInt32, numberPackets: UInt32, packetDescriptions: UnsafeMutablePointer<AudioStreamPacketDescription>) {
        if currentlyReadingEntry == nil {
            print("currentlyReadingEntry = nil")
            return
        }
        if currentlyReadingEntry.parsedHeader == false {
            print("currentlyReadingEntry.parsedHeader == false")
            return
        }

        if disposedWasRequested == true {
            print("disposedWasRequested == true")
            return
        }

        guard let audioConverterRef = audioConverterRef else {
            return
        }

        if seekToTimeWasRequested == true && currentlyReadingEntry.calculatedBitRate() > 0.0 {
            wakeupPlaybackThread()
            print("seekToTimeWasRequested == true && currentlyReadingEntry.calculatedBitRate() > 0.0")
            return
        }

        discontinuous = false

        var buffer = AudioBuffer()
        buffer.mNumberChannels = audioConverterAudioStreamBasicDescription.mChannelsPerFrame
        buffer.mDataByteSize = numberBytes
        buffer.mData = UnsafeMutablePointer<Void>(inputData)

        convertInfo? = AudioConvertInfo(done: false, numberOfPackets: numberPackets, audioBuffer: buffer,
            packetDescriptions: packetDescriptions)

        if packetDescriptions != nil && currentlyReadingEntry.processedPacketsCount < maxCompressedBacketsForBitrateCalculation {
            let count: Int = min(Int(numberPackets), Int(maxCompressedBacketsForBitrateCalculation - currentlyReadingEntry.processedPacketsCount!))
            for var i = 0;i < count;++i{
                let packetSize: Int32 = Int32(packetDescriptions[i].mDataByteSize)
                OSAtomicAdd32(packetSize, &currentlyReadingEntry.processedPacketsSizeTotal!)
                OSAtomicIncrement32(&currentlyReadingEntry.processedPacketsCount!)
            }
        }
        while true {
            OSSpinLockLock(&pcmBufferSpinLock)
            var used: UInt32 = pcmBufferUsedFrameCount!
            var start: UInt32 = pcmBufferFrameStartIndex!
            var end = (pcmBufferFrameStartIndex! + pcmBufferUsedFrameCount!) % pcmBufferTotalFrameCount!
            var framesLeftInsideBuffer = pcmBufferTotalFrameCount! - used
            OSSpinLockUnlock(&pcmBufferSpinLock)

            if framesLeftInsideBuffer == 0 {
                pthread_mutex_lock(&playerMutex)
                while true {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    used = pcmBufferUsedFrameCount!
                    start = pcmBufferFrameStartIndex!
                    end = (pcmBufferFrameStartIndex! + pcmBufferUsedFrameCount!) % pcmBufferTotalFrameCount!
                    framesLeftInsideBuffer = pcmBufferTotalFrameCount! - used
                    OSSpinLockUnlock(&pcmBufferSpinLock)

                    if framesLeftInsideBuffer > 0 {
                        break
                    }

                    if (disposedWasRequested == true
                        || internalState == SSPlayerInternalState.Disposed) {
                        pthread_mutex_unlock(&playerMutex)
                        return
                    }

                    if (seekToTimeWasRequested == true && currentlyPlayingEntry.calculatedBitRate() > 0.0)
                    {
                        pthread_mutex_unlock(&playerMutex)
                        wakeupPlaybackThread()
                        return;
                    }

                    waiting = true
                    pthread_cond_wait(&playerThreadReadyCondition, &playerMutex)
                    waiting = false
                }
                pthread_mutex_unlock(&playerMutex)
            }
            var localPcmAudioBuffer = AudioBuffer()
            var localPcmBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
            localPcmAudioBuffer = localPcmBufferList.mBuffers

            if end >= start {
                var framesAdded: UInt32 = 0
                var framesToDecode: UInt32 = pcmBufferTotalFrameCount! - end
                localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))
                localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!;
                localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

                AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfo, &framesToDecode, &localPcmBufferList, nil)

                framesAdded = framesToDecode

                if status == 100 {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    return
                } else if status != 0 {
                    print("error")
                    return
                }
                framesToDecode = start

                if framesToDecode == 0 {

                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    continue
                }

                localPcmAudioBuffer.mData = pcmAudioBuffer!.mData
                localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!
                localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

                AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfo, &framesToDecode, &localPcmBufferList, nil)
                let decodedFramesAdded = framesAdded + framesToDecode
                framesAdded = decodedFramesAdded

                if status == 100 {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    return
                } else if status == 0 {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    continue
                } else if status != 0 {
                    print("error")
                    return
                } else {
                    var framesAdded: UInt32 = 0
                    var framesToDecode: UInt32 = start - end
                    localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))
                    localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!;
                    localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

                    var  convertInfoo: UnsafePointer<Void> = unsafeBitCast(convertInfo, UnsafePointer<Void>.self)

                    status = AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfoo, &framesToDecode, &localPcmBufferList, nil)

                    framesAdded = framesToDecode

                    if status == 100 {
                        OSSpinLockLock(&pcmBufferSpinLock)
                        let newCount = pcmBufferUsedFrameCount! + framesAdded
                        pcmBufferUsedFrameCount = newCount
                        OSSpinLockUnlock(&pcmBufferSpinLock);

                        OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                        let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                        currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                        OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                        return
                    } else if status == 0 {
                        OSSpinLockLock(&pcmBufferSpinLock)
                        let newCount = pcmBufferUsedFrameCount! + framesAdded
                        pcmBufferUsedFrameCount = newCount
                        OSSpinLockUnlock(&pcmBufferSpinLock);

                        OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                        let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                        currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                        OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                        continue
                    } else if status != 0 {
                        print("error")
                        return
                    }

                }
            }
        }
    }
</code>```

答:
Easy to do with tanersener/mobile-ffmpeg</p>

```<code>      let command = "-i input.mp3 -f s16le -acodec pcm_s16le -ac 1 -ar 44100  output.raw"
      let result = MobileFFmpeg.execute(command)
           switch result {
           case RETURN_CODE_SUCCESS:
               print("command exe completed successfully.\n")
           case RETURN_CODE_CANCEL:
               print("command exe cancelled by user.\n")
           default:
               print("command exe failed with rc=\(result) and output=\(String(describing: MobileFFmpegConfig.getLastCommandOutput())).\n")
          }
</code>```

Body:
I have a AudioFileStream_PacketsProc callback set during an AudioFileStreamOpen which handles converting audio packets into PCM using AudioConverterFillComplexBuffer. The issue that I am having is that I am getting a -50 OSStatus (paramErr) after AudioConverterFillComplexBuffer is called. Below is a snippet of what parameters were used in AudioConverterFillComplexBuffer and how they were made:

        audioConverterRef = AudioConverterRef()

        // AudioConvertInfo is a struct that contains information
        // for the converter regarding the number of packets and
        // which audiobuffer is being allocated
        convertInfo? = AudioConvertInfo(done: false, numberOfPackets: numberPackets, audioBuffer: buffer,
            packetDescriptions: packetDescriptions)

        var framesToDecode: UInt32 = pcmBufferTotalFrameCount! - end

        var localPcmAudioBuffer = AudioBuffer()
        localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))

        var localPcmBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
        localPcmAudioBuffer = localPcmBufferList.mBuffers
        localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))
        localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!;
        localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

        var localPcmBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
        localPcmAudioBuffer = localPcmBufferList.mBuffers

        AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfo, &framesToDecode, &localPcmBufferList, nil)

Does what could possibly be causing the param error?

Here is the full method for the callback if needed:

func handleAudioPackets(inputData: UnsafePointer<Void>, numberBytes: UInt32, numberPackets: UInt32, packetDescriptions: UnsafeMutablePointer<AudioStreamPacketDescription>) {
        if currentlyReadingEntry == nil {
            print("currentlyReadingEntry = nil")
            return
        }
        if currentlyReadingEntry.parsedHeader == false {
            print("currentlyReadingEntry.parsedHeader == false")
            return
        }

        if disposedWasRequested == true {
            print("disposedWasRequested == true")
            return
        }

        guard let audioConverterRef = audioConverterRef else {
            return
        }

        if seekToTimeWasRequested == true && currentlyReadingEntry.calculatedBitRate() > 0.0 {
            wakeupPlaybackThread()
            print("seekToTimeWasRequested == true && currentlyReadingEntry.calculatedBitRate() > 0.0")
            return
        }

        discontinuous = false

        var buffer = AudioBuffer()
        buffer.mNumberChannels = audioConverterAudioStreamBasicDescription.mChannelsPerFrame
        buffer.mDataByteSize = numberBytes
        buffer.mData = UnsafeMutablePointer<Void>(inputData)

        convertInfo? = AudioConvertInfo(done: false, numberOfPackets: numberPackets, audioBuffer: buffer,
            packetDescriptions: packetDescriptions)

        if packetDescriptions != nil && currentlyReadingEntry.processedPacketsCount < maxCompressedBacketsForBitrateCalculation {
            let count: Int = min(Int(numberPackets), Int(maxCompressedBacketsForBitrateCalculation - currentlyReadingEntry.processedPacketsCount!))
            for var i = 0;i < count;++i{
                let packetSize: Int32 = Int32(packetDescriptions[i].mDataByteSize)
                OSAtomicAdd32(packetSize, &currentlyReadingEntry.processedPacketsSizeTotal!)
                OSAtomicIncrement32(&currentlyReadingEntry.processedPacketsCount!)
            }
        }
        while true {
            OSSpinLockLock(&pcmBufferSpinLock)
            var used: UInt32 = pcmBufferUsedFrameCount!
            var start: UInt32 = pcmBufferFrameStartIndex!
            var end = (pcmBufferFrameStartIndex! + pcmBufferUsedFrameCount!) % pcmBufferTotalFrameCount!
            var framesLeftInsideBuffer = pcmBufferTotalFrameCount! - used
            OSSpinLockUnlock(&pcmBufferSpinLock)

            if framesLeftInsideBuffer == 0 {
                pthread_mutex_lock(&playerMutex)
                while true {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    used = pcmBufferUsedFrameCount!
                    start = pcmBufferFrameStartIndex!
                    end = (pcmBufferFrameStartIndex! + pcmBufferUsedFrameCount!) % pcmBufferTotalFrameCount!
                    framesLeftInsideBuffer = pcmBufferTotalFrameCount! - used
                    OSSpinLockUnlock(&pcmBufferSpinLock)

                    if framesLeftInsideBuffer > 0 {
                        break
                    }

                    if (disposedWasRequested == true
                        || internalState == SSPlayerInternalState.Disposed) {
                        pthread_mutex_unlock(&playerMutex)
                        return
                    }

                    if (seekToTimeWasRequested == true && currentlyPlayingEntry.calculatedBitRate() > 0.0)
                    {
                        pthread_mutex_unlock(&playerMutex)
                        wakeupPlaybackThread()
                        return;
                    }

                    waiting = true
                    pthread_cond_wait(&playerThreadReadyCondition, &playerMutex)
                    waiting = false
                }
                pthread_mutex_unlock(&playerMutex)
            }
            var localPcmAudioBuffer = AudioBuffer()
            var localPcmBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
            localPcmAudioBuffer = localPcmBufferList.mBuffers

            if end >= start {
                var framesAdded: UInt32 = 0
                var framesToDecode: UInt32 = pcmBufferTotalFrameCount! - end
                localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))
                localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!;
                localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

                AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfo, &framesToDecode, &localPcmBufferList, nil)

                framesAdded = framesToDecode

                if status == 100 {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    return
                } else if status != 0 {
                    print("error")
                    return
                }
                framesToDecode = start

                if framesToDecode == 0 {

                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    continue
                }

                localPcmAudioBuffer.mData = pcmAudioBuffer!.mData
                localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!
                localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

                AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfo, &framesToDecode, &localPcmBufferList, nil)
                let decodedFramesAdded = framesAdded + framesToDecode
                framesAdded = decodedFramesAdded

                if status == 100 {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    return
                } else if status == 0 {
                    OSSpinLockLock(&pcmBufferSpinLock)
                    let newCount = pcmBufferUsedFrameCount! + framesAdded
                    pcmBufferUsedFrameCount = newCount
                    OSSpinLockUnlock(&pcmBufferSpinLock);

                    OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                    let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                    currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                    OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                    continue
                } else if status != 0 {
                    print("error")
                    return
                } else {
                    var framesAdded: UInt32 = 0
                    var framesToDecode: UInt32 = start - end
                    localPcmAudioBuffer.mData = pcmAudioBuffer!.mData.advancedBy(Int(end * pcmBufferFrameSizeInBytes!))
                    localPcmAudioBuffer.mDataByteSize = framesToDecode * pcmBufferFrameSizeInBytes!;
                    localPcmAudioBuffer.mNumberChannels = pcmAudioBuffer!.mNumberChannels

                    var  convertInfoo: UnsafePointer<Void> = unsafeBitCast(convertInfo, UnsafePointer<Void>.self)

                    status = AudioConverterFillComplexBuffer(audioConverterRef, AudioConverter_Callback, &convertInfoo, &framesToDecode, &localPcmBufferList, nil)

                    framesAdded = framesToDecode

                    if status == 100 {
                        OSSpinLockLock(&pcmBufferSpinLock)
                        let newCount = pcmBufferUsedFrameCount! + framesAdded
                        pcmBufferUsedFrameCount = newCount
                        OSSpinLockUnlock(&pcmBufferSpinLock);

                        OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                        let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                        currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                        OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                        return
                    } else if status == 0 {
                        OSSpinLockLock(&pcmBufferSpinLock)
                        let newCount = pcmBufferUsedFrameCount! + framesAdded
                        pcmBufferUsedFrameCount = newCount
                        OSSpinLockUnlock(&pcmBufferSpinLock);

                        OSSpinLockLock(&currentlyReadingEntry!.spinLock!)
                        let newFramesAddedCount = currentlyReadingEntry.framesQueued! + Int64(framesAdded)
                        currentlyReadingEntry!.framesQueued! = newFramesAddedCount
                        OSSpinLockUnlock(&currentlyReadingEntry!.spinLock!)
                        continue
                    } else if status != 0 {
                        print("error")
                        return
                    }

                }
            }
        }
    }

Body:
Easy to do with tanersener/mobile-ffmpeg

      let command = "-i input.mp3 -f s16le -acodec pcm_s16le -ac 1 -ar 44100  output.raw"
      let result = MobileFFmpeg.execute(command)
           switch result {
           case RETURN_CODE_SUCCESS:
               print("command exe completed successfully.\n")
           case RETURN_CODE_CANCEL:
               print("command exe cancelled by user.\n")
           default:
               print("command exe failed with rc=\(result) and output=\(String(describing: MobileFFmpegConfig.getLastCommandOutput())).\n")
          }


问:
How to automate this process?
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}
</code>```

In the Terminal, after getting the html file converted, I write:

```<code>script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt
</code>```

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

答:
I take it from your question that what you want to do is to apply this script to all the (html-) files in a certain folder, and output text versions of them.

So a simple solution is to simply replace the hardcoded file names with variables, and loop the script around the @ARGV, e.g. the arguments to the script, like so:

```<code>for my $file (@ARGV) {
    next unless ($file =~ /^(.+).html*$/i);
    my $outfile = $1 . ".txt";
    my $tree = HTML::TreeBuilder->new;
    $tree->parse_file($file); # credit to Phil for this one
    my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
    foreach my $files ($formatter->format($tree)) {
        $files =~ s/^\s+//mg;
        open my $fh, '>', $outfile or die $!;
        print $fh $files;
    }
}
</code>```

As you see, I cleaned up some of it. Use like so:

```<code>> script.pl *.htm
</code>```

Title: How to automate this process?

Body:
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}

In the Terminal, after getting the html file converted, I write:

script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

Body:
I take it from your question that what you want to do is to apply this script to all the (html-) files in a certain folder, and output text versions of them.

So a simple solution is to simply replace the hardcoded file names with variables, and loop the script around the @ARGV, e.g. the arguments to the script, like so:

for my $file (@ARGV) {
    next unless ($file =~ /^(.+).html*$/i);
    my $outfile = $1 . ".txt";
    my $tree = HTML::TreeBuilder->new;
    $tree->parse_file($file); # credit to Phil for this one
    my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
    foreach my $files ($formatter->format($tree)) {
        $files =~ s/^\s+//mg;
        open my $fh, '>', $outfile or die $!;
        print $fh $files;
    }
}

As you see, I cleaned up some of it. Use like so:

> script.pl *.htm


问:
For homebrew mysql installs, where's my.cnf?
For homebrew mysql installs, where's my.cnf? Does it install one?</p>

答:
Server version: 8.0.19 Homebrew. macOS Catalina 10.15.5 and installed MySQL via Homebrew. Found this file here:

```<code>/usr/local/etc/my.cnf
</code>```

This solution helped :)

Body:
Server version: 8.0.19 Homebrew. macOS Catalina 10.15.5 and installed MySQL via Homebrew. Found this file here:

/usr/local/etc/my.cnf

This solution helped :)


问:
How to hide view's shadow after its presenting?
I want to call a UIView with transparent background from table cell.

```<code>let myView = MyViewController()
myView.view.backgroundColor = .clear
tableController.present(myView, animated: true, completion: nil)
</code>```

But there remains such an unpleasant border.

myView.modalPresentationStyle = .fullScreen makes it worse - remove background view.

答:
You can present new viewController in a .fullscreen (or any other) mode with transparent background

Add view with content inside viewController

Add custom background color to the main viewController's view. Set opacity to any value less than 100% (e.g. 30% - see screen below)

Change viewController's presentation style to .overCurrentContext

Here is how you can do that programmatically

```<code>//apply that for viewController that will be displayed at the top
viewController.modalPresentationStyle = .fullScreen
viewController.modalPresentationStyle = .overCurrentContext
</code>```

Body:
I want to call a UIView with transparent background from table cell.

let myView = MyViewController()
myView.view.backgroundColor = .clear
tableController.present(myView, animated: true, completion: nil)

But there remains such an unpleasant border.

myView.modalPresentationStyle = .fullScreen makes it worse - remove background view.

Body:
You can present new viewController in a .fullscreen (or any other) mode with transparent background

Add view with content inside viewController

Add custom background color to the main viewController's view. Set opacity to any value less than 100% (e.g. 30% - see screen below)

Change viewController's presentation style to .overCurrentContext

Here is how you can do that programmatically

//apply that for viewController that will be displayed at the top
viewController.modalPresentationStyle = .fullScreen
viewController.modalPresentationStyle = .overCurrentContext