问:
How to use the "Find in Path" options in Intellij?
There are four "location" options to Find in Path:  Project, Module, Directory, and Scope.  I would have thought that the most restrictive would be Directory but instead it is the only one I am seeing any results:

Directory

The expected results can be seen by doing a search from the command line in the root of the project:

```<code>$find . -name \*.js | xargs grep "n createSTFT(" 2>/dev/null
./js/cough-app-local-audio-file.js:function createSTFT(buffer) {
./js/testOnsets.js:function createSTFT(buffer) {
./js/cough-local-file.headless.js:export function createSTFT(buffer) {
</code>```

I would expect the remaining types of searches to find all of those results - but instead they find .. nothing ??

Project

Module

All Places

So the only one that makes any sense is Directory .. but even that one is missing results.. What are these options supposed to do and why are they not showing the expected results?  I am on Intellij 2019.3.5 Ultimate

答:
Make sure the module was imported with the right type and has the content and/or source roots configured properly. Find in Path will work within the module roots only when you have specified the option to search in a project or in a module.

You can remove the module and add a new one or adjust the roots configuration.

Body:
There are four "location" options to Find in Path:  Project, Module, Directory, and Scope.  I would have thought that the most restrictive would be Directory but instead it is the only one I am seeing any results:

Directory

The expected results can be seen by doing a search from the command line in the root of the project:

$find . -name \*.js | xargs grep "n createSTFT(" 2>/dev/null
./js/cough-app-local-audio-file.js:function createSTFT(buffer) {
./js/testOnsets.js:function createSTFT(buffer) {
./js/cough-local-file.headless.js:export function createSTFT(buffer) {

I would expect the remaining types of searches to find all of those results - but instead they find .. nothing ??

Project

Module

All Places

So the only one that makes any sense is Directory .. but even that one is missing results.. What are these options supposed to do and why are they not showing the expected results?  I am on Intellij 2019.3.5 Ultimate


来源: stackexchange

问:
c# constructor injection and constructor overloads
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

```<code>public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}
</code>```

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

```<code>public SomeConstructor(string name) : this(name, null)
{
}
</code>```

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.

答:
You may prevent that situation with a run-time exception like InvalidOperationException.

If some instantiated the class with the two-parameters-constructor and tries to call Save, just check if "someObject" is null, and if it's so:

throw new InvalidOperationException("This method cannot be invoked in current object state");

In the other hand, if this second constructor would be used by your library and third-party library developers wouldn't be allowed to use it, this constructor should have the internal modifier.

ContentLicense: CC BY-SA 3.0

Body:
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

public SomeConstructor(string name) : this(name, null)
{
}

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.


问:
Formik onSubmit function is not working on my code
I am creating a form by using react and formik.Below is my code:

```<code><div>
  <Formik
    initialValues={{
      email: ""
    }}
    onSubmit={(values: FState, setSubmitting: any) => {
      console.log("Enter in submit function", values);
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 500);
    }}
    validationSchema={validationSchemaGlobal}
  >
    {({
      errors,
      touched,
      handleBlur,
      handleChange,
      isSubmitting,
      values,
      handleSubmit
    }: any) => (
      <div>
        <Cards>
          <form onSubmit={handleSubmit}>
            <CardBody>
              <h4>
                Enter Your Email Address and we'll send you a link to reset your
                password
              </h4>
              <Field
                type="text"
                id="email"
                value={values.email}
                component={CustomInput}
                onChange={handleChange}
                onBlur={handleBlur}
              />
              {errors.email && touched.email ? (
                <div style={{ color: "red" }}>{errors.email}</div>
              ) : null}
            </CardBody>
            <CardFooter>
              <br />
              <button type="submit" disabled={isSubmitting}>
                Send Password Reset Link
                {/* {isSubmitting && <i className="fa fa-sponner fa-spin"/>} */}
              </button>
            </CardFooter>
          </form>
        </Cards>
      </div>
    )}
  </Formik>
</div>
</code>```

In this formik form, onSubmit function not working. I dont know why? Please tell me guys what is problem with my code?

答:
In my case I use Yup as validator and I accidentally had firstName and lastName in my validationSchema as required but I did not have those values in my form.

My validationSchema was,

```<code>const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  lastName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
})
</code>```

I just deleted firstName and lastName,

```<code>const SignupSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
})
</code>```

So check your validationSchema and see if you require something that does not exist in your form.

ContentLicense: CC BY-SA 4.0

Body:
I am creating a form by using react and formik.Below is my code:

  <Formik
    initialValues={{
      email: ""
    }}
    onSubmit={(values: FState, setSubmitting: any) => {
      console.log("Enter in submit function", values);
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 500);
    }}
    validationSchema={validationSchemaGlobal}
  >
    {({
      errors,
      touched,
      handleBlur,
      handleChange,
      isSubmitting,
      values,
      handleSubmit
    }: any) => (

        <Cards>
          <form onSubmit={handleSubmit}>
            <CardBody>

                Enter Your Email Address and we'll send you a link to reset your
                password

              <Field
                type="text"
                id="email"
                value={values.email}
                component={CustomInput}
                onChange={handleChange}
                onBlur={handleBlur}
              />
              {errors.email && touched.email ? (

{errors.email}

              ) : null}
            </CardBody>
            <CardFooter>

              <button type="submit" disabled={isSubmitting}>
                Send Password Reset Link
                {/* {isSubmitting && } */}
              </button>
            </CardFooter>
          </form>
        </Cards>

    )}
  </Formik>

In this formik form, onSubmit function not working. I dont know why? Please tell me guys what is problem with my code?

Body:
In my case I use Yup as validator and I accidentally had firstName and lastName in my validationSchema as required but I did not have those values in my form.

My validationSchema was,

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  lastName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
})

I just deleted firstName and lastName,

const SignupSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
})

So check your validationSchema and see if you require something that does not exist in your form.


问:
How to make buttons click(work) multiple times?
I'm creating a c# windows form application, and I created a navigation bar with buttons. There are 5 main buttons that appear all the time on the form but I also made sub buttons that appear when you click on the main buttons. When I click once they appear and if I click again on the same button they disappear and it works only once. If I click on the button for the third time or multiple times afterward they don't appear anymore. Can someone please tell me how to make it work properly? This is the code I used in the event handlers:</p>

```<code>public void Izlez_Click(object sender, EventArgs e)
    {
            if (!buttonPressed4)
            {
                buttonPressed4 = true;
                logout.Show();
                exit.Show();
            }
            else
            {
                logout.Hide();
                exit.Hide();
            }
        }
</code>```

答:
As Steve said, you also need to change buttonPressed4 to false in else statement.

```<code>public Form1()
{
    InitializeComponent();
    button2.Visible = false;
}

bool buttonPressed4 = false;
private void button1_Click(object sender, EventArgs e)
{
    if (!buttonPressed4)
    {
        buttonPressed4 = true;
        logout.Show();
    }
    else
    {
        // change buttonPressed4 to false
        buttonPressed4 = false;
        logout.Hide();
    }
}
</code>```

Body:
I'm creating a c# windows form application, and I created a navigation bar with buttons. There are 5 main buttons that appear all the time on the form but I also made sub buttons that appear when you click on the main buttons. When I click once they appear and if I click again on the same button they disappear and it works only once. If I click on the button for the third time or multiple times afterward they don't appear anymore. Can someone please tell me how to make it work properly? This is the code I used in the event handlers:

public void Izlez_Click(object sender, EventArgs e)
    {
            if (!buttonPressed4)
            {
                buttonPressed4 = true;
                logout.Show();
                exit.Show();
            }
            else
            {
                logout.Hide();
                exit.Hide();
            }
        }

Body:
As Steve said, you also need to change buttonPressed4 to false in else statement.

public Form1()
{
    InitializeComponent();
    button2.Visible = false;
}

bool buttonPressed4 = false;
private void button1_Click(object sender, EventArgs e)
{
    if (!buttonPressed4)
    {
        buttonPressed4 = true;
        logout.Show();
    }
    else
    {
        // change buttonPressed4 to false
        buttonPressed4 = false;
        logout.Hide();
    }
}


问:
is .then supported by Internet Explorer?
I have read that IE does not support promises, however I have legacy code with .then which seems to run fine on IE.

How can this be as my understanding is .then = promises?

Thanks

答:
The Promise.prototype.then() method returns a Promise. This method still doesn't support IE browser. You could check the Browser compatibility.

To use the Promise and Then method in IE 11 browser, you can use 3rd party promise library (like Bluebird) or Babel transpiler to convert the ES6 code to ES5 code. Please refer the following sample code:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>
    (function (global, factory) {
        if (typeof define === "function" && define.amd) {
            define([], factory);
        } else if (typeof exports !== "undefined") {
            factory();
        } else {
            var mod = {
                exports: {}
            };
            factory();
            global.repl = mod.exports;
        }
    })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function () {
        "use strict";

        var myFirstPromise = new Promise(function (resolve, reject) {
            // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
            // In this example, we use setTimeout(...) to simulate async code.
            // In reality, you will probably be using something like XHR or an HTML5 API.
            setTimeout(function () {
                resolve("Success!"); // Yay! Everything went well!
            }, 250);
        });
        myFirstPromise.then(function (successMessage) {
            // successMessage is whatever we passed in the resolve(...) function above.
            // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
            console.log("Yay! " + successMessage);
        });
    });
