问:
Job name "..getProjectMetadata" does not exist
I updated my angular to v9 and when I try to go back in v8, I receive this error.
I have already tried the following:

uninstall -global angular/cli

uninstall angular/cli

go back to my last package.json

delete node_module folder

delete repo

This error continues to show.

My stacktrace is :

```<code>An unhandled exception occurred: Job name "..getProjectMetadata" does not exist.
See angular-errors.log for further details.
</code>```

angular-errors.log :

```<code>[error] Error: Job name "..getProjectMetadata" does not exist.
    at Observable._subscribe (/Front/node_modules/@angular-devkit/core/src/experimental/jobs/simple-scheduler.js:350:23)
    at Observable._trySubscribe (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:44:25)
    at Observable.subscribe (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:30:22)
    at /Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:22:31
    at Object.subscribeToResult (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
    at SwitchMapSubscriber._innerSub (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
    at SwitchMapSubscriber._next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
    at SwitchMapSubscriber.Subscriber.next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
    at SwitchMapSubscriber.notifyNext (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:86:26)
    at InnerSubscriber._next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:28:21)
    at InnerSubscriber.Subscriber.next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
    at /Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:17:28
    at Object.subscribeToResult (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
    at SwitchMapSubscriber._innerSub (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
    at SwitchMapSubscriber._next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
    at SwitchMapSubscriber.Subscriber.next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
</code>```

ng --version :

```<code>Angular CLI: 8.3.18
Node: 12.15.0
OS: darwin x64
Angular: 8.2.13
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.18
@angular-devkit/build-angular     0.900.1
@angular-devkit/build-optimizer   0.900.1
@angular-devkit/build-webpack     0.900.1
@angular-devkit/core              8.3.18
@angular-devkit/schematics        8.3.18
@angular/cdk                      8.2.3
@angular/cli                      8.3.18
@angular/material                 8.2.3
@ngtools/webpack                  9.0.1
@schematics/angular               8.3.18
@schematics/update                0.803.18
rxjs                              6.5.3
typescript                        3.5.3
webpack                           4.41.2
</code>```

答:
From my experience a new module that you are using is designed for angular9 and you should upgrade your imports if possible to:</p>

```<code> "dependencies": {
    "@angular/animations": "^9.1.9",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "^9.1.9",
    "@angular/compiler": "^9.1.9",
    "@angular/core": "^9.1.9",
    "@angular/forms": "^9.1.9",
    "@angular/platform-browser": "^9.1.9",
    "@angular/platform-browser-dynamic": "^9.1.9",
    "@angular/router": "^9.1.9",
 ...
}
"devDependencies": {
    "@angular-devkit/build-angular": "^0.901.7",
    "@angular/cli": "^9.1.7",
    "@angular/compiler-cli": "^9.1.9",
    "@angular/language-service": "^9.1.9",
   ...
}
</code>```

Body:
I updated my angular to v9 and when I try to go back in v8, I receive this error.
I have already tried the following:

uninstall -global angular/cli

uninstall angular/cli

go back to my last package.json

delete node_module folder

delete repo

This error continues to show.

My stacktrace is :

An unhandled exception occurred: Job name "..getProjectMetadata" does not exist.
See angular-errors.log for further details.

angular-errors.log :