</script>
</code>```

The output in IE browser:

Edit:

The deferred.then() method support IE browser. Perhaps you are using the deferred.then method.

Body:
The Promise.prototype.then() method returns a Promise. This method still doesn't support IE browser. You could check the Browser compatibility.

To use the Promise and Then method in IE 11 browser, you can use 3rd party promise library (like Bluebird) or Babel transpiler to convert the ES6 code to ES5 code. Please refer the following sample code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>
    (function (global, factory) {
        if (typeof define === "function" && define.amd) {
            define([], factory);
        } else if (typeof exports !== "undefined") {
            factory();
        } else {
            var mod = {
                exports: {}
            };
            factory();
            global.repl = mod.exports;
        }
    })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function () {
        "use strict";

        var myFirstPromise = new Promise(function (resolve, reject) {
            // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
            // In this example, we use setTimeout(...) to simulate async code.
            // In reality, you will probably be using something like XHR or an HTML5 API.
            setTimeout(function () {
                resolve("Success!"); // Yay! Everything went well!
            }, 250);
        });
        myFirstPromise.then(function (successMessage) {
            // successMessage is whatever we passed in the resolve(...) function above.
            // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
            console.log("Yay! " + successMessage);
        });
    });
</script>

The output in IE browser:

Edit:

The deferred.then() method support IE browser. Perhaps you are using the deferred.then method.


问:
Inferring function signature from tuple in Typescript
I tried for long hours now and honestly it wasn't worth the effort, bu I'd still like to see if there's a solution to this:

I'm trying to force TS to infer my function signature from tuples. I tried to play with conditional types, but I don't seem to get it right:

// model
interface User {
    name: string
}

interface Article {
    title: string
}

/// api
type Resource = 'user' | 'articles'
type Params = Record<string, number | string | boolean>

type GetSignature =
    | ['user', undefined, User]
    | ['articles', { articleId: number }, Article[]]
    | ['articles', undefined, Article]

// get request
interface ObjArg {
    resource: Resource
    params?: Params
}

type RetType<TResult> = TResult & { cancel: () => void }

async function get<TResult>(args: ObjArg): Promise<RetType<TResult>>
async function get<TResult>(resource: Resource, params?: Params): Promise<RetType<TResult>>
async function get<TResult>(args: [ObjArg | Resource, Params?]): Promise<RetType<TResult>>{
    const { resource, params } = typeof args[0] === 'object' ? args[0] : { resource: args[0], params: args[1] }
    const result = await someAsyncFetch(resource, params)
    return { ...result, cancel: () => { cancelAsyncFetch() }}
}
```

<p>I'd like TS to be able to infer the <code>get</code>'s signature from provided arguments, so it automatically knows that e.g. when calling <code>get('articles', { articleId: 1 }) the return type should be</code>Article<code>as well as that I need the second argument to be of type</code>{articleId: number}<code>(or</code>undefined<code>for array of articles). This is what</code>GetSignature` union type should define.</p>

<p>So the desired usage would be something like</p>

<pre class="lang-js prettyprint-override"><code>const user = get('user') // returns User
const article = get('articles', { articleId: 1 }) // returns Article
const articles = get('articles') // returns Article[]
</code>```

I tried dozens of approaches and none seemed to provide the interface I aim for. Just to mention one of them, I tried to expect signature as a type argument (get<TSignature exntends GetSignature>(...))  and tried to infer the desired signature like in likes of this:

resource: TSignature[0] extends infer T ? T : never
```

<p>or even</p>

<pre class="lang-js prettyprint-override"><code>resource: TSignature[0] extends infer T ? Extract<GetSignature, T> : never
</code>```

But nothing seemed to work. For now I think I'll stick to providing the type argument for TResult, but I'd like to know whether there a way to do what I describe in TS?

答:
It looks like you want GetSignature to be this:

```<code>type GetSignature =
    | ['user', undefined, User]
    | ['articles', { articleId: number }, Article]
    | ['articles', undefined, Article[]]
</code>```

(note how I swapped Article with Article[] to match with what you are expecting at the end).

Given that, I'd probably separate out the one-arg and two-arg signatures using the Extract and Exclude utility types:

```<code>type OneArgSignatures = Extract<GetSignature, [any, undefined, any]>;
type TwoArgSignatures = Exclude<GetSignature, [any, undefined, any]>;
</code>```

And then define the call signature for get() to be a pair of overloads, one for one-arg and one for two-arg calls:

```<code>declare function get<R extends OneArgSignatures[0]>(
    resource: R
): Extract<OneArgSignatures, [R, any, any]>[2];

declare function get<R extends TwoArgSignatures[0]>(
    resource: R,
    params: Extract<TwoArgSignatures, [R, any, any]>[1]
): Extract<TwoArgSignatures, [R, any, any]>[2];
</code>```

You can see that the functions are generic in R, the resource string literal type.  Note that the compiler generally has the easiest time inferring a type parameter from a value of that type.  Inferring TSignature from resource: TSignature[0] extends infer R ? R : never is problematic, but inferring R from resource: R is straightforward.   Once R is inferred, the compiler can use Extract to calculate the type of params (if present) and the return type.

Let's see if it works:

```<code>const u = get("user"); // User
const aa = get("articles"); // Article[]
const a = get("articles", { articleId: 123 }); // Article
</code>```

Looks good.  Note that I didn't worry about Promises, RetType, or your other overload.  I assume you can take care of that.  Okay, hope that helps; good luck!

Playground link to code

Body:
I tried for long hours now and honestly it wasn't worth the effort, bu I'd still like to see if there's a solution to this:

I'm trying to force TS to infer my function signature from tuples. I tried to play with conditional types, but I don't seem to get it right:

// model
interface User {
    name: string
}

interface Article {
    title: string
}

/// api
type Resource = 'user' | 'articles'
type Params = Record<string, number | string | boolean>

type GetSignature =
    | ['user', undefined, User]
    | ['articles', { articleId: number }, Article[]]
    | ['articles', undefined, Article]

// get request
interface ObjArg {
    resource: Resource
    params?: Params
}

type RetType<TResult> = TResult & { cancel: () => void }

async function get<TResult>(args: ObjArg): Promise<RetType<TResult>>
async function get<TResult>(resource: Resource, params?: Params): Promise<RetType<TResult>>
async function get<TResult>(args: [ObjArg | Resource, Params?]): Promise<RetType<TResult>>{
    const { resource, params } = typeof args[0] === 'object' ? args[0] : { resource: args[0], params: args[1] }
    const result = await someAsyncFetch(resource, params)
    return { ...result, cancel: () => { cancelAsyncFetch() }}
}