[error] Error: Job name "..getProjectMetadata" does not exist.
    at Observable._subscribe (/Front/node_modules/@angular-devkit/core/src/experimental/jobs/simple-scheduler.js:350:23)
    at Observable._trySubscribe (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:44:25)
    at Observable.subscribe (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:30:22)
    at /Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:22:31
    at Object.subscribeToResult (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
    at SwitchMapSubscriber._innerSub (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
    at SwitchMapSubscriber._next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
    at SwitchMapSubscriber.Subscriber.next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
    at SwitchMapSubscriber.notifyNext (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:86:26)
    at InnerSubscriber._next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:28:21)
    at InnerSubscriber.Subscriber.next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
    at /Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:17:28
    at Object.subscribeToResult (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
    at SwitchMapSubscriber._innerSub (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
    at SwitchMapSubscriber._next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
    at SwitchMapSubscriber.Subscriber.next (/Front/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)

ng --version :

Angular CLI: 8.3.18
Node: 12.15.0
OS: darwin x64
Angular: 8.2.13
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.18
@angular-devkit/build-angular     0.900.1
@angular-devkit/build-optimizer   0.900.1
@angular-devkit/build-webpack     0.900.1
@angular-devkit/core              8.3.18
@angular-devkit/schematics        8.3.18
@angular/cdk                      8.2.3
@angular/cli                      8.3.18
@angular/material                 8.2.3
@ngtools/webpack                  9.0.1
@schematics/angular               8.3.18
@schematics/update                0.803.18
rxjs                              6.5.3
typescript                        3.5.3
webpack                           4.41.2

Body:
From my experience a new module that you are using is designed for angular9 and you should upgrade your imports if possible to:

 "dependencies": {
    "@angular/animations": "^9.1.9",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "^9.1.9",
    "@angular/compiler": "^9.1.9",
    "@angular/core": "^9.1.9",
    "@angular/forms": "^9.1.9",
    "@angular/platform-browser": "^9.1.9",
    "@angular/platform-browser-dynamic": "^9.1.9",
    "@angular/router": "^9.1.9",
 ...
}
"devDependencies": {
    "@angular-devkit/build-angular": "^0.901.7",
    "@angular/cli": "^9.1.7",
    "@angular/compiler-cli": "^9.1.9",
    "@angular/language-service": "^9.1.9",
   ...
}


来源: stackexchange

问:
Working with branches in bitbucket and sourcetree
I am pretty new to using advanced features in Git, and am wondering if   someone can help me understand branches a little better. I have created two branches in Bitbucket named live and dev. What I am trying to do is push changes to dev, and only update the live branch when I push to it. How can I accomplish this?</p>

答:
You should think git like a tree. A branch represents independent line of development.

So, branches actually encapsulates your changes. For example, when you want to add a new feature to the code, you create a new branch and push commit to the new branch.

Working with branches makes master branch is clean and unreviewed code (questionable code maybe?). It also makes harder to merge unwanted code to the master branch.

ContentLicense: CC BY-SA 4.0


问:
Difference between Single Responsibility Principle and Separation of Concerns
What is the difference between Single Responsibility Principle and Separation of Concerns?</p>

答:
Separation of Concerns

The Separation of Concerns (SOC) principle states that a code artifact should allow one to focus one's attention upon a certain aspect. A code artifact can be anything, from a specific function, to a class, or a whole package, or even an entire application. The SOC principle can be applied to every architectural level in one's applications. An example of an architecture where SOC is applied is a layered architecture.

Single Responsibility Principle

The Single Responsibility Principle (SRP) states that "A module should have one, and only one, reason to change" (Clean Architecture, Martin, p. 62). The SRP applies to the module level and when applying the SRP one should be focused on the reason to change.

Conclusion

The SOC principle states that a code artifact should allow one to focus one's attention upon a certain aspect. The SRP makes this concrete by stating that at the module level we should focus our attention at the reason of change. Thus the SRP is a SOC.

P.S. For completeness: the Common Closure Principle

The Common Closure Principle (CCP) is a restatement of the SRP at an even higher level, the component level. The CCP states that classes that change for the same reasons and at the same times should be gathered into the same components (Clean Architecture, p. 105). The CCP is another example of a SOC.

ContentLicense: CC BY-SA 2.5


问:
How can I automatically generate a new input area when user started to enter text?
I want to generate input dynamically. Searched almost all samples and they generate inputs with button clicks. It is ok but i need something different. When user started to type in input then i want to create second input and when user typed to second then create third input like this..

My problem is when user typed inputs then it creates many inputs (letter counts=inputs). I must solve this issue immediately . I tried to some tricks but they could not work . Thanks for helping . You can check it in Codepen .

```<code>  <div class="container1">
      <button class="add_form_field">
        Add New Field
        <span style="font-size: 16px; font-weight: bold;">+ </span>
      </button>
      <div class="divInput firstChild">
        <input type="text" autocomplete="off" name="mytext[]" />
      </div>
    </div>
</code>```

```<code> $(document).ready(function () {
        var max_fields = 10;
        var wrapper = $(".container1");
        var add_button = $(".add_form_field");

        var inputs = document.querySelectorAll(".divInput");
        let xs = [];
        var x = 1;
        $(add_button).click(function (e) {
          e.preventDefault();
          if (x < max_fields) {
            x++;

            $(wrapper).append(
              '<div class="divInput"><input type="text" autocomplete="off" name="mytext[]"/><a href="#" class="delete"></a></div>'
            ); //add input box
          } else {
            alert("You Reached the limits");
          }
        });

        $(wrapper).on("keyup", "input", function (e) {
          e.preventDefault();

          if ($(this).val() == "") {
            //when user cleaned input then delete it
            $(this).parent("div").remove();
            x--;
            return;
          } else if ($(this).val() != "") {
            //dont use click check if length>0 then use this trick to add new input
            $(add_button).trigger("click");
            return;
          }

          if (x == 0) {
            //if user tries to delete last input then create a new one
            console.log("xx", x);
            $(wrapper).append(
              '<div class="divInput"><input type="text" autocomplete="off" name="mytext[]"/><a href="#" class="delete"></a></div>'
            ); //add input box
            x = 1;
            console.log("xx", x);
            return;
          }
        });
      });

</code>```

https://codepen.io/otontas11/pen/BaogrZR

答:
I know this is mostly an opinion, but IMO you shouldn't mix jQuery with react, they use fairly orthogonal ways to accomplish UI manipulation.

Here is a way I accomplished this design

```<code>const createInitialState = initialValues =>
  initialValues.map(value => ({ id: uuidv4(), value })); // id used internally

const createOnChangeValues = values => values.map(({ value }) => value);

const InputList = ({ defaultValues = [], onChange }) => {
  const renderRef = useRef(null);
  const inputRef = useRef(null);
  const [values, setValues] = useState(createInitialState(defaultValues));
  const [inputFocused, setInputFocused] = useState(false);
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    if (renderRef.current) {
      onChange && onChange(createOnChangeValues(values));
    }
    renderRef.current = true;
  }, [onChange, values]);

  const addValue = value => {
    if (value) {
      setValues(values => [...values, { id: uuidv4(), value }]);
      setInputValue("");
    }
  };

  const updateValue = index => e => {
    const updateValue = e.target.value;
    if (updateValue) {
      setValues(values =>
        values.map(({ id, value }, i) => ({
          id,
          value: index === i ? updateValue : value
        }))
      );
    } else {
      setValues(values => values.filter((_, i) => i !== index));
    }
  };

  useEffect(() => {
    if (!inputFocused && inputValue) {
      addValue(inputValue);
      inputRef.current.focus();
    }
  }, [inputFocused, inputValue]);

  const submitHandler = e => {
    e.preventDefault();
    addValue(inputValue);
  };

  const resetHandler = e => {
    e.preventDefault();
    setInputValue("");
  };

  return (
    <Fragment>
      <form id="inputForm" onReset={resetHandler} onSubmit={submitHandler} />

      {values.map(({ id, value }, i) => (
        <div key={id}>
          <input value={value} onChange={updateValue(i)} />
        </div>
      ))}

      <div>
        <input
          form="inputForm"
          ref={inputRef}
          type="text"
          value={inputValue}
          onFocus={() => setInputFocused(true)}
          onBlur={() => setInputFocused(false)}
          onChange={e => setInputValue(e.target.value)}
        />
      </div>

      {inputValue && (
        <div>
          <input />
        </div>
      )}
    </Fragment>
  );
};
</code>```

The gist is you have some array of inputs currently being used, and you always render an extra blank input. As soon as user starts filling the new blank input it becomes part of the array of inputs upon losing focus. If any input becomes blank it is removed from the array. Much of the logic is to manage the swap from the new/empty input to one in the array and keep focus.

Usage

```<code><InputList defaultValues={[... input values from state]} onChange={... values from inputs in array} />
</code>```

Body:
I want to generate input dynamically. Searched almost all samples and they generate inputs with button clicks. It is ok but i need something different. When user started to type in input then i want to create second input and when user typed to second then create third input like this..

My problem is when user typed inputs then it creates many inputs (letter counts=inputs). I must solve this issue immediately . I tried to some tricks but they could not work . Thanks for helping . You can check it in Codepen .

      <button class="add_form_field">
        Add New Field
        +
      </button>

        <input type="text" autocomplete="off" name="mytext[]" />

 $(document).ready(function () {
        var max_fields = 10;
        var wrapper = $(".container1");
        var add_button = $(".add_form_field");

        var inputs = document.querySelectorAll(".divInput");
        let xs = [];
        var x = 1;
        $(add_button).click(function (e) {
          e.preventDefault();
          if (x < max_fields) {
            x++;

            $(wrapper).append(
              '
<input type="text" autocomplete="off" name="mytext[]"/>
'
            ); //add input box
          } else {
            alert("You Reached the limits");
          }
        });

        $(wrapper).on("keyup", "input", function (e) {
          e.preventDefault();

          if ($(this).val() == "") {
            //when user cleaned input then delete it
            $(this).parent("div").remove();
            x--;
            return;
          } else if ($(this).val() != "") {
            //dont use click check if length>0 then use this trick to add new input
            $(add_button).trigger("click");
            return;
          }

          if (x == 0) {
            //if user tries to delete last input then create a new one
            console.log("xx", x);
            $(wrapper).append(
              '
<input type="text" autocomplete="off" name="mytext[]"/>
'
            ); //add input box
            x = 1;
            console.log("xx", x);
            return;
          }
        });
      });

https://codepen.io/otontas11/pen/BaogrZR

Body:
I know this is mostly an opinion, but IMO you shouldn't mix jQuery with react, they use fairly orthogonal ways to accomplish UI manipulation.

Here is a way I accomplished this design

const createInitialState = initialValues =>
  initialValues.map(value => ({ id: uuidv4(), value })); // id used internally

const createOnChangeValues = values => values.map(({ value }) => value);

const InputList = ({ defaultValues = [], onChange }) => {
  const renderRef = useRef(null);
  const inputRef = useRef(null);
  const [values, setValues] = useState(createInitialState(defaultValues));
  const [inputFocused, setInputFocused] = useState(false);
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    if (renderRef.current) {
      onChange && onChange(createOnChangeValues(values));
    }
    renderRef.current = true;
  }, [onChange, values]);

  const addValue = value => {
    if (value) {
      setValues(values => [...values, { id: uuidv4(), value }]);
      setInputValue("");
    }
  };

  const updateValue = index => e => {
    const updateValue = e.target.value;
    if (updateValue) {
      setValues(values =>
        values.map(({ id, value }, i) => ({
          id,
          value: index === i ? updateValue : value
        }))
      );
    } else {
      setValues(values => values.filter((_, i) => i !== index));
    }
  };

  useEffect(() => {
    if (!inputFocused && inputValue) {
      addValue(inputValue);
      inputRef.current.focus();
    }
  }, [inputFocused, inputValue]);

  const submitHandler = e => {
    e.preventDefault();
    addValue(inputValue);
  };

  const resetHandler = e => {
    e.preventDefault();
    setInputValue("");
  };

  return (
    <Fragment>
      <form id="inputForm" onReset={resetHandler} onSubmit={submitHandler} />

      {values.map(({ id, value }, i) => (
        <div key={id}>
          <input value={value} onChange={updateValue(i)} />
        </div>
      ))}

      <div>
        <input
          form="inputForm"
          ref={inputRef}
          type="text"
          value={inputValue}
          onFocus={() => setInputFocused(true)}
          onBlur={() => setInputFocused(false)}
          onChange={e => setInputValue(e.target.value)}
        />
      </div>

      {inputValue && (
        <div>
          <input />
        </div>
      )}
    </Fragment>
  );
};

The gist is you have some array of inputs currently being used, and you always render an extra blank input. As soon as user starts filling the new blank input it becomes part of the array of inputs upon losing focus. If any input becomes blank it is removed from the array. Much of the logic is to manage the swap from the new/empty input to one in the array and keep focus.

Usage

<InputList defaultValues={[... input values from state]} onChange={... values from inputs in array} />


问:
Delete Google Analytics filter with Google App Scripts (delete not a function error)
I'm want to delete Google Analytics filters at view level using Google App Script and Google Analytics management API.

I'm trying to run the following function:

```<code>function delete_filter() {

var delete = Analytics.Management.ProfileFilterLinks.delete('213755:84538578', '123456','12345678','UA-12345678-1');

}
</code>```

but I have the following error:

```<code>TypeError: Analytics.Management.ProfileFilterLinks.delete is not a function
</code>```

Does it means that the delete function is not available with Google App Script API?

答:
How about this modification? At the official document, the "Profile Filter Links: delete" method is used. But at Advanced Google services, it seems that remove is used. I think that the reason of your error message is due to this. So please modify as follows and testing it again.

From:

```<code>var delete = Analytics.Management.ProfileFilterLinks.delete('213755:84538578', '123456','12345678','UA-12345678-1');
</code>```

To:

```<code>var delete = Analytics.Management.ProfileFilterLinks.remove(accountId, webPropertyId, profileId, linkId);
</code>```

Note:

In this case, the returned value is void. Please be careful this.

Please confirm whether the values of accountId, webPropertyId, profileId, linkId are correct.

Reference:

Profile Filter Links: delete

Body:
I'm want to delete Google Analytics filters at view level using Google App Script and Google Analytics management API.

I'm trying to run the following function:

function delete_filter() {

var delete = Analytics.Management.ProfileFilterLinks.delete('213755:84538578', '123456','12345678','UA-12345678-1');

}

but I have the following error:

TypeError: Analytics.Management.ProfileFilterLinks.delete is not a function

Does it means that the delete function is not available with Google App Script API?

Body:
How about this modification? At the official document, the "Profile Filter Links: delete" method is used. But at Advanced Google services, it seems that remove is used. I think that the reason of your error message is due to this. So please modify as follows and testing it again.

From:

var delete = Analytics.Management.ProfileFilterLinks.delete('213755:84538578', '123456','12345678','UA-12345678-1');

To:

var delete = Analytics.Management.ProfileFilterLinks.remove(accountId, webPropertyId, profileId, linkId);

Note:

In this case, the returned value is void. Please be careful this.

Please confirm whether the values of accountId, webPropertyId, profileId, linkId are correct.

Reference:

Profile Filter Links: delete


问:
Discord.py on_message() but only for private messages
So, I'm working on a discord bot. And am using the on_message() event, which works both on private messages and on servers. I want this to only work in private messages and am unsure of how to go about this.
If anyone can help me, that would be great.</p>
```<code>import os
import discord
from discord.ext import commands

TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))

@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)

client.run(TOKEN)
</code>```

答:
When a DM is received, it won't have a guild, so you'll be able to use that logic like so:

@client.event
async def on_message(message):
    # you'll need this because you're also using cmd decorators
    await client.process_commands(message)
    if not message.guild:
        await message.author.send(f"Received: {message.content}")
```

References:

Bot.process_commands()

Message.guild - it mentions "if applicable", meaning that it'll return None if it's not in a guild, and rather a DM

f-Strings - Python 3.6+

Body:
So, I'm working on a discord bot. And am using the on_message() event, which works both on private messages and on servers. I want this to only work in private messages and am unsure of how to go about this.
If anyone can help me, that would be great.

import os
import discord
from discord.ext import commands

TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))

@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)

client.run(TOKEN)

Body:
When a DM is received, it won't have a guild, so you'll be able to use that logic like so:

@client.event
async def on_message(message):
    # you'll need this because you're also using cmd decorators
    await client.process_commands(message)
    if not message.guild:
        await message.author.send(f"Received: {message.content}")

References:

Bot.process_commands()

Message.guild - it mentions "if applicable", meaning that it'll return None if it's not in a guild, and rather a DM

f-Strings - Python 3.6+


问:
Implementing getAuthToken in AccountManager using coroutines
I am having a problem implementing getAuthToken.

```<code>   override fun getAuthToken(
        response: AccountAuthenticatorResponse,
        account: Account,
        authTokenType: String,
        options: Bundle
    ): Bundle? {
        val password = AccountManager.get(context).getPassword(account)
        val scope = CoroutineScope(Dispatchers.IO + Job())
        scope.launch {
            val user = getNetworkService().login(account.name, password)
            val token = Gson().toJson(user)
            // ERROR: return is not allowed here
            return Bundle().apply {
                putString(AccountManager.KEY_ACCOUNT_NAME, account.name)
                putString(AccountManager.KEY_ACCOUNT_TYPE, account.type)
                putString(AccountManager.KEY_AUTHTOKEN, token)
                Timber.i("Got auth token and bundle is $this")
            }
        }
    }
</code>```

When I launch the coroutine scope, I cannot return the token I get after the network call. There is an error, 'Return not allowed here'. How can I correctly return the authToken?

答:
The solution I came up with was to perform the asynchronous login request outside getAuthToken.

In getAuthToken all I do is to fetch the existing token else return null.

```<code>    // This method runs whenever the authToken is invalid or null
    // The first time it runs is after you add an account to accountManager
    // Use this method to fetch the token from the network/server and return it in a bundle
    // Do not call accountManager.setAuthToken(token) directly in the application
    override fun getAuthToken(
        response: AccountAuthenticatorResponse,
        account: Account,
        authTokenType: String,
        options: Bundle
    ): Bundle? {
        val authToken: String? = AccountManager.get(context).peekAuthToken(account, accountType)
        return authToken?.let { token ->
            Bundle().apply {
                putString(AccountManager.KEY_ACCOUNT_NAME, account.name)
                putString(AccountManager.KEY_ACCOUNT_TYPE, account.type)
                putString(AccountManager.KEY_AUTHTOKEN, token)
                Timber.i("Got auth token, bundle is $this")
            }
        }
    }
</code>```

I had to neglect all the comments above the method.

I then set the authToken directly from register and login fragments.

This is the extension function for adding an account.

```<code>fun Fragment.addAccount(email: String, password: String, token: String) {
    val am = AccountManager.get(activity)
    val account = Account(email, getAccountType())
    am.addAccountExplicitly(account, password, null)
    am.setAuthToken(account, accountType, token)
    am.setUserData(account, userData, token)
}
</code>```

Body:
I am having a problem implementing getAuthToken.

   override fun getAuthToken(
        response: AccountAuthenticatorResponse,
        account: Account,
        authTokenType: String,
        options: Bundle
    ): Bundle? {
        val password = AccountManager.get(context).getPassword(account)
        val scope = CoroutineScope(Dispatchers.IO + Job())
        scope.launch {
            val user = getNetworkService().login(account.name, password)
            val token = Gson().toJson(user)
            // ERROR: return is not allowed here
            return Bundle().apply {
                putString(AccountManager.KEY_ACCOUNT_NAME, account.name)
                putString(AccountManager.KEY_ACCOUNT_TYPE, account.type)
                putString(AccountManager.KEY_AUTHTOKEN, token)
                Timber.i("Got auth token and bundle is $this")
            }
        }
    }

When I launch the coroutine scope, I cannot return the token I get after the network call. There is an error, 'Return not allowed here'. How can I correctly return the authToken?

Body:
The solution I came up with was to perform the asynchronous login request outside getAuthToken.

In getAuthToken all I do is to fetch the existing token else return null.

    // This method runs whenever the authToken is invalid or null
    // The first time it runs is after you add an account to accountManager
    // Use this method to fetch the token from the network/server and return it in a bundle
    // Do not call accountManager.setAuthToken(token) directly in the application
    override fun getAuthToken(
        response: AccountAuthenticatorResponse,
        account: Account,
        authTokenType: String,
        options: Bundle
    ): Bundle? {
        val authToken: String? = AccountManager.get(context).peekAuthToken(account, accountType)
        return authToken?.let { token ->
            Bundle().apply {
                putString(AccountManager.KEY_ACCOUNT_NAME, account.name)
                putString(AccountManager.KEY_ACCOUNT_TYPE, account.type)
                putString(AccountManager.KEY_AUTHTOKEN, token)
                Timber.i("Got auth token, bundle is $this")
            }
        }
    }

I had to neglect all the comments above the method.

I then set the authToken directly from register and login fragments.

This is the extension function for adding an account.

fun Fragment.addAccount(email: String, password: String, token: String) {
    val am = AccountManager.get(activity)
    val account = Account(email, getAccountType())
    am.addAccountExplicitly(account, password, null)
    am.setAuthToken(account, accountType, token)
    am.setUserData(account, userData, token)
}


问:
Efficiently deleting rows from one table where not matching another [MySQL]
So, I have two tables, users and points. A lot of users no longer have points (literally and by table) -- so I wish to delete them. I try and achieve this by doing this, but it basically times out (about one hundred thousand rows in both tables). I'm doing select rather than delete because I want to verify the data before issuing the same query as a delete:

```<code>SELECT WWW t1
FROM users t1
JOIN points t2 ON t1.id != t2.user_id;
</code>```

Both tables have an ID that matches each other. If a user has a point, there will be a matching ID. If there is no longer a point for that user, there is no matching ID. Therefor, != therorhetically should delete all the no longer needed users.

How can I do this without timing out my database?

答:
I would recommend not exists:

```<code>delete from users
where not exists (select 1 from points p where p.user_id = users.id)
</code>```

This should be an efficient option, if you have the right index in place, that is: points(user_id).

On the other hand, if you are deleting a great proportion of the table, it might be simpler to move that rows that you want to keep to a temporary table, then truncate and recreate the table:

```<code>create table tmp_users as
select u.*
from users
where exists(select 1 from points p where p.user_id = u.id)

truncate table users;  -- back it up first!

insert into users select * from tmp_users;

drop table tmp_users;
</code>```

Body:
So, I have two tables, users and points. A lot of users no longer have points (literally and by table) -- so I wish to delete them. I try and achieve this by doing this, but it basically times out (about one hundred thousand rows in both tables). I'm doing select rather than delete because I want to verify the data before issuing the same query as a delete:

SELECT WWW t1
FROM users t1
JOIN points t2 ON t1.id != t2.user_id;

Both tables have an ID that matches each other. If a user has a point, there will be a matching ID. If there is no longer a point for that user, there is no matching ID. Therefor, != therorhetically should delete all the no longer needed users.

How can I do this without timing out my database?

Body:
I would recommend not exists:

delete from users
where not exists (select 1 from points p where p.user_id = users.id)

This should be an efficient option, if you have the right index in place, that is: points(user_id).

On the other hand, if you are deleting a great proportion of the table, it might be simpler to move that rows that you want to keep to a temporary table, then truncate and recreate the table:

create table tmp_users as
select u.*
from users
where exists(select 1 from points p where p.user_id = u.id)

truncate table users;  -- back it up first!

insert into users select * from tmp_users;

drop table tmp_users;


问:
Lodash create object from array of arrays
I would like to use lodash to generete object from array of arrays. I use for it lodash.zipObject method and map. But it is not 1:1 what I would like to generate:

Input:

```<code> "rows": [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ]

dictionary: ['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll' ], [action.yearReportData]
</code>```

output:

```<code>{
  source: ['stravi/aa', 'stravi/ab', 'stravi/ac'],
  sessions: ['202001', '202003', '202007']
  ...
}
</code>```

I would like to use lodash, and I try by:

```<code>   lodash.map(rows, arr =>
                lodash.zipObject(['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll'], arr))
</code>```

But is not correct... I received multiple object. I would like to have one object with all data. Like my example.

答:
You need a reducer instead of map. Map just transform each elements that is why you get multiple elements.

I would use plain JS for this one. It will look like this:

```<code>const rows = [
  [
    'stravi/aa',
    '202001',
    '59',
    '51',
    '2558.98',
    '0.5358894453719162',
    '1.9204668112983725',
    '140',
    '2.3466309084813943',
  ],
  [
    'stravi/ab',
    '202003',
    '3591',
    '349',
    '2246.09',
    '0.41838214',
    '3.57603358',
    '50',
    '4.82115474',
  ],
  [
    'stravi/ac',
    '202007',
    '3354',
    '25',
    '1975.76',
    '0.74220667708',
    '1.12321555541',
    '11',
    '0.9324532454',
  ],
];

const keys = [
  'source',
  'sessions',
  'adClicks',
  'adCost',
  'CPC',
  'CTR',
  'goalCompletionsAll',
  'goalConversionRateAll',
  'missingFieldName',
];

const initialAcc = keys.reduce((acc, cur) => {
  acc[cur] = [];
  return acc;
}, {});

const resultAcc = rows.reduce((acc, cur) => {
  cur.forEach((value, index) => acc[keys[index]].push(value));
  return acc;
}, initialAcc);

console.log(resultAcc);
</code>```

Body:
I would like to use lodash to generete object from array of arrays. I use for it lodash.zipObject method and map. But it is not 1:1 what I would like to generate:

Input:

 "rows": [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ]

dictionary: ['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll' ], [action.yearReportData]

output:

{
  source: ['stravi/aa', 'stravi/ab', 'stravi/ac'],
  sessions: ['202001', '202003', '202007']
  ...
}

I would like to use lodash, and I try by:

   lodash.map(rows, arr =>
                lodash.zipObject(['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll'], arr))

But is not correct... I received multiple object. I would like to have one object with all data. Like my example.

Body:
You need a reducer instead of map. Map just transform each elements that is why you get multiple elements.

I would use plain JS for this one. It will look like this:

const rows = [
  [
    'stravi/aa',
    '202001',
    '59',
    '51',
    '2558.98',
    '0.5358894453719162',
    '1.9204668112983725',
    '140',
    '2.3466309084813943',
  ],
  [
    'stravi/ab',
    '202003',
    '3591',
    '349',
    '2246.09',
    '0.41838214',
    '3.57603358',
    '50',
    '4.82115474',
  ],
  [
    'stravi/ac',
    '202007',
    '3354',
    '25',
    '1975.76',
    '0.74220667708',
    '1.12321555541',
    '11',
    '0.9324532454',
  ],
];

const keys = [
  'source',
  'sessions',
  'adClicks',
  'adCost',
  'CPC',
  'CTR',
  'goalCompletionsAll',
  'goalConversionRateAll',
  'missingFieldName',
];

const initialAcc = keys.reduce((acc, cur) => {
  acc[cur] = [];
  return acc;
}, {});

const resultAcc = rows.reduce((acc, cur) => {
  cur.forEach((value, index) => acc[keys[index]].push(value));
  return acc;
}, initialAcc);

console.log(resultAcc);


问:
R expss use_labels and dplyr logic
I trying to get expss use_labels to work with dplyr logic - see example below.

The vignette states the following under use_labels.
By now variable labels support available only for expressions which will be evaluated inside data.frame.
Is this the issue I'm having here?

#

```<code>##########################################
library(expss)
library(tidyverse)
data(mtcars)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)

# table with caption from label - labels working
cro_cpct(mtcars$am, mtcars$vs) %>% set_caption(var_lab(mtcars$am))

## This works as expected - now to get this with expss use_labels.
mtcars %>%
 group_by(am) %>%
  summarise(
   freq = n()
)
#######
#am             freq
#<labelled>    <int>
# 1 0             19
# 2 1             13
########################

#### This doesn't work - i.e. not labelled
use_labels(mtcars %>%
  group_by(am) %>%
   summarise(
    freq = n()
))
## Error in substitute_symbols(expr, c(substitution_list, list(..data = quote(expss::vars(other))))) :
  # argument "expr" is missing, with no default
</code>```

If labels can't be used with dplyr logic does anyone know another package that can do labels with dplyr?
Regards

答:
Package foreign does keep the value labels. Haven does not, or at least not by default and I can't figure out how to make it happen. You can confirm this by inspecting str() of the imported data. If you don't see the labels in there somewhere, they didn't get imported. Here I'm importing a Stata data set with value labels for union and female, both of which are 0/1 underlying. The cro_cpct command uses the value labels, but not the variable labels, when imported with package foreign (read.dta). When imported with package haven (read_dta), cro_cpct uses the variable labels but not the value labels.

```<code>    library(expss)
    library(tidyverse)
    library(foreign)
    wages <- read.dta("c:/users/pjargowsky/documents/course/qm2/wages.dta")
    cro_cpct(wages$female, wages$union) %>% set_caption(var_lab(wages$female))