I'd like TS to be able to infer the get's signature from provided arguments, so it automatically knows that e.g. when calling get('articles', { articleId: 1 }) the return type should beArticleas well as that I need the second argument to be of type{articleId: number}(orundefinedfor array of articles). This is whatGetSignature` union type should define.

So the desired usage would be something like

const user = get('user') // returns User
const article = get('articles', { articleId: 1 }) // returns Article
const articles = get('articles') // returns Article[]

I tried dozens of approaches and none seemed to provide the interface I aim for. Just to mention one of them, I tried to expect signature as a type argument (get<TSignature exntends GetSignature>(...))  and tried to infer the desired signature like in likes of this:

resource: TSignature[0] extends infer T ? T : never

or even

resource: TSignature[0] extends infer T ? Extract<GetSignature, T> : never

But nothing seemed to work. For now I think I'll stick to providing the type argument for TResult, but I'd like to know whether there a way to do what I describe in TS?

Body:
It looks like you want GetSignature to be this:

type GetSignature =
    | ['user', undefined, User]
    | ['articles', { articleId: number }, Article]
    | ['articles', undefined, Article[]]

(note how I swapped Article with Article[] to match with what you are expecting at the end).

Given that, I'd probably separate out the one-arg and two-arg signatures using the Extract and Exclude utility types:

type OneArgSignatures = Extract<GetSignature, [any, undefined, any]>;
type TwoArgSignatures = Exclude<GetSignature, [any, undefined, any]>;

And then define the call signature for get() to be a pair of overloads, one for one-arg and one for two-arg calls:

declare function get<R extends OneArgSignatures[0]>(
    resource: R
): Extract<OneArgSignatures, [R, any, any]>[2];

declare function get<R extends TwoArgSignatures[0]>(
    resource: R,
    params: Extract<TwoArgSignatures, [R, any, any]>[1]
): Extract<TwoArgSignatures, [R, any, any]>[2];

You can see that the functions are generic in R, the resource string literal type.  Note that the compiler generally has the easiest time inferring a type parameter from a value of that type.  Inferring TSignature from resource: TSignature[0] extends infer R ? R : never is problematic, but inferring R from resource: R is straightforward.   Once R is inferred, the compiler can use Extract to calculate the type of params (if present) and the return type.

Let's see if it works:

const u = get("user"); // User
const aa = get("articles"); // Article[]
const a = get("articles", { articleId: 123 }); // Article

Looks good.  Note that I didn't worry about Promises, RetType, or your other overload.  I assume you can take care of that.  Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgKoGdrIN4ChkHIhwC2EAXMumFKAOa4C++uoksiKAglGMAgBsUeQsj5ghlarRANmuMAE8ADigDiEMAGVgdYmACuUFAF58hAD7IA2gHIDmKLYA0yAyAAmEGKAgfXGNAAuuYEVnZwvPxC6C44yJF8ghAAkh6UIAYkAEZYjK48SUIhouG2idEQsa7uXj4gfgVRydZBIQoqKADyDTx0OnpwhsboyCbIAKIAHjSIYAA8Gtq6+kYQrtZwIIo1nt6+-gnbQQB8ANwdqsgAKgDuAPZ9A6sjY5NTggZei5rPQ2sbLY7Nx7eqNI6KU4XXBeQSRFAwdwIPj3EDIOiaeYAJWQEBmEE8ox6ECeK3+I2sAAZTgAKULIEb3IxIShY3AASko01myPmxNJg2GVQ2WNcQLFxxO1gATEELrCBPDkIiQMjgKj0ZicXjIISbg8BS8qlTafTGcyKMhRfTlJFSOguTMoHN5ndHlB+mShegRRLgUDTtYAIwhTnvHkLN2G8nCmyiiF+wOy6EIVHUNxvDFgGkAIgc0Bz7LOyAA9CW0I5cKmQOm4HBM5pcxVkuhC8Wy8hCpVWlW02AEg3sznmzEc65sAlmkI0pQg9KAMzIRhF0vlrvJXBAA" rel="nofollow noreferrer">Playground link to code


问:
How do I mask an email address between the first and the last character before the @ sign?
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

```<code>var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};
</code>```

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

答:
Here is the code with your approach:

var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0][0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first += '*';
        }
        ans = first + parts[0][parts[0].length - 1] +"@" +parts[1];
    }else{

    }
    return ans;
};
```

<p>But if i were you i would use:</p>

<pre class="lang-js prettyprint-override"><code>var mail = "johndoe@abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.@)/gi, '*'.repeat(mail.split('@')[0].length - 2));
console.log(mail);
</code>```

Body:
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

Body:
Here is the code with your approach:

var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0][0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first += '*';
        }
        ans = first + parts[0][parts[0].length - 1] +"@" +parts[1];
    }else{

    }
    return ans;
};

But if i were you i would use:

var mail = "johndoe@abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.@)/gi, '*'.repeat(mail.split('@')[0].length - 2));
console.log(mail);


问:
Enable copy button title on long press on the button
I have UIButton for an address in my tableview cell. When I tap on it once; I open google map with the direction no problem. Now, I want to provide the option for long gesture so if you hold your finger on the button, it provides the option to copy the address which is in the title of the button. This is my code:

```<code>@IBOutlet weak var addressBtn: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()

    addLongPressGesture()
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizer.State.began {

        // how do I make it possible to copy the title of the button here? The address is already inserted as the title of the button

    }
}

func addLongPressGesture(){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 0.5
    self.addressBtn.addGestureRecognizer(longPress)
}
</code>```

This is where on one tap it goes to the map with no problem; so I have no issue here but just fyi:
    @IBAction func addressClicked(_ sender: Any) {

```<code>    if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {

        let street = order.street.replacingOccurrences(of: " ", with: "+")
        let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")

        if street == "" || order.city == "" || order.province == "" || postalCode == ""{
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
        } else {
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
        }

        } else {
            NSLog("Can't use comgooglemaps://")
        }
    }
</code>```

答:
Use

```<code>let text =  addressBtn.currentTitle
</code>```

or

```<code>let text = addressBtn.titleLabel?.text
</code>```

Body:
I have UIButton for an address in my tableview cell. When I tap on it once; I open google map with the direction no problem. Now, I want to provide the option for long gesture so if you hold your finger on the button, it provides the option to copy the address which is in the title of the button. This is my code:

@IBOutlet weak var addressBtn: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()

    addLongPressGesture()
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizer.State.began {

        // how do I make it possible to copy the title of the button here? The address is already inserted as the title of the button

    }
}

func addLongPressGesture(){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 0.5
    self.addressBtn.addGestureRecognizer(longPress)
}

This is where on one tap it goes to the map with no problem; so I have no issue here but just fyi:
    @IBAction func addressClicked(_ sender: Any) {

    if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {

        let street = order.street.replacingOccurrences(of: " ", with: "+")
        let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")

        if street == "" || order.city == "" || order.province == "" || postalCode == ""{
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
        } else {
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
        }

        } else {
            NSLog("Can't use comgooglemaps://")
        }
    }

Body:
Use

let text =  addressBtn.currentTitle

or

let text = addressBtn.titleLabel?.text


问:
Is there an equivalent of Javascript's hasOwnProperty() in Python?
I want to check whether an object has an attribute as a direct (i.e. not inherited) property, similar to Javascript's obj.hasOwnProperty(). How can I do this in Python? hasattr() seems to return inherited attributes as well.

答:
Have you tried using "in"?

If you have a class object you can check if an attribute was defined by:

```<code>"what_you_want_to_search" in object.__dict__
</code>```

Body:
Have you tried using "in"?

If you have a class object you can check if an attribute was defined by:

"what_you_want_to_search" in object.__dict__


问:
How to factor `paths:` in common for push: and pull_request: in github actions?
I’d like to factor the common paths in this:

```<code>on:
  push:
    # Run only on changes on these files
    paths:
      - 'lib/**.nim'
      - 'doc/**.rst'
      - 'doc/nimdoc.css'
      - '.github/workflows/ci_docs.yml'

  pull_request:
    # Run only on changes on these files
    paths:
      - 'lib/**.nim'
      - 'doc/**.rst'
      - '.github/workflows/ci_docs.yml'
</code>```

documentation on github mentions [push, pull_request] but it doesn’t work if we have paths node. What is the syntax to avoid code duplication?

(apologies in advance for cross posting with https://github.community/t/how-to-factor-paths-in-common-for-push-and-pull-request/115967, if I get any answer I'll update on the other end)

答:
If I'm understanding your question correctly you're asking how to list common paths for multiple events, as in on both push and pull_request run for file paths lib/**.nim', 'doc/**.rst', '.github/workflows/ci_docs.yml' that's not currently possible.

Respectfully, it's not a lot of duplication to have the lists in both places, and it's likely that way for some implementation detail reason on GitHub's side of things.

Official docs if you want more reading: https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#onpushpull_requestpaths

Body:
I’d like to factor the common paths in this:

on:
  push:
    # Run only on changes on these files
    paths:
      - 'lib/**.nim'
      - 'doc/**.rst'
      - 'doc/nimdoc.css'
      - '.github/workflows/ci_docs.yml'

  pull_request:
    # Run only on changes on these files
    paths:
      - 'lib/**.nim'
      - 'doc/**.rst'
      - '.github/workflows/ci_docs.yml'

documentation on github mentions [push, pull_request] but it doesn’t work if we have paths node. What is the syntax to avoid code duplication?

(apologies in advance for cross posting with https://github.community/t/how-to-factor-paths-in-common-for-push-and-pull-request/115967, if I get any answer I'll update on the other end)


答:
You can try elasticsearch-py library.

A Little example:

```<code>from elasticsearch import Elasticsearch
from datetime import datetime
es = Elasticsearch(
    ['localhost', 'otherhost'],
    http_auth=('user', 'secret'),
    scheme="https",
    port=443,
)

es.index(index="my-index", id=42, body={"any": "data", "timestamp": datetime.now()})
</code>```

Title: how to query public IP in ELK on python?

Body:
public IP ：

class A： 1.0.0.0~9.255.255.255 11.0.0.0~126.255.255.255

class B： 128.0.0.0~172.15.255.255 172.32.0.0~191.255.255.255

class C： 192.0.0.0~192.168.255.255 192.169.0.0~223.255.255.255

private IP：

class A： 10.0.0.0～10.255.255.255

class B： 172.16.0.0～172.31.255.255

class C： 192.168.0.0～192.168.255.255

If I want to query pulic IP in ELK on python ,how can I do?

I exclude private IP with wildcrd but not work.

          {
            'query':{
                'bool':{
                    'must_not':{
                        'wildcard':{
                            'field':'10.*.*.*  192.168.*.* 172.16.*.*  172.17.*.* ... 172.31.*.*
  192.168.*.* '
                            }
                        }
                    }
                }
            }

Body:
You can try elasticsearch-py library.

A Little example:

from elasticsearch import Elasticsearch
from datetime import datetime
es = Elasticsearch(
    ['localhost', 'otherhost'],
    http_auth=('user', 'secret'),
    scheme="https",
    port=443,
)

es.index(index="my-index", id=42, body={"any": "data", "timestamp": datetime.now()})


问:
Python for-loop won't iterate past first character in stirng
My python function is supposed to take an input that is a string (of only letters and only lowercase letters). The function should output true if there are no repeating letters ( regardless of whether they are consecutive letters or not) and it's suppose to return false if there are repeating letters. My code only checks if the first letter is repeating or not, but doesn't check any other letter in the string. What is the issue?

答:
My solution</p>

```<code>def is_isogram(x):
    if len(str(x)) > len(set(x)):
        return False
    else:
        return True