#
# |              |              | wages$union |      |
# |              |              |          no |  yes |
# | ------------ | ------------ | ----------- | ---- |
# | wages$female |         male |        50.5 | 70.8 |
# |              |       female |        49.5 | 29.2 |
# |              | #Total cases |       438.0 | 96.0 |

library(haven)
wages <- read_dta("c:/users/pjargowsky/documents/course/qm2/wages.dta")
cro_cpct(wages$female, wages$union) %>% set_caption(var_lab(wages$female))

# Gender
# |        |              | Union Membership |      |
# |        |              |                0 |    1 |
# | ------ | ------------ | ---------------- | ---- |
# | Gender |            0 |             50.5 | 70.8 |
# |        |            1 |             49.5 | 29.2 |
# |        | #Total cases |            438.0 | 96.0 |
</code>```

Title: R expss use_labels and dplyr logic

Body:
I trying to get expss use_labels to work with dplyr logic - see example below.

The vignette states the following under use_labels.
By now variable labels support available only for expressions which will be evaluated inside data.frame.
Is this the issue I'm having here?

#

##########################################
library(expss)
library(tidyverse)
data(mtcars)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)

# table with caption from label - labels working
cro_cpct(mtcars$am, mtcars$vs) %>% set_caption(var_lab(mtcars$am))

## This works as expected - now to get this with expss use_labels.
mtcars %>%
 group_by(am) %>%
  summarise(
   freq = n()
)
#######
#am             freq
#<labelled>    <int>
# 1 0             19
# 2 1             13
########################

#### This doesn't work - i.e. not labelled
use_labels(mtcars %>%
  group_by(am) %>%
   summarise(
    freq = n()
))
## Error in substitute_symbols(expr, c(substitution_list, list(..data = quote(expss::vars(other))))) :
  # argument "expr" is missing, with no default

If labels can't be used with dplyr logic does anyone know another package that can do labels with dplyr?
Regards

Body:
Package foreign does keep the value labels. Haven does not, or at least not by default and I can't figure out how to make it happen. You can confirm this by inspecting str() of the imported data. If you don't see the labels in there somewhere, they didn't get imported. Here I'm importing a Stata data set with value labels for union and female, both of which are 0/1 underlying. The cro_cpct command uses the value labels, but not the variable labels, when imported with package foreign (read.dta). When imported with package haven (read_dta), cro_cpct uses the variable labels but not the value labels.

    library(expss)
    library(tidyverse)
    library(foreign)
    wages <- read.dta("c:/users/pjargowsky/documents/course/qm2/wages.dta")
    cro_cpct(wages$female, wages$union) %>% set_caption(var_lab(wages$female))

#
# |              |              | wages$union |      |
# |              |              |          no |  yes |
# | ------------ | ------------ | ----------- | ---- |
# | wages$female |         male |        50.5 | 70.8 |
# |              |       female |        49.5 | 29.2 |
# |              | #Total cases |       438.0 | 96.0 |

library(haven)
wages <- read_dta("c:/users/pjargowsky/documents/course/qm2/wages.dta")
cro_cpct(wages$female, wages$union) %>% set_caption(var_lab(wages$female))

# Gender
# |        |              | Union Membership |      |
# |        |              |                0 |    1 |
# | ------ | ------------ | ---------------- | ---- |
# | Gender |            0 |             50.5 | 70.8 |
# |        |            1 |             49.5 | 29.2 |
# |        | #Total cases |            438.0 | 96.0 |


问:
psycopg2 Installation Problems
When I start my Django server, I get the following error:

```<code>Failed to get real commands on module "mysite": python process died with code 1: Traceback (most recent call last):
  File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module>
    import psycopg2 as Database
  File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\psycopg2\__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: DLL load failed while importing _psycopg: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2019.3.1\plugins\python\helpers\pycharm\_jb_manage_tasks_provider.py", line 25, in <module>
    django.setup()
  File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\django\__init__.py", line 24, in setup
</code>```

When I checked the psycopg2 directory after you installed the library, __init__.py contains from psycopg2._psycopg import .... But there is no _psycopg.dll file in the psycopg2 directory. Possible bug?

Part of my settings.py:

```<code>DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "database1",
        "USER": "postgres",
        "PASSWORD": "123456",
        "HOST": "127.0.0.1",
        "PORT": "5432"
    }
}
</code>```

Using:

Windows 10

PyCharm

Anaconda

Python 3.8.3

psycopg2 2.8.4

Django 3.0.3

PostgreSQL

答:
Okay, I finally got it to work.

I had to switch out of the Anaconda environment to a Virtualenv environment and install with Pip, maintaining the same set-up.

So the problem was either with how Anaconda handled psycopg2 or there was a problem with the library itself because the latest version of psycopg2 on Anaconda was older by 0.0.x

A small version difference, but it might've been missing a hotfix.

Title: psycopg2 Installation Problems

Body:
When I start my Django server, I get the following error:

Failed to get real commands on module "mysite": python process died with code 1: Traceback (most recent call last):
  File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module>
    import psycopg2 as Database
  File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\psycopg2\__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: DLL load failed while importing _psycopg: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2019.3.1\plugins\python\helpers\pycharm\_jb_manage_tasks_provider.py", line 25, in <module>
    django.setup()
  File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\django\__init__.py", line 24, in setup

When I checked the psycopg2 directory after you installed the library, __init__.py contains from psycopg2._psycopg import .... But there is no _psycopg.dll file in the psycopg2 directory. Possible bug?

Part of my settings.py:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "database1",
        "USER": "postgres",
        "PASSWORD": "123456",
        "HOST": "127.0.0.1",
        "PORT": "5432"
    }
}

Using:

Windows 10

PyCharm

Anaconda

Python 3.8.3

psycopg2 2.8.4

Django 3.0.3

PostgreSQL


问:
onchange="javascript: document.my_form.submit()" vs. normal submit
I have a select field within a form:

```<code><form id="myform">
<select id="value" onchange="javascript: document.myform.submit()">
    <option>....
</select>
</form>
</code>```

After the form is submitted, it is impossible to use the 'back' button without resubmitting the form.  However, if I use a regular 'submit' button, it is possible.

Is there a way you know of to get this behavior while still being able to use the javascript 'submit()'?

Accessibility is not a concern, having javascript enabled is required to use this site and that is the way the client wants it.

答:
"onchange only works first time?"

Are you re-selecting the same value? onchange only fires when there is a change. If you want to be able to reselect the same option, you need to use onblur.

Also you really should be using

```<code>document.getElementById("myform").submit();
</code>```

Body:
I have a select field within a form:

<form id="myform">
<select id="value" onchange="javascript: document.myform.submit()">
    <option>....
</select>
</form>

After the form is submitted, it is impossible to use the 'back' button without resubmitting the form.  However, if I use a regular 'submit' button, it is possible.

Is there a way you know of to get this behavior while still being able to use the javascript 'submit()'?

Accessibility is not a concern, having javascript enabled is required to use this site and that is the way the client wants it.

Body:
"onchange only works first time?"

Are you re-selecting the same value? onchange only fires when there is a change. If you want to be able to reselect the same option, you need to use onblur.

Also you really should be using

document.getElementById("myform").submit();

OwnerDisplayName: epascarello

ContentLicense: CC BY-SA 3.0


问:
Generate a plaintext file from list of words on a webpage
I am trying to generate a plain text file containing a list of words that is on a webpage. The problem is that the list is divided into multiple pages.

http://www.whonamedit.com/eponyms/A/?start=50&maxrows=25

This is what I mean. Like for the letter A, I need all 13 pages of words and I also need every letter of the alphabet.

I was thinking of maybe modifying a webcrawler to do this task, would that be the easiest way?

I prefer Java, but Python is ok.

Sorry if the answer is obvious, but any nudges in the right direction would be SO GREATLY appreciated!!

答: I use HtmlUnit to write spiders</p>

Body: I use HtmlUnit to write spiders


问:
Python compare two lists, add specific string to list if substring is in main list
I have a python bot which scrapes a website for data. Once it has the data it's filtered and the names are read clearly; this is list 1. Then, in list 2, I have strings of set names and I'm trying to compare list 2 to list 1 to see if list 1 contains one of any of the strings from list 2, and if it does, list 1 will have a string inserted into it showing that it contains a string from list 2. This is my loop:

```<code>for x in boss_bots:
    for index, y in enumerate(new_bots):
        if x in y[index]:
            new_bots.insert(index, 'Boss Bot')
</code>```

Here is the rest of the code

```<code>from selenium import webdriver
from time import sleep

boss_bots = ['Flunky', 'Pencil Pusher', 'Yesman', 'Micro manager', 'Downsizer', 'Head Hunter', 'Corporate Raider',
             'The Big Cheese']
cash_bots = ['Short Change', 'Penny Pincher', 'Tightwad', 'Bean Counter', 'Number Cruncher', 'Money Bags', 'Loan Shark',
             'Robber Baron']
sell_bots = ['Cold Caller', 'Telemarketer', 'Name Dropper', 'Glad Hander', 'Mover & Shaker', 'Two-Face', 'The Mingler',
             'Mr. Hollywood']
law_bots = ['Bottom Feeder', 'Blood sucker', 'Double Talker', 'Ambulance Chaser', 'Back Stabber', 'Spin Doctor',
            'Legal Eagle', 'Big Wig']

def format_box(bots):
    new_bots = []
    for string in bots:
        new_bot = string.replace('', ' ')
        new_bots.append(new_bot)
    return new_bots

def print_bots(bots):
    for i in bots:
        print(i)
        print()

def get_all_info():
    driver = webdriver.Chrome()
    driver.get("https://toonhq.org/invasions/")
    sleep(2)
    bots = driver.find_elements_by_class_name('media-body')
    info = [name.text for name in bots if name.text != '']
    new_bots = format_box(info)

    t = 0
    """    for index, (x, y) in enumerate(zip(boss_bots, info)):
        if x == y:
            new_bots.insert(index, 'Boss Bot')"""

    for x in boss_bots:
        for index, y in enumerate(new_bots):
            #print('Boss bots: ' + x + 'index: ' + str(index) + 'Bot list: ' + y)
            if x in y[index]:
                new_bots.insert(index, 'Boss Bot')

    print_bots(new_bots)
    driver.close()
    return info

get_all_info()
</code>```

答:
Hope I got your problem right. If you do want to replace list 1 items with 'Boss Bot' string if item in list one matches the items in list 2. For this, you can use list indexes

for i in range(len(new_bots)) :

         if(new_bots[i] in boss_bots) :
              new_bots[i] = 'Boss Bot'

Body:
I have a python bot which scrapes a website for data. Once it has the data it's filtered and the names are read clearly; this is list 1. Then, in list 2, I have strings of set names and I'm trying to compare list 2 to list 1 to see if list 1 contains one of any of the strings from list 2, and if it does, list 1 will have a string inserted into it showing that it contains a string from list 2. This is my loop:

for x in boss_bots:
    for index, y in enumerate(new_bots):
        if x in y[index]:
            new_bots.insert(index, 'Boss Bot')

Here is the rest of the code

from selenium import webdriver
from time import sleep

boss_bots = ['Flunky', 'Pencil Pusher', 'Yesman', 'Micro manager', 'Downsizer', 'Head Hunter', 'Corporate Raider',
             'The Big Cheese']
cash_bots = ['Short Change', 'Penny Pincher', 'Tightwad', 'Bean Counter', 'Number Cruncher', 'Money Bags', 'Loan Shark',
             'Robber Baron']
sell_bots = ['Cold Caller', 'Telemarketer', 'Name Dropper', 'Glad Hander', 'Mover & Shaker', 'Two-Face', 'The Mingler',
             'Mr. Hollywood']
law_bots = ['Bottom Feeder', 'Blood sucker', 'Double Talker', 'Ambulance Chaser', 'Back Stabber', 'Spin Doctor',
            'Legal Eagle', 'Big Wig']

def format_box(bots):
    new_bots = []
    for string in bots:
        new_bot = string.replace('', ' ')
        new_bots.append(new_bot)
    return new_bots

def print_bots(bots):
    for i in bots:
        print(i)
        print()

def get_all_info():
    driver = webdriver.Chrome()
    driver.get("https://toonhq.org/invasions/")
    sleep(2)
    bots = driver.find_elements_by_class_name('media-body')
    info = [name.text for name in bots if name.text != '']
    new_bots = format_box(info)

    t = 0
    """    for index, (x, y) in enumerate(zip(boss_bots, info)):
        if x == y:
            new_bots.insert(index, 'Boss Bot')"""

    for x in boss_bots:
        for index, y in enumerate(new_bots):
            #print('Boss bots: ' + x + 'index: ' + str(index) + 'Bot list: ' + y)
            if x in y[index]:
                new_bots.insert(index, 'Boss Bot')

    print_bots(new_bots)
    driver.close()
    return info

get_all_info()


问:
Graceful way to link to item in Sitecore client?
I am looking for the best way to link to an item in the Sitecore client (not the external website). The link will be embedded in a broken links report email. The user should be able to click the link and launch the Sitecore content editor with that Item auto-selected in the tree.

I have found Mark Ursino's solution on his blog here, but unfortunately, it only works if you are actively logged into Sitecore (Otherwise, it brings you to the Sitecore Desktop after logging in).

I am running Sitecore.NET 6.4.1 (rev. 110324)

UPDATE

Just to close the loop on Marko's solution:

```<code>public void Process(LoggedInArgs args)
{
    string url = HttpUtility.UrlDecode(WebUtil.GetQueryString("url"));

    // Ensure we're dealing with the client login site and there is a URL to redirect to
    if (Sitecore.Context.GetSiteName() == "login" &&
        !String.IsNullOrEmpty(url))
    {
        var queryString = WebUtil.ParseQueryString(url);

        // Check for redirect param to prevent accidental redirections
        if (queryString.ContainsKey("redirectAfterLogin"))
                WebUtil.Redirect(url);
    }
}
</code>```

答:
I think the easiest solution by far would be to simply roll your own login page.  There is nothing that the default Sitecore login is doing that you can't do yourself very easily in a new page... one that then automatically redirects the user to the appropriate item in Content Editor.

This is essentially the same as mstiles first suggestion, minus the auto-login process.  That's just a security breach waiting to happen... don't do that.

Body:
I am looking for the best way to link to an item in the Sitecore client (not the external website). The link will be embedded in a broken links report email. The user should be able to click the link and launch the Sitecore content editor with that Item auto-selected in the tree.

I have found Mark Ursino's solution on his blog here, but unfortunately, it only works if you are actively logged into Sitecore (Otherwise, it brings you to the Sitecore Desktop after logging in).

I am running Sitecore.NET 6.4.1 (rev. 110324)

UPDATE

Just to close the loop on Marko's solution:

public void Process(LoggedInArgs args)
{
    string url = HttpUtility.UrlDecode(WebUtil.GetQueryString("url"));

    // Ensure we're dealing with the client login site and there is a URL to redirect to
    if (Sitecore.Context.GetSiteName() == "login" &&
        !String.IsNullOrEmpty(url))
    {
        var queryString = WebUtil.ParseQueryString(url);

        // Check for redirect param to prevent accidental redirections
        if (queryString.ContainsKey("redirectAfterLogin"))
                WebUtil.Redirect(url);
    }
}


问:
read pdf from url to memory omitting saving file to local file
I have a problem with omitting saving file to a local file. My problem is how to pass directly the url content to the pdfplumber module. My code is as follows

```<code>from pathlib import Path
import urllib3
import pdfplumber

def read_pdf(url: str) -> str:
    http = urllib3.PoolManager()
    temp = Path('temp.pdf')
    temp.write_bytes(http.request("GET", url).data)
    with pdfplumber.open(temp) as pdf:
        text = pdf.pages[0].extract_text()
    temp.unlink()
    return text

text = read_pdf('https://sample.com/test.pdf')
</code>```

It works but I would like to avoid saving file to local but do it in the RAM only.
I have tried io.BytesIO but it doesn't work

答:
Here is an example, which uses io.BytesIO() instead of creating any files on the hard drive.
Note that pdfplumber.load(...) is used instead of pdfplumber.open(...).

```<code>import urllib3
import pdfplumber
import io

def read_pdf(url: str) -> str:
    http = urllib3.PoolManager()
    temp = io.BytesIO()
    temp.write(http.request("GET", url).data)
    with pdfplumber.load(temp) as pdf:
        text = pdf.pages[0].extract_text()
    return text