</code>```

Body:
My solution

def is_isogram(x):
    if len(str(x)) > len(set(x)):
        return False
    else:
        return True


问:
Data not set after fetch in react
This is my code for component employ which not set data but gets count rows correct ( empty ).

I want to set the data after fetching from the server-side.

```<code>import React, { Component } from 'react';

export class Employ extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")

            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        employ: result
                    });
                }
            );
    }

    render() {
        return (
            <div>
                <h2>Employ Data...</h2>
                <table className="table stripted bordered hover">
                    <thead>
                        <tr>
                            <th>EmployeeID</th>
                            <th>FullName</th>
                            <th>EMPCode</th>
                            <th>Mobile</th>
                            <th>Position</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.employ.map(emp => (
                            <tr key={Math.random()}>
                                <td>{emp.EmployeeID}</td>
                                <td>{emp.FullName}</td>
                                <td>{emp.EMPCode}</td>
                                <td>{emp.Mobile}</td>
                                <td>{emp.Position}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        );
    }

}
</code>```

I used Asp.net.Api.core for connecting database(backend).

答:
You can use setState as callback function.

```<code>import React, { Component } from 'react';

export class Employ extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")
            .then(res => res.json())
                .then(result => {
                    this.setState(() => ({
                        employ: result
                    }))
                })
    }

    render() {
        return (
            <div>
                ... YOUR JSX CODE GOES HERE ...
            </div>
        )
    }
}
</code>```

Title: Data not set after fetch in react

Body:
This is my code for component employ which not set data but gets count rows correct ( empty ).

I want to set the data after fetching from the server-side.

import React, { Component } from 'react';

export class Employ extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")

            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        employ: result
                    });
                }
            );
    }

    render() {
        return (

Employ Data...

                            EmployeeID
                            FullName
                            EMPCode
                            Mobile
                            Position

                        {this.state.employ.map(emp => (

                                {emp.EmployeeID}
                                {emp.FullName}
                                {emp.EMPCode}
                                {emp.Mobile}
                                {emp.Position}

                        ))}

        );
    }

}

I used Asp.net.Api.core for connecting database(backend).

Body:
You can use setState as callback function.

import React, { Component } from 'react';

export class Employ extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")
            .then(res => res.json())
                .then(result => {
                    this.setState(() => ({
                        employ: result
                    }))
                })
    }

    render() {
        return (
            <div>
                ... YOUR JSX CODE GOES HERE ...
            </div>
        )
    }
}


问:
Will call by name affect the argument variables passed into the function like called by reference or is it like call by value?
Suppose I have an integer array a

```<code>a[0] = 1
a[1] = 2
a[2] = 3
</code>```

and a function in no particular language

```<code>func swap(int l, int r){
  int temp = l;
  l = r;
  r = temp;
}
</code>```

What is my final value of array a if I execute

```<code>int i = 1;
swap(i,a[i]);
</code>```

in call by value, call by reference and call by name?

I think that call by value would give me the same integer array a = [1,2,3] as changes within the function has no effect to the arguments passed in.

and call by reference would give me the result a = [1,1,3], so what about call by name? Can you show me the steps of the evaluation, I only know that it will pass in the i and a[i] directly into the function call so far but have no ideas what would be affected.

Edit: I have misread the question and array a is supposed to be a = [1,2,3] initially rather than a= [10,20,30]

答:
I'm not aware of any language that has implemented "call by name" since Algol 60 (and possibly a few close derivatives in that era).

But the way to figure it out on paper is:

(1) write out the text of 'swap'.

(2) replace every occurrence of the formal parameter 'l' by the actual argument 'i'.

(3) replace every occurrence of the formal parameter 'r' by the actual argument 'a[i]'.

(4) evaluate the resulting code.

(This would require a little more explanation if there were name clashes, but there aren't)

Steps 1 through 3 get you this code,  commented as to the evaluation.

```<code>  int temp = i;  // temp = 1
  i = a[i];      // i = a[1] = 20
  a[i] = temp;   // a[20] = 1
</code>```

The last line looks like an array bounds violation.

The difference between this and the by-reference case is this: with by-reference, for a[i] we determine prior to the call that the actual argument is a[1], and pass a reference to that single element. Changes to the value of i after that do not affect what is referenced.   But with call-by-name, what the argument refers to is recalculated each time the argument is used, so it always depends on the value of i right there and then.

(Implementationally, the argument a[i] is passed as a pointer to a little piece of code -- called a 'thunk' -- that will compute the address of a[i])

Body:
Suppose I have an integer array a

a[0] = 1
a[1] = 2
a[2] = 3

and a function in no particular language

func swap(int l, int r){
  int temp = l;
  l = r;
  r = temp;
}

What is my final value of array a if I execute

int i = 1;
swap(i,a[i]);

in call by value, call by reference and call by name?

I think that call by value would give me the same integer array a = [1,2,3] as changes within the function has no effect to the arguments passed in.

and call by reference would give me the result a = [1,1,3], so what about call by name? Can you show me the steps of the evaluation, I only know that it will pass in the i and a[i] directly into the function call so far but have no ideas what would be affected.

Edit: I have misread the question and array a is supposed to be a = [1,2,3] initially rather than a= [10,20,30]

Body:
I'm not aware of any language that has implemented "call by name" since Algol 60 (and possibly a few close derivatives in that era).

But the way to figure it out on paper is:

(1) write out the text of 'swap'.

(2) replace every occurrence of the formal parameter 'l' by the actual argument 'i'.

(3) replace every occurrence of the formal parameter 'r' by the actual argument 'a[i]'.

(4) evaluate the resulting code.

(This would require a little more explanation if there were name clashes, but there aren't)

Steps 1 through 3 get you this code,  commented as to the evaluation.

  int temp = i;  // temp = 1
  i = a[i];      // i = a[1] = 20
  a[i] = temp;   // a[20] = 1

The last line looks like an array bounds violation.

The difference between this and the by-reference case is this: with by-reference, for a[i] we determine prior to the call that the actual argument is a[1], and pass a reference to that single element. Changes to the value of i after that do not affect what is referenced.   But with call-by-name, what the argument refers to is recalculated each time the argument is used, so it always depends on the value of i right there and then.

(Implementationally, the argument a[i] is passed as a pointer to a little piece of code -- called a 'thunk' -- that will compute the address of a[i])


问:
datalist how to tell if selected input in dropdown
```<code> <label>Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onchange="castvote()"  /></label>
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>

function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    console.log("Chrome" in datalist);
    }
</code>```

when i select Chrome or any other options and check to see if it is one of the options i wanted (one of the drop down options) the console is returning false. How do I make it return true (detect that one of the options I selected is indeed the dropdown options)? If possible no Jquery please

答:
function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    // console.log("Chrome" in datalist);
    var browserChildren = document.getElementById('browsers').children

    var flag = false
    for(let i = 0; i < browserChildren.length; i++){
        flag = browserChildren[i].value === datalist.value || flag
    }
    console.log(flag)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onchange="castvote()"  /></label>
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist></code>```

Body:
 Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onchange="castvote()"  />
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>

function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    console.log("Chrome" in datalist);
    }

when i select Chrome or any other options and check to see if it is one of the options i wanted (one of the drop down options) the console is returning false. How do I make it return true (detect that one of the options I selected is indeed the dropdown options)? If possible no Jquery please

Body:
function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    // console.log("Chrome" in datalist);
    var browserChildren = document.getElementById('browsers').children

    var flag = false
    for(let i = 0; i < browserChildren.length; i++){
        flag = browserChildren[i].value === datalist.value || flag
    }
    console.log(flag)
}

<label>Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onchange="castvote()"  /></label>
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>


问:
How to get the 3 highest values in a HashMap?
I have a hashmap which is the following:

```<code>    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);
</code>```

How would I get the keys which have the 3 highest values? So it would return:

```<code>    "c", "e", "b"
</code>```

Thanks.

答:
Here's my take on it:  This keeps track of only the top n items in a TreeSet.

```<code>import java.util.*;
import java.util.stream.Collectors;

public class TopN {
    public static <E> Collection<E> topN(Iterable<E> values, Comparator<? super E> comparator, int n) {
        NavigableSet<E> result = new TreeSet<>(comparator.reversed());
        for (E value : values) {
            result.add(value);
            if (result.size() > n) {
                result.remove(result.last());
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, Integer> hm = Map.of(
                "a", 1,
                "b", 12,
                "c", 53,
                "d", 2,
                "e", 17,
                "f", 8,
                "g", 8);

        List<String> result = topN(hm.entrySet(), Map.Entry.comparingByValue(), 3)
                .stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        System.out.println(result);
    }
}
</code>```