text = read_pdf('https://sample.com/test.pdf')
</code>```

Body:
I have a problem with omitting saving file to a local file. My problem is how to pass directly the url content to the pdfplumber module. My code is as follows

from pathlib import Path
import urllib3
import pdfplumber

def read_pdf(url: str) -> str:
    http = urllib3.PoolManager()
    temp = Path('temp.pdf')
    temp.write_bytes(http.request("GET", url).data)
    with pdfplumber.open(temp) as pdf:
        text = pdf.pages[0].extract_text()
    temp.unlink()
    return text

text = read_pdf('https://sample.com/test.pdf')

It works but I would like to avoid saving file to local but do it in the RAM only.
I have tried io.BytesIO but it doesn't work

Body:
Here is an example, which uses io.BytesIO() instead of creating any files on the hard drive.
Note that pdfplumber.load(...) is used instead of pdfplumber.open(...).

import urllib3
import pdfplumber
import io

def read_pdf(url: str) -> str:
    http = urllib3.PoolManager()
    temp = io.BytesIO()
    temp.write(http.request("GET", url).data)
    with pdfplumber.load(temp) as pdf:
        text = pdf.pages[0].extract_text()
    return text

text = read_pdf('https://sample.com/test.pdf')


问:
Add class style to CKEditor text with javascript
I'm building a self contained web page and am using CKEditor 4.6.2 for input. My last hurdle, for now, is trying to apply a css class style to text inserted via javascript. My css is in the head tag, nothing special there. I have defined a styleset as directed by CKEditor documentation.

```<code>CKEDITOR.stylesSet.add('my_custom_styles', [
      // Block-level Styles
      { name: 'My Custom Block', element: 'p',
        styles:{
          'color': 'dimgray',
          'padding-left':'15px',
          'border-left-style':'solid',
          'border-width':'3px',
          'border-color':'#52bab3',
          'margin-left':'2px',
        }
      },
      { name: 'MyCustomInline', element: 'span', attributes: {'class': 'redText'}
      }
    ]);
</code>```

And added it in CKEditor

```<code>CKEDITOR.replace('LogBook', {
      language: 'en',
      uiColor: '#9AB8F3',
      toolbar: [
        ['Undo','Redo','-'],
        ['Bold','Italic','Underline','Strike','-'],
        ['RemoveFormat','-'],
        ['NumberedList','BulletedList','-'],
        ['HorizontalRule'],
        '/',
        ['Styles','-','Source','-','About','Maximize'],
      ],
      removeButtons: 'Subscript,Superscript,Cut,Copy,Paste,Anchor,Scayt,PasteText,PasteFromWord,Image,SpecialChar,Link,Unlink,Table,Indent,Outdent,Blockquote,Format',
      removePlugins: 'wsc,scayt',
 stylesSet:'my_custom_styles',
 allowedContent: true
    })
</code>```

But for the life of me I can't figure out how to apply a class to an element in the editor with javascript like so...

```<code><p class="My Custom Block">Some text here</p>
</code>```

I have turned off content filtering and have a custom function that inserts the above code, but the paragraph element does not get styled.

I have also tried applying styles right from my style sheet like:

```<code><p class="redText">Some text here</p>
</code>```

But again the paragraph element isn't getting styled.

Any help would be great, thank you.

答:
After a long search I finally ran across an answer (by surtyaar towards the bottom) to add a class to a CKEditor elements.

```<code>CKEDITOR.addCss( '.redText { border-bottom: 1px dotted red }' );
</code>```

This needs to be called before the CKEditor instances are declared.

From the CKEditor docs.

Body:
I'm building a self contained web page and am using CKEditor 4.6.2 for input. My last hurdle, for now, is trying to apply a css class style to text inserted via javascript. My css is in the head tag, nothing special there. I have defined a styleset as directed by CKEditor documentation.

CKEDITOR.stylesSet.add('my_custom_styles', [
      // Block-level Styles
      { name: 'My Custom Block', element: 'p',
        styles:{
          'color': 'dimgray',
          'padding-left':'15px',
          'border-left-style':'solid',
          'border-width':'3px',
          'border-color':'#52bab3',
          'margin-left':'2px',
        }
      },
      { name: 'MyCustomInline', element: 'span', attributes: {'class': 'redText'}
      }
    ]);

And added it in CKEditor

CKEDITOR.replace('LogBook', {
      language: 'en',
      uiColor: '#9AB8F3',
      toolbar: [
        ['Undo','Redo','-'],
        ['Bold','Italic','Underline','Strike','-'],
        ['RemoveFormat','-'],
        ['NumberedList','BulletedList','-'],
        ['HorizontalRule'],
        '/',
        ['Styles','-','Source','-','About','Maximize'],
      ],
      removeButtons: 'Subscript,Superscript,Cut,Copy,Paste,Anchor,Scayt,PasteText,PasteFromWord,Image,SpecialChar,Link,Unlink,Table,Indent,Outdent,Blockquote,Format',
      removePlugins: 'wsc,scayt',
 stylesSet:'my_custom_styles',
 allowedContent: true
    })

But for the life of me I can't figure out how to apply a class to an element in the editor with javascript like so...

Some text here

I have turned off content filtering and have a custom function that inserts the above code, but the paragraph element does not get styled.

I have also tried applying styles right from my style sheet like:

Some text here

But again the paragraph element isn't getting styled.

Any help would be great, thank you.

Body:
After a long search I finally ran across an answer (by surtyaar towards the bottom) to add a class to a CKEditor elements.

CKEDITOR.addCss( '.redText { border-bottom: 1px dotted red }' );

This needs to be called before the CKEditor instances are declared.

From the CKEditor docs.


问:
Symfony installing doctrine
So here is what i did, i did use this command

```<code>composer require doctrine
</code>```

and i got this message while installing, i am told that symfony was down when i tried to install this.

```<code>The "https://flex.symfony.com/aliases.json" file could not be downloaded: failed to open stream: Connection refused
</code>```

https://flex.symfony.com/aliases.json could not be fully loaded, package information was loaded from the local cache and may be out of date

Then i was told i need to install

```<code> composer require symfony/orm-pack
 composer require --dev symfony/maker-bundle
</code>```

My problem is that my .env file does not contain any or any other database configurations...
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name"

What is it i am doing wrong? I would be very grateful for any help..

答:
Try forcing the use of https with composer:</p>

```<code>composer config -g repo.packagist composer https://packagist.org
</code>```

Title: Symfony installing doctrine

Body:
So here is what i did, i did use this command

composer require doctrine

and i got this message while installing, i am told that symfony was down when i tried to install this.

The "https://flex.symfony.com/aliases.json" file could not be downloaded: failed to open stream: Connection refused

https://flex.symfony.com/aliases.json could not be fully loaded, package information was loaded from the local cache and may be out of date

Then i was told i need to install

 composer require symfony/orm-pack
 composer require --dev symfony/maker-bundle

My problem is that my .env file does not contain any or any other database configurations...
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name"

What is it i am doing wrong? I would be very grateful for any help..

Body:
Try forcing the use of https with composer:

composer config -g repo.packagist composer https://packagist.org


问:
will an in clause always return the same order in mysql
ok so i have this query

```<code>select price from product where product_id in (49, 50, 51)
</code>```

and I want to know if the three records returned will be in the same order as my in clause. SO for example

```<code>100.0000
166.0000
55.0000
</code>```

will 100.0000 belong to 49, 166.0000 to 50 and 55.0000 to 51

答:
No

An IN clause does not sort your rows.
Also IN clauses suck, if you can avoid them do.

```<code>SELECT price from product where product_id BETWEEN 49 AND 51
</code>```

is a better query. If you want your query in a particular order do order by somefield at the end.

More on IN

In your use case you don't need IN, because you can trade 3 comparisons with 2, which is faster.

If your query is:

```<code>select price from product where product_id in (51547, 417853, 879823)
</code>```

Then using IN is fine. This is the only case where IN doesn't suck

Especially never use IN with a subselect

coding horror

```<code>SELECT price FROM product WHERE product_id IN
    (SELECT product_id FROM tableX)
</code>```

Replace this with

```<code>SELECT price FROM product
INNER JOIN tableX ON (product.product_id = tableX.product_id)
</code>```

Which is much faster.

Body:
ok so i have this query

select price from product where product_id in (49, 50, 51)

and I want to know if the three records returned will be in the same order as my in clause. SO for example

100.0000
166.0000
55.0000

will 100.0000 belong to 49, 166.0000 to 50 and 55.0000 to 51

Body:
No

An IN clause does not sort your rows.
Also IN clauses suck, if you can avoid them do.

SELECT price from product where product_id BETWEEN 49 AND 51

is a better query. If you want your query in a particular order do order by somefield at the end.

More on IN

In your use case you don't need IN, because you can trade 3 comparisons with 2, which is faster.

If your query is:

select price from product where product_id in (51547, 417853, 879823)

Then using IN is fine. This is the only case where IN doesn't suck

Especially never use IN with a subselect

coding horror

SELECT price FROM product WHERE product_id IN
    (SELECT product_id FROM tableX)

Replace this with

SELECT price FROM product
INNER JOIN tableX ON (product.product_id = tableX.product_id)

Which is much faster.


问:
How can I get calculate an average in angular?
I'm trying add average reviews info when people review number of stars and then it calculate that movie have that average stars. I don't know how to get my avg caluclate in html.

Here is my HTML file:

```<code><div *ngFor="let movie of movieData">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Reviewer</th>
        <th>Stars</th>
        <th>Reviews</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let info of movie.reviews">
        <td>{{info.name}}</td>
        <td>{{info.stars}}</td>
        <td>{{info.comment}}</td>
      </tr>
    </tbody>
  </table>
</div>
<p>Average rating: <b> {{avgRating}} </b></p>
</code>```

my DetailsComponent component:

```<code>export class DetailsComponent implements OnInit {
  @Input() avgRating: any;
  movieID: string;
  movieData: any;
  avg;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private httpService: HttpService
  ) {}

  ngOnInit() {
    this.movieID = this.route.snapshot.paramMap.get("id");
    this.getOneMovie();
  }

  getOneMovie() {
    let observable = this.httpService.oneMovie(this.movieID);
    observable.subscribe((data) => {
      this.movieData = data;
    });
  }
  getMovie(idx) {
    var sum = 0;
    for (var i = 0; i < this.movieData.reviews.length; i++) {
      sum += this.movieData.reviews[i].stars;
    }
    this.avg = sum / this.movieData.reviews.length;
  }
}
</code>```

and my model.js file:

```<code>const ReviewSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Customer name is required"],
        minlength: [3, "Customer name must be a minimum of 3 characters"]
    },
    stars: {
        type: Number,
        required: [true, "Star is required"]
    },
    comment: {
        type: String,
        required: [true, "Review is required"],
        minlength: [3, "Review must be a minimum of 3 characters"]
    },
})

const MovieSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, "Movie title is required"],
        minlength: [3, "Movie title must be a minimum of 3 characters"]
    },
    reviews: [ReviewSchema]
})
</code>```

Could anybody help?

答:
There are some issues here.

First there is avgRating defined as an input:

```<code>@Input() avgRating: any;
</code>```

but it doesn't seem it should be an input, if it's an input you don't need to calculate it and then it's shown in the template as the same value that is get as the input.

On the other hand, there is an avg var which is supposed to have the value of the average. But the getMovie() method that does the maths to set the avg value seems not to be ever called.

What it seems more logical to me would be to get rid of avgRating var and then call getMovie(idx) on getOneMovie() method when the subscription callback is executed:

```<code>  getOneMovie() {
    let observable = this.httpService.oneMovie(this.movieID);
    observable.subscribe((data) => {
      this.movieData = data;
      getMovie(idx)
    });
  }
</code>```

And use this avg var in the template:

```<code><p>Average rating: <b> {{ avg }} </b></p>
</code>```

Actually the idx parameter of getMovie(idx) seems not to be used for anything so you might also want to get rid of this parameter.

Body:
I'm trying add average reviews info when people review number of stars and then it calculate that movie have that average stars. I don't know how to get my avg caluclate in html.

Here is my HTML file:

        Reviewer
        Stars
        Reviews
        Action

        {{info.name}}
        {{info.stars}}
        {{info.comment}}

Average rating:  {{avgRating}}

my DetailsComponent component:

export class DetailsComponent implements OnInit {
  @Input() avgRating: any;
  movieID: string;
  movieData: any;
  avg;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private httpService: HttpService
  ) {}

  ngOnInit() {
    this.movieID = this.route.snapshot.paramMap.get("id");
    this.getOneMovie();
  }

  getOneMovie() {
    let observable = this.httpService.oneMovie(this.movieID);
    observable.subscribe((data) => {
      this.movieData = data;
    });
  }
  getMovie(idx) {
    var sum = 0;
    for (var i = 0; i < this.movieData.reviews.length; i++) {
      sum += this.movieData.reviews[i].stars;
    }
    this.avg = sum / this.movieData.reviews.length;
  }
}

and my model.js file:

const ReviewSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Customer name is required"],
        minlength: [3, "Customer name must be a minimum of 3 characters"]
    },
    stars: {
        type: Number,
        required: [true, "Star is required"]
    },
    comment: {
        type: String,
        required: [true, "Review is required"],
        minlength: [3, "Review must be a minimum of 3 characters"]
    },
})

const MovieSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, "Movie title is required"],
        minlength: [3, "Movie title must be a minimum of 3 characters"]
    },
    reviews: [ReviewSchema]
})

Could anybody help?

Body:
There are some issues here.

First there is avgRating defined as an input:

@Input() avgRating: any;

but it doesn't seem it should be an input, if it's an input you don't need to calculate it and then it's shown in the template as the same value that is get as the input.

On the other hand, there is an avg var which is supposed to have the value of the average. But the getMovie() method that does the maths to set the avg value seems not to be ever called.

What it seems more logical to me would be to get rid of avgRating var and then call getMovie(idx) on getOneMovie() method when the subscription callback is executed:

  getOneMovie() {
    let observable = this.httpService.oneMovie(this.movieID);
    observable.subscribe((data) => {
      this.movieData = data;
      getMovie(idx)
    });
  }

And use this avg var in the template:

<p>Average rating: <b> {{ avg }} </b></p>

Actually the idx parameter of getMovie(idx) seems not to be used for anything so you might also want to get rid of this parameter.


问:
Is there a better way to find properties of object in an array
I am improving my coding skills. I wrote a code and it works fine. But I think it could be written better.

Here is are the codes and a bit of explanation,

I use the code below to setState for an array named transactions

```<code>useEffect(() => {
  TransactionService.getTransactions().then(data => {
    setTransactions(data.transactions);
  });
}, []);
</code>```

I needed to sum an object in the transaction array so I wrote this code.

```<code>let a = transactions,
  total = 0;

for (var i = 0; i < a.length; i++) {
  total += a[i].amount;

  console.log('total', total);
};
</code>```

Then, use the code by calling it like this  {total}

```<code><h1>{total}</h1>
</code>```

Then I needed the value of a property in the last object within the array so I wrote this

```<code>var array1 = transactions;
var first = array1[array1.length - 1];

console.log(first);

const payment = { ...first };
</code>```

And subsequently used it like this

```<code><h1>{payment.amount}</h1>
</code>```

The code works fine
Please any idea on how to write this better. Thanks

答:
This works better for me. thanks,

  const lastTransaction = transactions[transactions.length - 1];
  let lastPayment = ({ ...lastTransaction }).amount;
  const today = new Date();
  let lastMonth = today.getMonth() - 1;
  let relevantYear = today.getYear();
  let thisMonth = today.getMonth();

  const lastMonthTransactions = transactions.filter(i => {
  const date = new Date(i.date);
    return date.getMonth() === lastMonth && date.getYear() === relevantYear;
  }).reduce((prev, curr) => prev + parseFloat(curr.amount), 0)```

@Tr1stan @Emile Bergeron

Body:
I am improving my coding skills. I wrote a code and it works fine. But I think it could be written better.

Here is are the codes and a bit of explanation,

I use the code below to setState for an array named transactions

useEffect(() => {
  TransactionService.getTransactions().then(data => {
    setTransactions(data.transactions);
  });
}, []);

I needed to sum an object in the transaction array so I wrote this code.

let a = transactions,
  total = 0;

for (var i = 0; i < a.length; i++) {
  total += a[i].amount;

  console.log('total', total);
};

Then, use the code by calling it like this  {total}

{total}

Then I needed the value of a property in the last object within the array so I wrote this

var array1 = transactions;
var first = array1[array1.length - 1];

console.log(first);

const payment = { ...first };

And subsequently used it like this

{payment.amount}

The code works fine
Please any idea on how to write this better. Thanks

Body:
This works better for me. thanks,

  const lastTransaction = transactions[transactions.length - 1];
  let lastPayment = ({ ...lastTransaction }).amount;
  const today = new Date();
  let lastMonth = today.getMonth() - 1;
  let relevantYear = today.getYear();
  let thisMonth = today.getMonth();

  const lastMonthTransactions = transactions.filter(i => {
  const date = new Date(i.date);
    return date.getMonth() === lastMonth && date.getYear() === relevantYear;
  }).reduce((prev, curr) => prev + parseFloat(curr.amount), 0)

@Tr1stan @Emile Bergeron


问:
Wicket authentication error following example
I am learning wicket and trying to implement Authentication based on the flowing strategy

Example

I created MyAuthenticatedWebApplication class and also MyAuthenticatedWebSession with all other components, but as soon as I am trying to go to MySignInPage, I get this error.

Last cause: org.apache.wicket.protocol.http.WebSession cannot be cast to org.apache.wicket.authroles.authentication.AuthenticatedWebSession
WicketMessage: Error attaching this container for rendering: [Page class = com.myapp.wicket.SignInPage, id = 3, render count = 1]

Can someone please help?

答:
Solution:

When you define a class that extends AuthenticatedWebApplication, you don't have any method:

```<code>protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
    return BasicAuthenticationSession.class; }
</code>```

So you cannot override that method.

Background:

I had the same problem, but the solutions above don't work.

Body:
Solution:

When you define a class that extends AuthenticatedWebApplication, you don't have any method:

protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
    return BasicAuthenticationSession.class; }

So you cannot override that method.

Background:

I had the same problem, but the solutions above don't work.


问:
algorithm to read a matrix diagonally (all diagonalls)
i need an algorith that can read a matrix diagonally (all diagonals).

Example of input and output:

input:

```<code>matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
 ]
</code>```

and the output have to be like this:

```<code>["a", "eb", "ifc", "mjgd", "nkh", "ol","p"]
</code>```

thank you for your help.

答:
Let n be the number of rows (or columns),
then the number of diagonals is 2*n-1

For the first character of each string, we go down the first column,
once we reach the bottom left corner we start going across the bottom row

When adding characters to the strings, for every [row][column] that we are on, the next one we need to go to will be at [row-1][column+1]

Here a sample java code that adds the the diagonals as a string to an array, then prints the array out to stdout