The final output is [c, e, b]

Body:
I have a hashmap which is the following:

    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);

How would I get the keys which have the 3 highest values? So it would return:

    "c", "e", "b"

Thanks.

Body:
Here's my take on it:  This keeps track of only the top n items in a TreeSet.

import java.util.*;
import java.util.stream.Collectors;

public class TopN {
    public static <E> Collection<E> topN(Iterable<E> values, Comparator<? super E> comparator, int n) {
        NavigableSet<E> result = new TreeSet<>(comparator.reversed());
        for (E value : values) {
            result.add(value);
            if (result.size() > n) {
                result.remove(result.last());
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, Integer> hm = Map.of(
                "a", 1,
                "b", 12,
                "c", 53,
                "d", 2,
                "e", 17,
                "f", 8,
                "g", 8);

        List<String> result = topN(hm.entrySet(), Map.Entry.comparingByValue(), 3)
                .stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        System.out.println(result);
    }
}

The final output is [c, e, b]


问:
Android studio create multiple .iml for app module
I have created a new Android Kotlin project using Android Studio. Everything work as expected initially. However, when I close Android Studio and reopen it again a new .iml file is created inside the app module

Issue

Create a project in Android studio

Sync and build the project

Close Android Studio

Reopen Android Studio

New *.iml file is created for the app module

Workaround

Delete the .idea folder

Delete all *.iml files

Re-import project in Android studio

I have to do this workaround steps each time android studio launches. Is there any permanent solution for this. My Android studio version is 3.6.2

Screenshots

Project

app module

Thanks

答:
This project contains multiple modules, one for the root of the project where you have build.gradle in the root and another for the app with the second build file. Modules can be also created for multiple Gradle source roots. This behavior is by design and is not an issue that needs to be fixed.

See the document about sharing the project files which mentions that you can ignore .iml files for Gradle projects as they are generated on importing.


问:
Tips for using vim over a slow connection?
I'm using vim over a slow connection and it is a little painful. Is there anything I can do in vim to alleviate the pain?</p>

答:
Over a slow connection, it's painful to move the cursor character by character, because you don't get immediate visual feedback, so you always end up moving too much or too little.

So what's most effective to me is to use smarter movements and commands, like:

fx -- jump to next letter x

5w -- move 5 words forward

ci( -- replace what's between the parentheses

dap -- delete current paragraph

and a long etcetera.

I miss those commands all the time when typing in browser's textareas, like now :)

OwnerDisplayName: Paul Wicks

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Roberto Bonvallet


问:
A pattern that matches all except starting with a word
How can I set a regex pattern which matches all words but the strings which starts with

/word

/word/

/word/ following by anything else.

I think the pattern starts with  \A but I don'0t know how to tell that should not follow a word

Thanks

答: Take a look at the lookaround feature offered by regular expressions. Also, a similar thread. Also, posting your question in terms of a concrete sample problem might help you get a few working sample snippets.</p>


问:
Can't select same item twice on CollectionView
I use a CollectionView control to display a list of files, if users click an item a popup appears displaying information about the file and a button to download it, the problem is that I use the SelectionChanged method of the CollectionView to run this action, but if users close the popup and click again on the same item nothing happens. Back when we use ListView control, the ItemTapped event runs every time the users click the same item, but i need to changed to CollectionView because later we'll change the file item from a single row to multiple columns (2 or 3).

It is possible to make the users click on the same item multiple times with CollectionView control ?

P.D: also try to set the SelectedItem to null but the app crashes if the users select again the same item.

答:
It works for me when i set SelectedItem to null.What else did you do when you set selectitem?

below is my simple sample,i use DisplayAlert instead of popup.

the xaml ：

```<code><CollectionView x:Name="collection" SelectionChanged="CollectionView_SelectionChanged" SelectionMode="Single" >
            <CollectionView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>Baboon</x:String>
                    <x:String>Capuchin Monkey</x:String>
                    <x:String>Blue Monkey</x:String>
                    <x:String>Squirrel Monkey</x:String>
                    <x:String>Golden Lion Tamarin</x:String>
                    <x:String>Howler Monkey</x:String>
                    <x:String>Japanese Macaque</x:String>
                </x:Array>
            </CollectionView.ItemsSource>
</CollectionView>
</code>```

in page xaml.cs:

```<code>private async void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (collection.SelectedItem != null)
        {
            await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");
            collection.SelectedItem = null;

        }

    }
</code>```

the effect is like below：

Body:
It works for me when i set SelectedItem to null.What else did you do when you set selectitem?

below is my simple sample,i use DisplayAlert instead of popup.

the xaml ：

<CollectionView x:Name="collection" SelectionChanged="CollectionView_SelectionChanged" SelectionMode="Single" >
            <CollectionView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>Baboon</x:String>
                    <x:String>Capuchin Monkey</x:String>
                    <x:String>Blue Monkey</x:String>
                    <x:String>Squirrel Monkey</x:String>
                    <x:String>Golden Lion Tamarin</x:String>
                    <x:String>Howler Monkey</x:String>
                    <x:String>Japanese Macaque</x:String>
                </x:Array>
            </CollectionView.ItemsSource>
</CollectionView>

in page xaml.cs:

private async void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (collection.SelectedItem != null)
        {
            await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");
            collection.SelectedItem = null;

        }

    }

the effect is like below：


问:
How to check all column names of Tables in oracle with regex?
I usually search column names in Oracle as we have 1000+ tables. Is there simpler way to search column names using regex.

For example Column name have CURRENCY or COUNTRY etc.

答:
I would try something like this:

```<code>SELECT table_name, column_name from user_tab_columns

WHERE REGEXP_LIKE(column_name, 'country|currency', 'i' );
</code>```

i : Perform case-insensitive matching.

Body:
I would try something like this:

SELECT table_name, column_name from user_tab_columns

WHERE REGEXP_LIKE(column_name, 'country|currency', 'i' );

i : Perform case-insensitive matching.


问:
How to automate creating models in django?
My models are generated from the shapefiles by using ogrinspect . But , after the creation of the model , lets say the user want to add an additional attribute . For this , the new attribute should be reflected in two tables . One should contain the name of the attribute , the other the attribute as a column . The name of the attribute doesnt need a change in model , and can be easily taken care of . But how to add an attribute to a table which was generated automatically ?</p>

答: Use post_save signal. (docs)

Body: Use post_save signal. (docs)


问:
What is the difference between git diff HEAD vs. git diff --staged?
What is the difference between git diff HEAD and git diff --staged? I tried both but both give the same output.

答: Another edge case difference:  In a newly created git repo, where only git init has been run so far, git diff HEAD will result in a fatal error (ambiguous argument 'HEAD') while git diff --staged will produce no output.


问:
Pass connection string to code-first DbContext
How do I pass a connection string to entity framework's code-first DbContext? My database generation works correctly when both DbContext and the connection string in web.config is in the same project and named the same way. But now I need to move the DbContext to another project so I'm testing passing a connection string to it as follows:

Model & Context

```<code>public class Dinner
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
}

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
        : base(connString)
    {
    }
    public DbSet<Dinner> Dinners { get; set; }
}
</code>```

Action

```<code>    public ActionResult Index()
    {
        var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);

        var dinners = (from d in db.Dinners
                      select d).ToList();
        return View(dinners);
    }
</code>```

Web.Config

```<code><connectionStrings>
  <add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
</code>```

If I set a breakpoint in the action an analyze the db, the connection string is there, but it does not create or find the database or anything.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

答:
from here

```<code> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
    }
</code>```

note you may need to add Microsoft.EntityFrameworkCore.SqlServer

Body:
How do I pass a connection string to entity framework's code-first DbContext? My database generation works correctly when both DbContext and the connection string in web.config is in the same project and named the same way. But now I need to move the DbContext to another project so I'm testing passing a connection string to it as follows:

Model & Context

public class Dinner
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
}

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
        : base(connString)
    {
    }
    public DbSet<Dinner> Dinners { get; set; }
}

Action

    public ActionResult Index()
    {
        var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);

        var dinners = (from d in db.Dinners
                      select d).ToList();
        return View(dinners);
    }

Web.Config

<connectionStrings>
  <add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

If I set a breakpoint in the action an analyze the db, the connection string is there, but it does not create or find the database or anything.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Body:
from here

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
    }

note you may need to add Microsoft.EntityFrameworkCore.SqlServer


问:
Sympy square root of a matrix - elements are not simplified
I tried the following operation - square root of a symbolic matrix. I'm impressed at sympy's abilities. If you notice at the end, the square root of the matrix is left in a rather uncanny state - the square roots can all disappear and the elements simplify rather nicely. Is there a way to ask sympy to do this simplification for us?</p>

```<code>import sympy as sp
a, b, c = sp.symbols("a b c")

m = sp.Matrix([
    [a**2 + b**2, 0, 2*a*b],
    [0, c**2, 0],
    [2*a*b, 0, a**2 + b**2]
])

m**(1/2)
</code>```

答:
You can simplify like this:

```<code>In [8]: sqrt(m).doit().factor(deep=True)
Out[8]:
⎡    __________      __________                 __________      __________⎤
⎢   ╱        2      ╱        2                 ╱        2      ╱        2 ⎥
⎢ ╲╱  (a - b)     ╲╱  (a + b)                ╲╱  (a - b)     ╲╱  (a + b)  ⎥
⎢ ───────────── + ─────────────      0     - ───────────── + ─────────────⎥
⎢       2               2                          2               2      ⎥
⎢                                                                         ⎥
⎢                                    ____                                 ⎥
⎢                                   ╱  2                                  ⎥
⎢               0                 ╲╱  c                   0               ⎥
⎢                                                                         ⎥
⎢     __________      __________               __________      __________ ⎥
⎢    ╱        2      ╱        2               ╱        2      ╱        2  ⎥
⎢  ╲╱  (a - b)     ╲╱  (a + b)              ╲╱  (a - b)     ╲╱  (a + b)   ⎥
⎢- ───────────── + ─────────────     0      ───────────── + ───────────── ⎥
⎣        2               2                        2               2       ⎦
</code>```

Declaring the symbols to be positive with

```<code>a, b, c = sp.symbols("a b c", positive=True)

</code>```

gives this

```<code>In [13]: sqrt(m).doit().factor(deep=True)
Out[13]:
⎡a + b + │a - b│     a + b - │a - b│⎤
⎢───────────────  0  ───────────────⎥
⎢       2                   2       ⎥
⎢                                   ⎥
⎢       0         c         0       ⎥
⎢                                   ⎥
⎢a + b - │a - b│     a + b + │a - b│⎥
⎢───────────────  0  ───────────────⎥
⎣       2                   2       ⎦
</code>```

Body:
I tried the following operation - square root of a symbolic matrix. I'm impressed at sympy's abilities. If you notice at the end, the square root of the matrix is left in a rather uncanny state - the square roots can all disappear and the elements simplify rather nicely. Is there a way to ask sympy to do this simplification for us?

import sympy as sp
a, b, c = sp.symbols("a b c")

m = sp.Matrix([
    [a**2 + b**2, 0, 2*a*b],
    [0, c**2, 0],
    [2*a*b, 0, a**2 + b**2]
])

m**(1/2)

Body:
You can simplify like this:

In [8]: sqrt(m).doit().factor(deep=True)
Out[8]:
⎡    __________      __________                 __________      __________⎤
⎢   ╱        2      ╱        2                 ╱        2      ╱        2 ⎥
⎢ ╲╱  (a - b)     ╲╱  (a + b)                ╲╱  (a - b)     ╲╱  (a + b)  ⎥
⎢ ───────────── + ─────────────      0     - ───────────── + ─────────────⎥
⎢       2               2                          2               2      ⎥
⎢                                                                         ⎥
⎢                                    ____                                 ⎥
⎢                                   ╱  2                                  ⎥
⎢               0                 ╲╱  c                   0               ⎥
⎢                                                                         ⎥
⎢     __________      __________               __________      __________ ⎥
⎢    ╱        2      ╱        2               ╱        2      ╱        2  ⎥
⎢  ╲╱  (a - b)     ╲╱  (a + b)              ╲╱  (a - b)     ╲╱  (a + b)   ⎥
⎢- ───────────── + ─────────────     0      ───────────── + ───────────── ⎥
⎣        2               2                        2               2       ⎦

Declaring the symbols to be positive with

a, b, c = sp.symbols("a b c", positive=True)

gives this

In [13]: sqrt(m).doit().factor(deep=True)
Out[13]:
⎡a + b + │a - b│     a + b - │a - b│⎤
⎢───────────────  0  ───────────────⎥
⎢       2                   2       ⎥
⎢                                   ⎥
⎢       0         c         0       ⎥
⎢                                   ⎥
⎢a + b - │a - b│     a + b + │a - b│⎥
⎢───────────────  0  ───────────────⎥
⎣       2                   2       ⎦


问:
Inside the console.log dollar symbol isn't working
This is the code for greet.js where we pass 2 parameters via command line. But it isn't printing the proper results.</p>

```<code>const firstname = process.argv[2];
const lastname = process.argv[3];
console.log('hello ${firstname} ${lastname}');
</code>```