```<code>    public static void main(String[] args){
        int n = 4;  // number of rows
        String array[] = new String[2*n-1];  // array to hold the diagonals
        int arrayIndex = 0;
        for (int i = 0; i < 2*n-1; i++) {
            if (i < n) {  // until we reach the bottom left corner
                int row = i;  // for each row
                int column = 0;  // start from the left side
                String tmp = "";
                while (row >= 0)
                    tmp += m[row--][column++];
                array[arrayIndex++] = tmp;
            }
            else {  // after we've reached the bottom left corner
                int row = n-1;  // start from the bottom row
                int column = i-n+1;  // for each column
                String tmp = "";
                while (column < n)
                    tmp += m[row--][column++];
                array[arrayIndex++] = tmp;
            }
        }

        // prints out the array
        for (String s : array)
            System.out.print(s + " ");
        System.out.print("\n");
    }

    static String m[][] = {
        {"a", "b", "c", "d"},
        {"e", "f", "g", "h"},
        {"i", "j", "k", "l"},
        {"m", "n", "o", "p"}
    };
</code>```

Here is what stdout looks like

```<code>a eb ifc mjgd nkh ol p
</code>```

Hope this helps :)

Body:
i need an algorith that can read a matrix diagonally (all diagonals).

Example of input and output:

input:

matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
 ]

and the output have to be like this:

["a", "eb", "ifc", "mjgd", "nkh", "ol","p"]

thank you for your help.

Body:
Let n be the number of rows (or columns),
then the number of diagonals is 2*n-1

For the first character of each string, we go down the first column,
once we reach the bottom left corner we start going across the bottom row

When adding characters to the strings, for every [row][column] that we are on, the next one we need to go to will be at [row-1][column+1]

Here a sample java code that adds the the diagonals as a string to an array, then prints the array out to stdout

    public static void main(String[] args){
        int n = 4;  // number of rows
        String array[] = new String[2*n-1];  // array to hold the diagonals
        int arrayIndex = 0;
        for (int i = 0; i < 2*n-1; i++) {
            if (i < n) {  // until we reach the bottom left corner
                int row = i;  // for each row
                int column = 0;  // start from the left side
                String tmp = "";
                while (row >= 0)
                    tmp += m[row--][column++];
                array[arrayIndex++] = tmp;
            }
            else {  // after we've reached the bottom left corner
                int row = n-1;  // start from the bottom row
                int column = i-n+1;  // for each column
                String tmp = "";
                while (column < n)
                    tmp += m[row--][column++];
                array[arrayIndex++] = tmp;
            }
        }

        // prints out the array
        for (String s : array)
            System.out.print(s + " ");
        System.out.print("\n");
    }

    static String m[][] = {
        {"a", "b", "c", "d"},
        {"e", "f", "g", "h"},
        {"i", "j", "k", "l"},
        {"m", "n", "o", "p"}
    };

Here is what stdout looks like

a eb ifc mjgd nkh ol p

Hope this helps :)


问:
Serial communication in second thread, asynchronously?
I want to put the serial communication with an external device to a second thread, c#.

Here there is my first thread doing some stuff.
And there is the serial worker, the second thread:

It opens the serial port

It asks the external serial device regulary: Are you alive?

It receives queries from the first thread with a string and an int like: "Command2", 33 and it should give this to the external serial device.

Sometimes there comes an answer from the external serial device back with a string and an int  like: "Command4", 55 and the second thread should give this to the first thread and it should start a process there.

The second thread also does own things like error detection which I want to keep free the first thread of.

Serial communication itself works fine but I have problems with threads, delegates, BeginInvokes, EventHandlers, etc.

My first thread:

```<code>Class MainProgramme
{
internal void StartSerialCommunication
{
=> Here I want the second thread to open the serial port and I want to start the regulary serial device check, all in the
second thread.
}
internal bool SerialCommand(string s, int i)
{
=> Here I want to give the command s and i to the second thread asynchronously. That means this process does not wait for an answer from the second thread.
}
</code>```

The following process should be fired by the second thread because the second thread has received some important data
from the external serial device.

```<code>internal void SerialAnswered
{
=> Here I want to get the string and the int from the second device back.
}
}
</code>```

My second thread:

```<code>Class SerialCommunication
{
internal bool SerialDeviceIsAlive = true;
public bool SerialOpen

{
SerialPortMsp.Open();
RegularyDeviceCheckTimer.Enabled = true;
return true;
}

private void RegularyDeviceCheckTimer_Tick(System.Object

sender, System.EventArgs e)
{
if SerialDeviceIsAlive == true)
{
SerialDeviceIsAlive == false;
}
else
{
=> Here I want to inform the first thread that the answer from the external serial device is missing.
}
SerialSend("AreYouAlive");
}

public void SerialReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
IAmAlive = true;
int buff = SerialPortMsp.ReadExisting();
if (buff.IndexOf(new string('\n', 1)) > 0)
{
=> Here I want to inform the first thread that the answer was buff.
}
}

public bool SerialSend(string SerialCommand)
{
SerialPortMsp.Write(SerialCommand.ToCharArray(), 0,

SerialCommand.Length);
return true;
}
}
</code>```

I need help in calling processes and transferring data between the two threads.

答:
I think both thread1 and thread2 have their "own" execution path, and you can not force them to "interrupt" and do something with the data that you built in the other thread.
What you can do is that you "plan" for the possibility that there is something ready in the other thread that might need your attention in the current thread. Hence, both thread1 and thread2 need a code that regularly checks if there is something "ready" in the other thread.
If you plan to do other things in thread1 you still need to build in a regular check/poll for the results of thread2 and vica versa.

The concrete communication between the threads might be implemented with a queue in each direction. In .NET 4.0 there is a ConcurrentQueue class for thread-safe producer/consumer implementation. When thread1 has a command it should queue it in the command queue, while thread2 should regularly check if there are commands waiting. When thread2 has a result ready, it should queue it in a result queue, while thread1 should regularly check if there is a result and run the processing code accordingly.

Having all this said, I think you should consider once more, if your solution with exactly these two threads is really what you need. However, this depends on the details of your requirements (e.g. what other things thread1 should do in the meanwhile, and what the processing of the command result means, can it run parallel, etc).

My suggestion would be to align your design based on the producer/consumer pattern. That is a typical concurrency task and you will find a lot of explanations and optimized solutions (e.g. where the consumer does not have to poll the queue, but it can sleep on a waithandle, semaphore, or some other construct without using CPU and it can be waken up by the producers if there is something to consume).
In your case you could use this pattern twice. The CommandProducer is the entity that creates the commands and feeds the CommandConsumer (that can consume it by passing it to the serial line). On the back way you have the CommandResultProducer that reads the serial line and passes the result to the CommandResultConsumer to do something with the result. Aligning your code like this would result in a more flexible and clear solution, and you can even increase the number of consumer or producer threads if it turns out to be practical.

Body:
I want to put the serial communication with an external device to a second thread, c#.

Here there is my first thread doing some stuff.
And there is the serial worker, the second thread:

It opens the serial port

It asks the external serial device regulary: Are you alive?

It receives queries from the first thread with a string and an int like: "Command2", 33 and it should give this to the external serial device.

Sometimes there comes an answer from the external serial device back with a string and an int  like: "Command4", 55 and the second thread should give this to the first thread and it should start a process there.

The second thread also does own things like error detection which I want to keep free the first thread of.

Serial communication itself works fine but I have problems with threads, delegates, BeginInvokes, EventHandlers, etc.

My first thread:

Class MainProgramme
{
internal void StartSerialCommunication
{
=> Here I want the second thread to open the serial port and I want to start the regulary serial device check, all in the
second thread.
}
internal bool SerialCommand(string s, int i)
{
=> Here I want to give the command s and i to the second thread asynchronously. That means this process does not wait for an answer from the second thread.
}

The following process should be fired by the second thread because the second thread has received some important data
from the external serial device.

internal void SerialAnswered
{
=> Here I want to get the string and the int from the second device back.
}
}

My second thread:

Class SerialCommunication
{
internal bool SerialDeviceIsAlive = true;
public bool SerialOpen

{
SerialPortMsp.Open();
RegularyDeviceCheckTimer.Enabled = true;
return true;
}

private void RegularyDeviceCheckTimer_Tick(System.Object

sender, System.EventArgs e)
{
if SerialDeviceIsAlive == true)
{
SerialDeviceIsAlive == false;
}
else
{
=> Here I want to inform the first thread that the answer from the external serial device is missing.
}
SerialSend("AreYouAlive");
}

public void SerialReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
IAmAlive = true;
int buff = SerialPortMsp.ReadExisting();
if (buff.IndexOf(new string('\n', 1)) > 0)
{
=> Here I want to inform the first thread that the answer was buff.
}
}

public bool SerialSend(string SerialCommand)
{
SerialPortMsp.Write(SerialCommand.ToCharArray(), 0,

SerialCommand.Length);
return true;
}
}

I need help in calling processes and transferring data between the two threads.


Title: Lodash create object from array of arrays

Body:
I would like to use lodash to generete object from array of arrays. I use for it lodash.zipObject method and map. But it is not 1:1 what I would like to generate:

Input:

 "rows": [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ]

dictionary: ['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll' ], [action.yearReportData]

output:

{
  source: ['stravi/aa', 'stravi/ab', 'stravi/ac'],
  sessions: ['202001', '202003', '202007']
  ...
}

I would like to use lodash, and I try by:

   lodash.map(rows, arr =>
                lodash.zipObject(['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll'], arr))

But is not correct... I received multiple object. I would like to have one object with all data. Like my example.

Body:
Unzip the rows to transpose the sub-arrays, and then use zip object:

const { flow, unzip, zipObject } = _

const fn = flow(
  unzip,
  arr => zipObject(['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll'], arr)
)

const rows = [["stravi/aa","202001","59","51","2558.98","0.5358894453719162","1.9204668112983725","140","2.3466309084813943"],["stravi/ab","202003","3591","349","2246.09","0.41838214","3.57603358","50","4.82115474"],["stravi/ac","202007","3354","25","1975.76","0.74220667708","1.12321555541","11","0.9324532454"]]

const result = fn(rows)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>