答:
You should use the ` symbol instead of '

Take a look at Template String:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/template_strings

Body:
This is the code for greet.js where we pass 2 parameters via command line. But it isn't printing the proper results.

const firstname = process.argv[2];
const lastname = process.argv[3];
console.log('hello ${firstname} ${lastname}');


问:
Error from Azure function: ModuleNotFoundError
I followed the official documentation to set up my requirements.txt file. My understanding was that the function should be able to use modules if they are in requirements.txt. Here is an example of what that file looks like, with all the modules and their versions written in this way:

```<code>azure-common==1.1.12
azure-keyvault==1.0.0
azure-mgmt-keyvault==1.0.0
azure-mgmt-nspkg==2.0.0
azure-mgmt-resource==1.2.2
azure-storage-blob==12.3.1
azure-mgmt-subscription==0.5.0
azure-mgmt-network==10.2.0
azure-functions==1.2.1
</code>```

However, when I look at the function's logs, I can see that it keeps throwing the error, "ModuleNotFoundError: No module named 'azure.common'". This is the first module I try to import in __init__.py. What am I doing wrong?

答:
It seems the modules you use in your function are all old version(such as azure-common==1.1.12, azure-keyvault==1.0.0.....). So could you please install the modules with the latest version. You can search them on this page and for example if install the latest azure-common module, just run the command pip install azure-common(no need the version number) it will install the latest version of the module.

And then use the command below in your VS code to generate the "requirements.txt" automatically.

```<code>pip freeze > requirements.txt
</code>```

Then deploy the function code from local to azure by the command:

```<code>func azure functionapp publish <function app name> --build remote
</code>```

It will deploy the code to azure and install the modules according to the content in the "requirements.txt" which you generated just now.

Hope it helps~

Body:
I followed the official documentation to set up my requirements.txt file. My understanding was that the function should be able to use modules if they are in requirements.txt. Here is an example of what that file looks like, with all the modules and their versions written in this way:

azure-common==1.1.12
azure-keyvault==1.0.0
azure-mgmt-keyvault==1.0.0
azure-mgmt-nspkg==2.0.0
azure-mgmt-resource==1.2.2
azure-storage-blob==12.3.1
azure-mgmt-subscription==0.5.0
azure-mgmt-network==10.2.0
azure-functions==1.2.1

However, when I look at the function's logs, I can see that it keeps throwing the error, "ModuleNotFoundError: No module named 'azure.common'". This is the first module I try to import in __init__.py. What am I doing wrong?

Body:
It seems the modules you use in your function are all old version(such as azure-common==1.1.12, azure-keyvault==1.0.0.....). So could you please install the modules with the latest version. You can search them on this page and for example if install the latest azure-common module, just run the command pip install azure-common(no need the version number) it will install the latest version of the module.

And then use the command below in your VS code to generate the "requirements.txt" automatically.

pip freeze > requirements.txt

Then deploy the function code from local to azure by the command:

func azure functionapp publish <function app name> --build remote

It will deploy the code to azure and install the modules according to the content in the "requirements.txt" which you generated just now.

Hope it helps~


问:
Scroll Bar in JFrame Not Showing
I'm trying to add a horizontal scroll bar to my JFrame that essentially contains a bunch of JButtons. In my code, you can see that I've added 19 green JButtons called "Ground", as well as several other buttons. The last few clearly go off-screen. What I want is to implement a scroll bar so that I can view all the buttons. Unfortunately, I can't seem to get the JScrollPane scroll bar working. It shows up, but doesn't actually scroll.

I'd appreciate some feedback!

```<code>import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class World {
    public static void main(String[] args) {
        // Just defining my own colour hues
        Color blue = new Color(77, 121, 255);
        Color green = new Color(0, 255, 0);
        Color grey = new Color(166, 166, 166);
        Color red = new Color(255, 102, 102);

        // Create the JFrame
        JFrame f = new JFrame("World");

        // Creating the JButtons. They're added to the JFrame at the end of the code.
        JButton object0 = new JButton("Object");
        object0.setBounds(0, 0, 80, 80);
        object0.setBackground(red);

        JButton object1 = new JButton("Object");
        object1.setBounds(80, 80, 80, 80);
        object1.setBackground(red);

        // This just automatically adds the "Ground" buttons to the frame, as they are many of them.
        ArrayList<JButton> groundList = new ArrayList<JButton>();
        for (int i = 0; i < 19; i++) {
            groundList.add(new JButton("Ground"));
        }
        JButton temp;
        int x = 80;
        for (int i = 0; i < 19; i++) {
            temp = groundList.get(i);
            temp.setBounds(x, 0, 80, 80);
            temp.setBackground(green);
            f.add(temp);
            x = x + 80;
        }

        JButton wall = new JButton("Wall");
        wall.setBounds(80, 160, 80, 80);
        wall.setBackground(grey);

        JButton avatar = new JButton("Avatar");
        avatar.setBounds(0, 80, 80, 80);
        avatar.setBackground(blue);

        f.add(object0);
        f.add(object1);
        f.add(wall);
        f.add(avatar);

        JScrollPane scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVisible(true);
        f.add(scroll);  // This adds the scroll bars but doesn't actually make them work.
        f.setSize(800, 200);
        f.setVisible(true);
    }
}
</code>```

答:
That's because you need to drop the scrollable content inside the scroll bar instance.
Thus you need first to create a JPanel and add all your buttons to the panel, then create the JScrollPane with the panel passed to its constructor.

Adding UI components directly to the JFrame is not a good practice.

Try running this and inspecting changes, it should work:

```<code>import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class World {
    public static void main(String[] args) {
        // Just defining my own colour hues
        Color blue = new Color(77, 121, 255);
        Color green = new Color(0, 255, 0);
        Color grey = new Color(166, 166, 166);
        Color red = new Color(255, 102, 102);

        // Create the JFrame
        JFrame f = new JFrame("World");
        //button will be added to this panel
        JPanel myPanel = new JPanel();

        // Creating the JButtons. They're added to the JFrame at the end of the code.
        JButton object0 = new JButton("Object");
        object0.setBounds(0, 0, 80, 80);
        object0.setBackground(red);

        JButton object1 = new JButton("Object");
        object1.setBounds(80, 80, 80, 80);
        object1.setBackground(red);

        // This just automatically adds the "Ground" buttons to the frame, as they are many of them.
        ArrayList<JButton> groundList = new ArrayList<JButton>();
        for (int i = 0; i < 19; i++) {
            groundList.add(new JButton("Ground"));
        }
        JButton temp;
        int x = 80;
        for (int i = 0; i < 19; i++) {
            temp = groundList.get(i);
            temp.setBounds(x, 0, 80, 80);
            temp.setBackground(green);
            myPanel.add(temp);
            x = x + 80;
        }

        JButton wall = new JButton("Wall");
        wall.setBounds(80, 160, 80, 80);
        wall.setBackground(grey);

        JButton avatar = new JButton("Avatar");
        avatar.setBounds(0, 80, 80, 80);
        avatar.setBackground(blue);

        myPanel.add(object0);
        myPanel.add(object1);
        myPanel.add(wall);
        myPanel.add(avatar);

        //notice how the panel is dropped inside the scroll pane
        JScrollPane scroll = new JScrollPane(myPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVisible(true);
        //f.add(scroll);  // This adds the scroll bars but doesn't actually make them work.

        //finally add the scroll to frame's content pane .. which is more proper than adding to frame directly
        f.getContentPane().add(scroll, BorderLayout.CENTER);
        f.setSize(800, 200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}
</code>```

However

If you consider setting initial preferred size to your panel, you'll get all buttons line wrapped and you will not need to scroll horizontall:

```<code>myPanel.setPreferredSize(new Dimension(100, 200));
</code>```

Result:

Title: Scroll Bar in JFrame Not Showing

Body:
I'm trying to add a horizontal scroll bar to my JFrame that essentially contains a bunch of JButtons. In my code, you can see that I've added 19 green JButtons called "Ground", as well as several other buttons. The last few clearly go off-screen. What I want is to implement a scroll bar so that I can view all the buttons. Unfortunately, I can't seem to get the JScrollPane scroll bar working. It shows up, but doesn't actually scroll.

I'd appreciate some feedback!

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class World {
    public static void main(String[] args) {
        // Just defining my own colour hues
        Color blue = new Color(77, 121, 255);
        Color green = new Color(0, 255, 0);
        Color grey = new Color(166, 166, 166);
        Color red = new Color(255, 102, 102);

        // Create the JFrame
        JFrame f = new JFrame("World");

        // Creating the JButtons. They're added to the JFrame at the end of the code.
        JButton object0 = new JButton("Object");
        object0.setBounds(0, 0, 80, 80);
        object0.setBackground(red);

        JButton object1 = new JButton("Object");
        object1.setBounds(80, 80, 80, 80);
        object1.setBackground(red);

        // This just automatically adds the "Ground" buttons to the frame, as they are many of them.
        ArrayList<JButton> groundList = new ArrayList<JButton>();
        for (int i = 0; i < 19; i++) {
            groundList.add(new JButton("Ground"));
        }
        JButton temp;
        int x = 80;
        for (int i = 0; i < 19; i++) {
            temp = groundList.get(i);
            temp.setBounds(x, 0, 80, 80);
            temp.setBackground(green);
            f.add(temp);
            x = x + 80;
        }

        JButton wall = new JButton("Wall");
        wall.setBounds(80, 160, 80, 80);
        wall.setBackground(grey);

        JButton avatar = new JButton("Avatar");
        avatar.setBounds(0, 80, 80, 80);
        avatar.setBackground(blue);

        f.add(object0);
        f.add(object1);
        f.add(wall);
        f.add(avatar);

        JScrollPane scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVisible(true);
        f.add(scroll);  // This adds the scroll bars but doesn't actually make them work.
        f.setSize(800, 200);
        f.setVisible(true);
    }
}

Body:
That's because you need to drop the scrollable content inside the scroll bar instance.
Thus you need first to create a JPanel and add all your buttons to the panel, then create the JScrollPane with the panel passed to its constructor.

Adding UI components directly to the JFrame is not a good practice.

Try running this and inspecting changes, it should work:

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class World {
    public static void main(String[] args) {
        // Just defining my own colour hues
        Color blue = new Color(77, 121, 255);
        Color green = new Color(0, 255, 0);
        Color grey = new Color(166, 166, 166);
        Color red = new Color(255, 102, 102);

        // Create the JFrame
        JFrame f = new JFrame("World");
        //button will be added to this panel
        JPanel myPanel = new JPanel();

        // Creating the JButtons. They're added to the JFrame at the end of the code.
        JButton object0 = new JButton("Object");
        object0.setBounds(0, 0, 80, 80);
        object0.setBackground(red);

        JButton object1 = new JButton("Object");
        object1.setBounds(80, 80, 80, 80);
        object1.setBackground(red);

        // This just automatically adds the "Ground" buttons to the frame, as they are many of them.
        ArrayList<JButton> groundList = new ArrayList<JButton>();
        for (int i = 0; i < 19; i++) {
            groundList.add(new JButton("Ground"));
        }
        JButton temp;
        int x = 80;
        for (int i = 0; i < 19; i++) {
            temp = groundList.get(i);
            temp.setBounds(x, 0, 80, 80);
            temp.setBackground(green);
            myPanel.add(temp);
            x = x + 80;
        }

        JButton wall = new JButton("Wall");
        wall.setBounds(80, 160, 80, 80);
        wall.setBackground(grey);

        JButton avatar = new JButton("Avatar");
        avatar.setBounds(0, 80, 80, 80);
        avatar.setBackground(blue);

        myPanel.add(object0);
        myPanel.add(object1);
        myPanel.add(wall);
        myPanel.add(avatar);

        //notice how the panel is dropped inside the scroll pane
        JScrollPane scroll = new JScrollPane(myPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVisible(true);
        //f.add(scroll);  // This adds the scroll bars but doesn't actually make them work.

        //finally add the scroll to frame's content pane .. which is more proper than adding to frame directly
        f.getContentPane().add(scroll, BorderLayout.CENTER);
        f.setSize(800, 200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

However

If you consider setting initial preferred size to your panel, you'll get all buttons line wrapped and you will not need to scroll horizontall:

myPanel.setPreferredSize(new Dimension(100, 200));

Result:


问:
Is it possible to parse the templateURL in an Angular component?
I wish to generate a Table of Contents ( ToC ) by parsing the HTML that is already present in the templateUrl of my component.

This is my component.ts :

```<code>@Component({
  selector: 'app-presentation',
  templateUrl: './presentation.component.html',
  styleUrls: ['./presentation.component.css']
})
export class PresentationComponent implements OnInit {
  public toc = '';

  constructor() { }

  ngOnInit(): void {
    // parse tempalteUrl here
    // set the this.toc variable
  }
}
</code>```

and this is my component.html :

```<code><div class="container">
  <div class="row">
    <div class="col-sm-4">
      {{toc}}
    </div>
    <div class="col-sm-8">
      <h1>Title</h1>
      <h2>Sub Title1</h2>
      <p>some text</p>
      <h2>Sub Title2</h2>
      <p>more text</p>
      <h1>Title2</h1>
      <h2>Sub Title3</h2>
      <p>random text</p>
      <h2>Sub Title4</h2>
      <p>extra text</p>
    </div>
  </div>
</div>
</code>```

What I wish to do is to extract all of the  and children  and then use them to generate the ToC.

Only
 has the elements I am interested in

All
 are direct children of that div

All
 are direct children of a

The aim of what I am trying to do is have as little HTML as possible to edit at each update when I want to change the content of my website.

答:
Couple ways I can think of are inject ElementRef if just reading whole HTML doc, Renderer2 if going to modify HTML and output in ngOnInit(); add template ref and read ViewChild in ngAfterViewInit()

...

```<code>import { Component , ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('toc') toc: ElementRef;

  constructor(private elRef: ElementRef) {}

  ngOnInit() {
    console.log(this.elRef.nativeElement.innerHTML);
  }

  //template ref + viewChild
  ngAfterViewInit() {
    console.log(this.toc.nativeElement.innerHTML);
  }
}
</code>```

Body:
I wish to generate a Table of Contents ( ToC ) by parsing the HTML that is already present in the templateUrl of my component.

This is my component.ts :

@Component({
  selector: 'app-presentation',
  templateUrl: './presentation.component.html',
  styleUrls: ['./presentation.component.css']
})
export class PresentationComponent implements OnInit {
  public toc = '';

  constructor() { }

  ngOnInit(): void {
    // parse tempalteUrl here
    // set the this.toc variable
  }
}

and this is my component.html :

      {{toc}}

Title

Sub Title1

some text

Sub Title2

more text

Title2

Sub Title3

random text

Sub Title4

extra text

What I wish to do is to extract all of the  and children  and then use them to generate the ToC.

Only
 has the elements I am interested in

All
 are direct children of that div

All
 are direct children of a

The aim of what I am trying to do is have as little HTML as possible to edit at each update when I want to change the content of my website.

Body:
Couple ways I can think of are inject ElementRef if just reading whole HTML doc, Renderer2 if going to modify HTML and output in ngOnInit(); add template ref and read ViewChild in ngAfterViewInit()

<div #toc class="col-sm-8">...</div>

import { Component , ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('toc') toc: ElementRef;

  constructor(private elRef: ElementRef) {}

  ngOnInit() {
    console.log(this.elRef.nativeElement.innerHTML);
  }

  //template ref + viewChild
  ngAfterViewInit() {
    console.log(this.toc.nativeElement.innerHTML);
  }
}


问:
Restrict S3 sub-folder level bucket policy about private and public
We have a lot of information that we can make our bucket to public and private by bucket level. But I'm curious that we can make bucket policy to folder level even to sub-folders. Following is folder structure in my current S3 bucket.

```<code>companies/aa-company/public-folder
companies/aa-company/private-folder
companies/bb-company/public-folder
companies/bb-company/private-folder
</code>```

What I want to know is I want to make Public Read Access to public-folder in bucket policy. Is it possible to do?

答:
Yes, it's absolutely possible. You can use wildcards to achieve this.</p>

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::<bucket-name>/companies/aa-company/public-folder*",
                "arn:aws:s3:::<bucket-name>/companies/bb-company/public-folder*"
            ]
        }
    ]
}
</code>```

Body:
We have a lot of information that we can make our bucket to public and private by bucket level. But I'm curious that we can make bucket policy to folder level even to sub-folders. Following is folder structure in my current S3 bucket.

companies/aa-company/public-folder
companies/aa-company/private-folder
companies/bb-company/public-folder
companies/bb-company/private-folder

What I want to know is I want to make Public Read Access to public-folder in bucket policy. Is it possible to do?

Body:
Yes, it's absolutely possible. You can use wildcards to achieve this.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::<bucket-name>/companies/aa-company/public-folder*",
                "arn:aws:s3:::<bucket-name>/companies/bb-company/public-folder*"
            ]
        }
    ]
}


问:
ValueError: Error when checking target: expected output to have shape (1,) but got array with shape (2,)
I'm trying to create my face detection model on google colab tpu.
Basically, it's a copy of VGG16. Has same layers except the first one and the last three.
It runs on Python 2 notebook on colab.

I've seen other questions, they all get more than required members in an array and there are solutions for them.
Others are unanswered.

It raises an error when run the cell with training code for my model.

#img_data contains images converted to array and pre-processed
img_data = np.array(img_data_list)
img_data=np.rollaxis(img_data,1,0)
img_data =img_data[0]

#outputs
(2000, 1, 224, 224, 3)
(1, 2000, 224, 224, 3)
(1, 2000, 224, 224, 3)

num_classes = 2
num_of_samples = img_data.shape[0]
labels = np.ones((num_of_samples,),dtype='int64')
labels[0:1000]=0
labels[1000:]=1
names = ['happy' , 'not happy']

Y = np_utils.to_categorical(labels, num_classes)

x,y = shuffle(img_data,Y, random_state=2)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.BatchNormalization(input_shape=(224,224,3)))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D())

model.add(tf.keras.layers.Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu', name='fc1'))
model.add(tf.keras.layers.Dense(128, activation='relu', name='fc2'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax', name='output'))
model.summary()
```

<h1>Training the model</h1>

<pre class="lang-python prettyprint-override"><code>import os
tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    model,
    strategy=tf.contrib.tpu.TPUDistributionStrategy(
        tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
    )
)
tpu_model.compile(
    optimizer=tf.train.AdamOptimizer(learning_rate=1e-3, ),
    loss=tf.keras.losses.sparse_categorical_crossentropy,
    metrics=['sparse_categorical_accuracy']
)

def train_gen(batch_size):
  while True:
    offset = np.random.randint(0, x_train.shape[0] - batch_size)
    yield x_train[offset:offset+batch_size], y_train[offset:offset + batch_size]

tpu_model.fit_generator(
    train_gen(1024),
    epochs=10,
    steps_per_epoch=100,
    verbose = 1,
    validation_data=(x_test, y_test),
)
</code>```

Expected results :

Array with probabilities of each label.

Actual results :

ValueErrorTraceback (most recent call last)
<ipython-input-37-bffa1e87ffe0> in <module>()
     24     steps_per_epoch=100,
     25     verbose = 1,
---> 26     validation_data=(x_test, y_test),
     27 )
ValueError: Error when checking target: expected output to have shape (1,) but got array with shape (2,)
```

答:
your problem maybe is that y label should be processed onehot,
you used tf.keras.losses.categorical_crossentropy could ignore this procedure.

Body:
I'm trying to create my face detection model on google colab tpu.
Basically, it's a copy of VGG16. Has same layers except the first one and the last three.
It runs on Python 2 notebook on colab.

I've seen other questions, they all get more than required members in an array and there are solutions for them.
Others are unanswered.

It raises an error when run the cell with training code for my model.

#img_data contains images converted to array and pre-processed
img_data = np.array(img_data_list)
img_data=np.rollaxis(img_data,1,0)
img_data =img_data[0]

#outputs
(2000, 1, 224, 224, 3)
(1, 2000, 224, 224, 3)
(1, 2000, 224, 224, 3)

num_classes = 2
num_of_samples = img_data.shape[0]
labels = np.ones((num_of_samples,),dtype='int64')
labels[0:1000]=0
labels[1000:]=1
names = ['happy' , 'not happy']

Y = np_utils.to_categorical(labels, num_classes)

x,y = shuffle(img_data,Y, random_state=2)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.BatchNormalization(input_shape=(224,224,3)))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D())

model.add(tf.keras.layers.Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu', name='fc1'))
model.add(tf.keras.layers.Dense(128, activation='relu', name='fc2'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax', name='output'))
model.summary()

Training the model

import os
tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    model,
    strategy=tf.contrib.tpu.TPUDistributionStrategy(
        tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
    )
)
tpu_model.compile(
    optimizer=tf.train.AdamOptimizer(learning_rate=1e-3, ),
    loss=tf.keras.losses.sparse_categorical_crossentropy,
    metrics=['sparse_categorical_accuracy']
)

def train_gen(batch_size):
  while True:
    offset = np.random.randint(0, x_train.shape[0] - batch_size)
    yield x_train[offset:offset+batch_size], y_train[offset:offset + batch_size]

tpu_model.fit_generator(
    train_gen(1024),
    epochs=10,
    steps_per_epoch=100,
    verbose = 1,
    validation_data=(x_test, y_test),
)

Expected results :

Array with probabilities of each label.

Actual results :

ValueErrorTraceback (most recent call last)
<ipython-input-37-bffa1e87ffe0> in <module>()
     24     steps_per_epoch=100,
     25     verbose = 1,
---> 26     validation_data=(x_test, y_test),
     27 )
ValueError: Error when checking target: expected output to have shape (1,) but got array with shape (2,)


问:
How loss in RNN/LSTM is calculated?
I'm learing how LSTM works by practicing with time series training data(input is a list of features and output is a scalar).
There is a problem that i couldnt understand when calculating loss for RNN/LSTM:

How loss is calculated? Is it calculated at each time i give the nn new input or acummulated through all the given inputs and then be backprop

答:
@seed Answer is correct. However, in LSTM, or any RNN architecture, the loss for each instance, across all time steps, is added up. In other words, you'll have (L0@t0, L1@t1, ... LT@tT) for each sample in your input batch. Add those losses separately for each instance in the batch. Finally average the losses of each input instance to get the average loss for a current batch

For more information please visit: https://stanford.edu/~shervine/teaching/cs-230/cheatsheet-recurrent-neural-networks

Title: How loss in RNN/LSTM is calculated?