问:
When I click on the button, the value of that button needs to add up to sum
I was trying to code a POS like system as a small project to learn with.
So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object.
As soon as I click on one button the price needs to be added to sum.
Well what the code is currently doing is to add up the prices of the same product.
So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.

Here is the code:

```<code>  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

and here is the HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>POS</title>
  </head>

  <body>
    <button class="btn" id="cola">Cola</button>
    <button class="btn" id="fanta">Fanta</button>
    <script>
     ....
    </script>
  </body>
</html>
</code>```

答:
that is because you are declaring the variable "sum" inside the loop, so each one will get a unique "sum". What you need to do is to have them both share 1 variable "sum", so intead of this:

```<code>  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

do this:

```<code>  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };
  let sum = null; // moved it up here
  for (let i = 0; i < btnChoose.length; i++) {
    // moved it away from here
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

Body:
I was trying to code a POS like system as a small project to learn with.
So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object.
As soon as I click on one button the price needs to be added to sum.
Well what the code is currently doing is to add up the prices of the same product.
So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.

Here is the code:

  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }

and here is the HTML:

<!DOCTYPE html>

    <title>POS</title>

    <button class="btn" id="cola">Cola</button>
    <button class="btn" id="fanta">Fanta</button>

Body:
that is because you are declaring the variable "sum" inside the loop, so each one will get a unique "sum". What you need to do is to have them both share 1 variable "sum", so intead of this:

  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }

do this:

  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };
  let sum = null; // moved it up here
  for (let i = 0; i < btnChoose.length; i++) {
    // moved it away from here
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }


来源: stackexchange

问:
Can i mix Time and IF functions in excel?
I want to make a formula where :
If the time now is between 6:00 am and 8:00 am then type the word "early"
is it possible rephrase this in excel to achieve the result?</p>

答:
Yes, you can use any one of the following, assuming Cell A1 has a Time Value

```<code>=IF(AND(A1>=TIME(6,0,0),A1<=TIME(8,0,0)),"Early","")
</code>```

or

```<code>=IF(AND(A1>="06:00:00",A1<="08:00:00"),"Early","")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Yes, you can use any one of the following, assuming Cell A1 has a Time Value

=IF(AND(A1>=TIME(6,0,0),A1<=TIME(8,0,0)),"Early","")

or

=IF(AND(A1>="06:00:00",A1<="08:00:00"),"Early","")


问:
Half transparent image Pillow
How do i make an image half transparent like the dank memer command. Ive been using the putalpha since i found it on the Internet when i was searching for a solution but it didnt work. I am using Pillow.

The code:

```<code>class Image_Manipulation(commands.Cog, name="Image Manipulation"):
    def __init__(self, bot:commands.Bot):
        self.bot = bot

    @commands.command(aliases=["Clown","CLOWN"])
    async def clown(self, ctx, user: nextcord.Member = None):
        if user == None:
            user = ctx.author

        clown = Image.open(os.path.join("Modules", "Images", "clown.jpg"))

        useravatar = user.display_avatar.with_size(128)
        avatar_data = BytesIO(await useravatar.read())
        pfp = Image.open(avatar_data)
        pfp = pfp.resize((192,192))
        pfp.putalpha(300)
        if pfp.mode != "RGBA":
            pfp = pfp.convert("RGBA")

        clown.paste(pfp, (0,0))
        clown.save("clown_done.png")

        await ctx.send(file = nextcord.File("clown_done.png"))

def setup(bot: commands.Bot):
    bot.add_cog(Image_Manipulation(bot))
</code>```

The dank memer command example:
https://imgur.com/a/ZDNyKsG

答:
Effect you want to achieve is called average of two images. PIL.Image.blend allow to get weighted average of two images. Example usage:

```<code>from PIL import Image
im1 = Image.open('path/to/image1')
im2 = Image.open('path/to/image2')
im3 = Image.blend(im1, im2, 0.5)
im3.save('path/to/outputimage')
</code>```

where im1 and im2 are images of same size (width x height), you might elect to use different 3rd parameter for Image.blend if you wish one image to have more impact on result image (0.0 results in copy of im1, 1.0 results in copy of im2)

Title: Half transparent image Pillow

Body:
How do i make an image half transparent like the dank memer command. Ive been using the putalpha since i found it on the Internet when i was searching for a solution but it didnt work. I am using Pillow.

The code:

class Image_Manipulation(commands.Cog, name="Image Manipulation"):
    def __init__(self, bot:commands.Bot):
        self.bot = bot

    @commands.command(aliases=["Clown","CLOWN"])
    async def clown(self, ctx, user: nextcord.Member = None):
        if user == None:
            user = ctx.author

        clown = Image.open(os.path.join("Modules", "Images", "clown.jpg"))

        useravatar = user.display_avatar.with_size(128)
        avatar_data = BytesIO(await useravatar.read())
        pfp = Image.open(avatar_data)
        pfp = pfp.resize((192,192))
        pfp.putalpha(300)
        if pfp.mode != "RGBA":
            pfp = pfp.convert("RGBA")

        clown.paste(pfp, (0,0))
        clown.save("clown_done.png")

        await ctx.send(file = nextcord.File("clown_done.png"))

def setup(bot: commands.Bot):
    bot.add_cog(Image_Manipulation(bot))

The dank memer command example:
https://imgur.com/a/ZDNyKsG

Body:
Effect you want to achieve is called average of two images. PIL.Image.blend allow to get weighted average of two images. Example usage:

from PIL import Image
im1 = Image.open('path/to/image1')
im2 = Image.open('path/to/image2')
im3 = Image.blend(im1, im2, 0.5)
im3.save('path/to/outputimage')

where im1 and im2 are images of same size (width x height), you might elect to use different 3rd parameter for Image.blend if you wish one image to have more impact on result image (0.0 results in copy of im1, 1.0 results in copy of im2)


问:
Making a Grid pixel editor in iPad
I need to make a pixel editor in iPad similar like Microsoft Paint when displaying per pixel of the image, would like some advise on approach :

Should I make a series of UIButtons stacked in grid fashion in a UIScrollView? (sounds pretty resourceful and laggy), tapping the uibutton will toggle state to display the pixel.

Should I draw line grids using coregraphic and detect taps using gesturerecognizer (I like this, but need some code samples).

Or should I look into using UITableView and making use of reusable cells for the editor? (This seems like how apple would advise).

Hope to get some interesting responses!

答:
I'd use the UITableView. It's way more efficient and easier to do than a grid full with UIButtons.
Yep, CG is the proper way, I think </p>

ContentLicense: CC BY-SA 3.0

Title: Making a Grid pixel editor in iPad


问:
How to use tailwind with react-day-picker?
I am currently trying to style the DayPickerInput with Tailwind and it does not work. I have read the documentation and it doesn't seem to be integrated so what can be a good approach for this?

The current workaround, which i believe is not a good approach is using nextjs styling

```<code>
import DayPickerInput from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';

export default function DatePicker() {
  return (
    <div>
      <div className="grid grid-cols-3">
        <label>From:</label>
        <DayPickerInput />            <=== I am trying to style this component using tailwind.
      </div>
      <style jsx global>
        {`
          .DayPickerInput input {
            width: 120px;
            padding: 10px;
          }
        `}
      </style>
    </div>
  );
}

</code>```

答:
Try to apply your styles like below</p>
```<code>.DayPickerInput {
  @apply w-full;
}
.DayPickerInput input {
  @apply py-1 w-full px-2 text-base text-gray-700 bg-white rounded-xl outline-none focus:ring-0  transition duration-200 border-gray-400 border focus:border-primary-800;
}
</code>```

Body:
I am currently trying to style the DayPickerInput with Tailwind and it does not work. I have read the documentation and it doesn't seem to be integrated so what can be a good approach for this?

The current workaround, which i believe is not a good approach is using nextjs styling

import DayPickerInput from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';

export default function DatePicker() {
  return (

        From:
        <DayPickerInput />            <=== I am trying to style this component using tailwind.

  );
}

Body:
Try to apply your styles like below

.DayPickerInput {
  @apply w-full;
}
.DayPickerInput input {
  @apply py-1 w-full px-2 text-base text-gray-700 bg-white rounded-xl outline-none focus:ring-0  transition duration-200 border-gray-400 border focus:border-primary-800;
}


问:
How to display the currency symbol to the right in Angular
I have to display Euro currency like this : 583 €.

But with this code:

```<code>{{ price | currency:'EUR':true }}
</code>```

I get €583, is there any option in Angular core to move the symbol to right? A lot of european countries use the symbol at the right (France, Germany, Spain, Italy).

答:
For Angular12 you should import this in your module

```<code>import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';

registerLocaleData(localeDe, 'de-DE', localeDeExtra);

</code>```

And in your providers section

```<code>{
      provide: LOCALE_ID,
      useValue: 'de-DE'
}
</code>```

You can use like this

```<code>{{ price | currency:'EUR'}}
</code>```

The result will be like this

```<code>    139,00 €
</code>```

Body:
I have to display Euro currency like this : 583 €.

But with this code:

{{ price | currency:'EUR':true }}

I get €583, is there any option in Angular core to move the symbol to right? A lot of european countries use the symbol at the right (France, Germany, Spain, Italy).

Body:
For Angular12 you should import this in your module

import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';

registerLocaleData(localeDe, 'de-DE', localeDeExtra);

And in your providers section

{
      provide: LOCALE_ID,
      useValue: 'de-DE'
}

You can use like this

{{ price | currency:'EUR'}}

The result will be like this

    139,00 €


问:
Remove item in JSON if key has value
I have tried everything I can possible come up with, but the value wont go away.

I have a JSON user and if user['permissions'] have key permission = "DELETE PAGE" remove that index of del user['permissions'][1] (in this example)

I want to have a list of possible values as "DELETE PAGE" and so on. If value in key, then delete that index.

Then return the  users json without those items found.

I have tried del user['permission][x] and .pop() and so on but it is still there.

```<code>{
'id': 123,
'name': 'My name',
'description': 'This is who I am',
'permissions': [{
    'id': 18814,
    'holder': {
        'type': 'role',
        'parameter': '321',
        'projectRole': {
            'name': 'Admin',
            'id': 1,
        }
    },
    'permission': 'VIEW PAGE'
}, {
    'id': 18815,
    'holder': {
        'type': 'role',
        'parameter': '123',
        'projectRole': {
            'name': 'Moderator',
            'id': 2
        }
    },
    'permission': 'DELETE PAGE'
}]
</code>```

}

答:
Here's the code:

```<code>perm = a['permissions']
for p in perm:
    if p['permission'] == 'DELETE PAGE':
        perm.remove(p)

print(a)
</code>```

Output:

```<code>{'id': 123, 'name': 'My name', 'description': 'This is who I am', 'permissions': [{'id': 18814, 'holder': {'type': 'role', 'parameter': '321', 'projectRole': {'name': 'Admin', 'id': 1}}, 'permission': 'VIEW PAGE'}]}
</code>```

Title: Remove item in JSON if key has value

Body:
I have tried everything I can possible come up with, but the value wont go away.

I have a JSON user and if user['permissions'] have key permission = "DELETE PAGE" remove that index of del user['permissions'][1] (in this example)

I want to have a list of possible values as "DELETE PAGE" and so on. If value in key, then delete that index.

Then return the  users json without those items found.

I have tried del user['permission][x] and .pop() and so on but it is still there.

{
'id': 123,
'name': 'My name',
'description': 'This is who I am',
'permissions': [{
    'id': 18814,
    'holder': {
        'type': 'role',
        'parameter': '321',
        'projectRole': {
            'name': 'Admin',
            'id': 1,
        }
    },
    'permission': 'VIEW PAGE'
}, {
    'id': 18815,
    'holder': {
        'type': 'role',
        'parameter': '123',
        'projectRole': {
            'name': 'Moderator',
            'id': 2
        }
    },
    'permission': 'DELETE PAGE'
}]

}

Body:
Here's the code:

perm = a['permissions']
for p in perm:
    if p['permission'] == 'DELETE PAGE':
        perm.remove(p)

print(a)

Output:

{'id': 123, 'name': 'My name', 'description': 'This is who I am', 'permissions': [{'id': 18814, 'holder': {'type': 'role', 'parameter': '321', 'projectRole': {'name': 'Admin', 'id': 1}}, 'permission': 'VIEW PAGE'}]}


问:
how to pass extra parameter in Ajax AutoComplete for jQuery?
hi i am using Ajax AutoComplete for jQuery

in my jquery i am using

```<code>        options = { serviceUrl: "<? echo $this->config->item('base_url'); ?>index.php/welcome/autocomplete" };
        a = $('#query').autocomplete(options);
</code>```

i saw that i can pass extra parameters like

```<code>var a = $('#query').autocomplete({
    serviceUrl:'service/autocomplete.ashx',
    minChars:2,
    delimiter: /(,|;)\s*/, // regex or character
    maxHeight:400,
    width:300,
    zIndex: 9999,
    deferRequestBy: 0, //miliseconds
    params: { country:'Yes' }, //aditional parameters
    noCache: false, //default is false, set to true to disable caching
    // callback function:
    onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
    // local autosugest options:
    lookup: ['January', 'February', 'March', 'April', 'May'] //local lookup values
  });
</code>```

so i want to create n new parameter and pass it like this

```<code>         var a = $('#query2').autocomplete({
             serviceUrl: "<? echo $this->config->item('base_url'); ?>index.php/welcome/autocomplete",
             id:'query2'
            });
</code>```

How can i access that extra parameter from the autocomplete code ?? i want to add that id to my

```<code>.autocomplete-w1
</code>```

initially it looks like this

```<code><div class="autocomplete-w1"></div>
</code>```

i want to change it to

```<code> <div id="jquery2" class="autocomplete-w1"></div>
</code>```

please help................................

UPDATE

i tried to adding my id parameter to this function

```<code>  function Autocomplete(el, options) {
    this.el = $(el);
    this.el.attr('autocomplete', 'off');
    this.suggestions = [];
    this.data = [];
    this.badQueries = [];
    this.selectedIndex = -1;
    this.currentValue = this.el.val();
    this.intervalId = 0;
    this.cachedResponse = [];
    this.onChangeInterval = null;
    this.ignoreValueChange = false;
    this.serviceUrl = options.serviceUrl;
    this.isLocal = false;
    this.options = {
      autoSubmit: false,
      minChars: 1,
      maxHeight: 300,
      deferRequestBy: 0,
      width: 0,
      highlight: true,
      params: {},
      fnFormatResult: fnFormatResult,
      delimiter: null,
      zIndex: 9999,
      id:'test'
    };
    this.initialize();
    this.setOptions(options);
  }
</code>```

i gave a default value test . when i alert $this.options.id i always getting 'test' the value i passig jquery2 is not getting . what is the problem there ????

答:
hmmm. i have solved it .

i added extra parameter id

```<code>        a = $('#query').autocomplete({
                                        serviceUrl: "<? echo $this->config->item('base_url'); ?>index.php/welcome/autocomplete",
                                        id: 'query'
                                    });
</code>```

in my jquery.autocomplete.js in

```<code> function Autocomplete(el, options) {
</code>```

i get that parameter like

```<code>  this.id = options.id;
</code>```

now i can add it to div's id

```<code><div class="autocomplete-w1" id='+this.id+'></div>
</code>```

thanks.................... :) :) :D

Body:
hi i am using Ajax AutoComplete for jQuery

in my jquery i am using

        options = { serviceUrl: "<? echo $this->config->item('base_url'); ?>index.php/welcome/autocomplete" };
        a = $('#query').autocomplete(options);

i saw that i can pass extra parameters like

var a = $('#query').autocomplete({
    serviceUrl:'service/autocomplete.ashx',
    minChars:2,
    delimiter: /(,|;)\s*/, // regex or character
    maxHeight:400,
    width:300,
    zIndex: 9999,
    deferRequestBy: 0, //miliseconds
    params: { country:'Yes' }, //aditional parameters
    noCache: false, //default is false, set to true to disable caching
    // callback function:
    onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
    // local autosugest options:
    lookup: ['January', 'February', 'March', 'April', 'May'] //local lookup values
  });

so i want to create n new parameter and pass it like this

         var a = $('#query2').autocomplete({
             serviceUrl: "<? echo $this->config->item('base_url'); ?>index.php/welcome/autocomplete",
             id:'query2'
            });

How can i access that extra parameter from the autocomplete code ?? i want to add that id to my

.autocomplete-w1

initially it looks like this

i want to change it to

please help................................

UPDATE

i tried to adding my id parameter to this function

  function Autocomplete(el, options) {
    this.el = $(el);
    this.el.attr('autocomplete', 'off');
    this.suggestions = [];
    this.data = [];
    this.badQueries = [];
    this.selectedIndex = -1;
    this.currentValue = this.el.val();
    this.intervalId = 0;
    this.cachedResponse = [];
    this.onChangeInterval = null;
    this.ignoreValueChange = false;
    this.serviceUrl = options.serviceUrl;
    this.isLocal = false;
    this.options = {
      autoSubmit: false,
      minChars: 1,
      maxHeight: 300,
      deferRequestBy: 0,
      width: 0,
      highlight: true,
      params: {},
      fnFormatResult: fnFormatResult,
      delimiter: null,
      zIndex: 9999,
      id:'test'
    };
    this.initialize();
    this.setOptions(options);
  }

i gave a default value test . when i alert $this.options.id i always getting 'test' the value i passig jquery2 is not getting . what is the problem there ????

Body:
hmmm. i have solved it .

i added extra parameter id

        a = $('#query').autocomplete({
                                        serviceUrl: "<? echo $this->config->item('base_url'); ?>index.php/welcome/autocomplete",
                                        id: 'query'
                                    });

in my jquery.autocomplete.js in

 function Autocomplete(el, options) {

i get that parameter like

  this.id = options.id;

now i can add it to div's id

<div class="autocomplete-w1" id='+this.id+'></div>

thanks.................... :) :) :D


问:
how to create web service Api in Angular 8?
can anyone help me how to create a web service API in angular 8.
I am in new in angular 8. I am currently working on angular 8 project. Please Help..

from POSTMAN => api

答:
Here I have provided a sample code for creating the web service API in Angular for your reference.

Service.ts

```<code>    import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  constructor(private fb: FormBuilder,private http: HttpClient) { }
  readonly BaseURI = 'http://localhost:53189';

  }
  register() {
    return this.http.post(this.BaseURI + '/auth/Register', body);
  }

  login(formData: any) {
    return this.http.post(this.BaseURI + '/auth/Login', formData);
  }

  getData(){
    return this.http.get(this.BaseURI +'/api/categories');
  }

  viewCategory(id: any) {
    return this.http.get(this.BaseURI + '/api/categories/'+id);
  }

  postData(formData: any){
    return this.http.post(this.BaseURI +'/api/categories',formData);
  }

  putData(id: any,formData: any){
    return this.http.put(this.BaseURI +'/api/categories/'+id,formData);
  }

  deleteData(id:any){
    return this.http.delete(this.BaseURI +'/api/categories/'+ id);
  }

  getProduct() {
    return this.http.get(this.BaseURI +'/api/products')
  }

  viewProducts(id: any) {
    return this.http.get(this.BaseURI + '/api/products/'+id);
  }

  postProduct(formData: any){
    return this.http.post(this.BaseURI +'/api/products',formData);
  }

  putProduct(id: any,formData: any){
    return this.http.put(this.BaseURI +'/api/products/'+id,formData);
  }

  deleteProduct(id:any)
  {
    return this.http.delete(this.BaseURI +'/api/products/'+ id);
  }

  getCart(userId:any) {
    return this.http.get(this.BaseURI +'/api/cart/GetId/'+ userId);
  }

  addProductToCart(userId:any,productId:any) {

    return this.http.put(this.BaseURI +'/api/cart/add/'+userId+'/'+productId,null);
  }

  decreaseQuantity(userId:any,id:any) {
    return this.http.put(this.BaseURI +'/api/cart/decreaseQuantity/'+ userId+'/' + id,null);
  }

  Productbycategory(categoryId: any) {
    return this.http.get(this.BaseURI +'/api/products/Getproduct/' + categoryId );

  }
    getCategory() {
    return this.http.get(this.BaseURI +'/api/categories');
    }

  // getUserProfile() {
  //   var tokenheader= new HttpHeaders({ 'Authorization':'Bearer '+ localStorage.getItem('token')});

  //   return this.http.get(this.BaseURI + '/UserProfile',{headers:tokenheader});
  // }

  }
</code>```

Body:
Here I have provided a sample code for creating the web service API in Angular for your reference.

Service.ts

    import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  constructor(private fb: FormBuilder,private http: HttpClient) { }
  readonly BaseURI = 'http://localhost:53189';

  }
  register() {
    return this.http.post(this.BaseURI + '/auth/Register', body);
  }

  login(formData: any) {
    return this.http.post(this.BaseURI + '/auth/Login', formData);
  }

  getData(){
    return this.http.get(this.BaseURI +'/api/categories');
  }

  viewCategory(id: any) {
    return this.http.get(this.BaseURI + '/api/categories/'+id);
  }

  postData(formData: any){
    return this.http.post(this.BaseURI +'/api/categories',formData);
  }

  putData(id: any,formData: any){
    return this.http.put(this.BaseURI +'/api/categories/'+id,formData);
  }

  deleteData(id:any){
    return this.http.delete(this.BaseURI +'/api/categories/'+ id);
  }

  getProduct() {
    return this.http.get(this.BaseURI +'/api/products')
  }

  viewProducts(id: any) {
    return this.http.get(this.BaseURI + '/api/products/'+id);
  }

  postProduct(formData: any){
    return this.http.post(this.BaseURI +'/api/products',formData);
  }

  putProduct(id: any,formData: any){
    return this.http.put(this.BaseURI +'/api/products/'+id,formData);
  }

  deleteProduct(id:any)
  {
    return this.http.delete(this.BaseURI +'/api/products/'+ id);
  }

  getCart(userId:any) {
    return this.http.get(this.BaseURI +'/api/cart/GetId/'+ userId);
  }

  addProductToCart(userId:any,productId:any) {

    return this.http.put(this.BaseURI +'/api/cart/add/'+userId+'/'+productId,null);
  }

  decreaseQuantity(userId:any,id:any) {
    return this.http.put(this.BaseURI +'/api/cart/decreaseQuantity/'+ userId+'/' + id,null);
  }

  Productbycategory(categoryId: any) {
    return this.http.get(this.BaseURI +'/api/products/Getproduct/' + categoryId );

  }
    getCategory() {
    return this.http.get(this.BaseURI +'/api/categories');
    }

  // getUserProfile() {
  //   var tokenheader= new HttpHeaders({ 'Authorization':'Bearer '+ localStorage.getItem('token')});

  //   return this.http.get(this.BaseURI + '/UserProfile',{headers:tokenheader});
  // }

  }


问:
options.domAPI is not a function
I've tried adding stylus config of Vuetify to modify the global variables, until I noticed that it's not supported anymore.

I've run this command to install the required loaders: npm i --save-dev stylus stylus-loader css-loader style-loader.

After that, I started getting the error in the title, and after removing those libraries, it didn't remove it at all. I've tried running npm reinstall and have a complete fresh install of the npm packages.

My config is like this:

```<code>"devDependencies": {
    "axios": "^0.21.4",
    "bootstrap": "^4.6.0",
    "css-loader": "^6.2.0",
    "jquery": "^3.6",
    "laravel-mix": "^6.0.31",
    "lodash": "^4.17.19",
    "popper.js": "^1.16.1",
    "postcss": "^8.3.6",
    "resolve-url-loader": "^3.1.2",
    "sass": "^1.32.11",
    "sass-loader": "^11.0.1",
    "style-loader": "^3.2.1",
    "stylus": "^0.55.0",
    "stylus-loader": "^6.1.0",
    "vue": "^2.6.12",
    "vue-loader": "^15.9.8",
    "vue-template-compiler": "^2.6.12"
},
"dependencies": {
    "vue-router": "^3.5.2",
    "vuetify": "^2.5.8",
    "vuex": "^3.6.2"
}
</code>```

Error log:

```<code>Uncaught TypeError: options.domAPI is not a function
at addStyle (app.js:38836)
at modulesToDom (app.js:38824)
at module.exports (app.js:38854)
at Module../node_modules/vuetify/dist/vuetify.min.css (app.js:38769)
at __webpack_require__ (app.js:100988)
at Module../resources/js/theme/Vuetify.js (app.js:2356)
at __webpack_require__ (app.js:100988)
at Module../resources/js/app.js (app.js:2139)
at __webpack_require__ (app.js:100988)
</code>```

This is an extremely annoying issue, as I've not found anything related to it. Any help is greatly appreciated.

答:
I had to remove style-loader and only use css-loader to get this error go.

```<code>yarn remove style-loader
</code>```

Title: options.domAPI is not a function

Body:
I've tried adding stylus config of Vuetify to modify the global variables, until I noticed that it's not supported anymore.

I've run this command to install the required loaders: npm i --save-dev stylus stylus-loader css-loader style-loader.

After that, I started getting the error in the title, and after removing those libraries, it didn't remove it at all. I've tried running npm reinstall and have a complete fresh install of the npm packages.

My config is like this:

"devDependencies": {
    "axios": "^0.21.4",
    "bootstrap": "^4.6.0",
    "css-loader": "^6.2.0",
    "jquery": "^3.6",
    "laravel-mix": "^6.0.31",
    "lodash": "^4.17.19",
    "popper.js": "^1.16.1",
    "postcss": "^8.3.6",
    "resolve-url-loader": "^3.1.2",
    "sass": "^1.32.11",
    "sass-loader": "^11.0.1",
    "style-loader": "^3.2.1",
    "stylus": "^0.55.0",
    "stylus-loader": "^6.1.0",
    "vue": "^2.6.12",
    "vue-loader": "^15.9.8",
    "vue-template-compiler": "^2.6.12"
},
"dependencies": {
    "vue-router": "^3.5.2",
    "vuetify": "^2.5.8",
    "vuex": "^3.6.2"
}

Error log:

Uncaught TypeError: options.domAPI is not a function
at addStyle (app.js:38836)
at modulesToDom (app.js:38824)
at module.exports (app.js:38854)
at Module../node_modules/vuetify/dist/vuetify.min.css (app.js:38769)
at __webpack_require__ (app.js:100988)
at Module../resources/js/theme/Vuetify.js (app.js:2356)
at __webpack_require__ (app.js:100988)
at Module../resources/js/app.js (app.js:2139)
at __webpack_require__ (app.js:100988)

This is an extremely annoying issue, as I've not found anything related to it. Any help is greatly appreciated.

Body:
I had to remove style-loader and only use css-loader to get this error go.

yarn remove style-loader


问:
open port 23 but not possible to access it
okay I just did a scan on the xiaomi repeater extender using nmap
and output like this:

nmap 192.168.90.8 -Pn -sV

```<code>Starting Nmap 7.92 ( https://nmap.org ) at 2022-01-19 15:08 WIB
Nmap scan report for 192.168.90.8
Host is up (0.048s latency).
Not shown: 999 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
23/tcp open  telnet?
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port23-TCP:V=7.92%I=7%D=1/19%Time=61E7C71F%P=x86_64-pc-linux-gnu%r(NULL
SF:,9,"Login\x20as:")%r(GenericLines,41,"Login\x20as:Invalid\x20User\x20Na
SF:me\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:")%r(tn3270,18
SF:,"Login\x20as:\xff\xfd\x18\xff\xfd\x19\xff\xfb\x19\xff\xfd\0\xff\xfb\0"
SF:)%r(GetRequest,41,"Login\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:I
SF:nvalid\x20User\x20Name\r\nLogin\x20as:")%r(HTTPOptions,41,"Login\x20as:
SF:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin
SF:\x20as:")%r(RTSPRequest,41,"Login\x20as:Invalid\x20User\x20Name\r\nLogi
SF:n\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:")%r(RPCCheck,9,"Login\x
SF:20as:")%r(DNSVersionBindReqTCP,9,"Login\x20as:")%r(DNSStatusRequestTCP,
SF:9,"Login\x20as:")%r(Help,25,"Login\x20as:Invalid\x20User\x20Name\r\nLog
SF:in\x20as:")%r(SSLSessionReq,9,"Login\x20as:")%r(TerminalServerCookie,9,
SF:"Login\x20as:")%r(TLSSessionReq,9,"Login\x20as:")%r(Kerberos,9,"Login\x
SF:20as:")%r(SMBProgNeg,9,"Login\x20as:")%r(X11Probe,9,"Login\x20as:")%r(F
SF:ourOhFourRequest,41,"Login\x20as:Invalid\x20User\x20Name\r\nLogin\x20as
SF::Invalid\x20User\x20Name\r\nLogin\x20as:")%r(LPDString,25,"Login\x20as:
SF:Invalid\x20User\x20Name\r\nLogin\x20as:")%r(LDAPSearchReq,41,"Login\x20
SF:as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLo
SF:gin\x20as:")%r(LDAPBindReq,9,"Login\x20as:")%r(SIPOptions,13D,"Login\x2
SF:0as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nL
SF:ogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Na
SF:me\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20Use
SF:r\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid
SF:\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:
SF:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin
SF:\x20as:")%r(LANDesk-RC,9,"Login\x20as:")%r(TerminalServer,9,"Login\x20a
SF:s:")%r(NCP,9,"Login\x20as:")%r(NotesRPC,9,"Login\x20as:")%r(JavaRMI,9,"
SF:Login\x20as:")%r(WMSRequest,9,"Login\x20as:")%r(oracle-tns,9,"Login\x20
SF:as:")%r(ms-sql-s,9,"Login\x20as:")%r(afp,9,"Login\x20as:")%r(giop,9,"Lo
SF:gin\x20as:");

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 120.76 seconds
</code>```

then when I want to access the open port, which is port 23/telnet I can't press enter in the login field, and this is what I get:

```<code>telnet 192.168.90.8
Trying 192.168.90.8...
Connected to 192.168.90.8.
Escape character is '^]'.
Login as:admin^M
</code>```

you can see above that I tried to press the enter key after filling in the admin login, but instead it came out

```<code> ^M
</code>```

is there something wrong with the scan?
Or is that port not accessible?

答:
use python</p>
```<code>Python 3.9.10 (main, Jan 15 2022, 11:40:36)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from telnetlib import Telnet
>>> Telnet('192.168.90.8',23).interact()
</code>```

Body:
okay I just did a scan on the xiaomi repeater extender using nmap
and output like this:

nmap 192.168.90.8 -Pn -sV

Starting Nmap 7.92 ( https://nmap.org ) at 2022-01-19 15:08 WIB
Nmap scan report for 192.168.90.8
Host is up (0.048s latency).
Not shown: 999 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
23/tcp open  telnet?
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port23-TCP:V=7.92%I=7%D=1/19%Time=61E7C71F%P=x86_64-pc-linux-gnu%r(NULL
SF:,9,"Login\x20as:")%r(GenericLines,41,"Login\x20as:Invalid\x20User\x20Na
SF:me\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:")%r(tn3270,18
SF:,"Login\x20as:\xff\xfd\x18\xff\xfd\x19\xff\xfb\x19\xff\xfd\0\xff\xfb\0"
SF:)%r(GetRequest,41,"Login\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:I
SF:nvalid\x20User\x20Name\r\nLogin\x20as:")%r(HTTPOptions,41,"Login\x20as:
SF:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin
SF:\x20as:")%r(RTSPRequest,41,"Login\x20as:Invalid\x20User\x20Name\r\nLogi
SF:n\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:")%r(RPCCheck,9,"Login\x
SF:20as:")%r(DNSVersionBindReqTCP,9,"Login\x20as:")%r(DNSStatusRequestTCP,
SF:9,"Login\x20as:")%r(Help,25,"Login\x20as:Invalid\x20User\x20Name\r\nLog
SF:in\x20as:")%r(SSLSessionReq,9,"Login\x20as:")%r(TerminalServerCookie,9,
SF:"Login\x20as:")%r(TLSSessionReq,9,"Login\x20as:")%r(Kerberos,9,"Login\x
SF:20as:")%r(SMBProgNeg,9,"Login\x20as:")%r(X11Probe,9,"Login\x20as:")%r(F
SF:ourOhFourRequest,41,"Login\x20as:Invalid\x20User\x20Name\r\nLogin\x20as
SF::Invalid\x20User\x20Name\r\nLogin\x20as:")%r(LPDString,25,"Login\x20as:
SF:Invalid\x20User\x20Name\r\nLogin\x20as:")%r(LDAPSearchReq,41,"Login\x20
SF:as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLo
SF:gin\x20as:")%r(LDAPBindReq,9,"Login\x20as:")%r(SIPOptions,13D,"Login\x2
SF:0as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nL
SF:ogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Na
SF:me\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20Use
SF:r\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid
SF:\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin\x20as:
SF:Invalid\x20User\x20Name\r\nLogin\x20as:Invalid\x20User\x20Name\r\nLogin
SF:\x20as:")%r(LANDesk-RC,9,"Login\x20as:")%r(TerminalServer,9,"Login\x20a
SF:s:")%r(NCP,9,"Login\x20as:")%r(NotesRPC,9,"Login\x20as:")%r(JavaRMI,9,"
SF:Login\x20as:")%r(WMSRequest,9,"Login\x20as:")%r(oracle-tns,9,"Login\x20
SF:as:")%r(ms-sql-s,9,"Login\x20as:")%r(afp,9,"Login\x20as:")%r(giop,9,"Lo
SF:gin\x20as:");

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 120.76 seconds

then when I want to access the open port, which is port 23/telnet I can't press enter in the login field, and this is what I get:

telnet 192.168.90.8
Trying 192.168.90.8...
Connected to 192.168.90.8.
Escape character is '^]'.
Login as:admin^M

you can see above that I tried to press the enter key after filling in the admin login, but instead it came out

 ^M

is there something wrong with the scan?
Or is that port not accessible?

Body:
use python

Python 3.9.10 (main, Jan 15 2022, 11:40:36)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from telnetlib import Telnet
>>> Telnet('192.168.90.8',23).interact()


问:
Dependency library points to device build
I've got an XCode 4 project that has an additional dependency project in it. The dependency project creates a static library I need for the major project.

I'm trying to add the library from the Target->Build Phases->Link Binary With Libraries, choosing the static library in my workspace.

Problem is every time I do that, the build settings "Library Search Paths" is appended a path to the build of the iphoneos build. When I try to compile for simulator, that file is ignored as it not meant for i386 architecture and the build fails.

I've been searching like mad, not understanding what I'm doing differently. Everywhere I look, it seems like XCode should be doing some magic to link simulator with simulator and device with device - But for me it always adds the specific path to either the device or simulator.

(I've tried using two targets to differ them, and that worked, but it's not an ideal solution at all. I have to change  2 targets everytime instead of 1.)

Hope I was understood,

pleeeaaaaase help :)

Oded.

答:
My colleague found the answer eventually -

In XCode 4 the default is to build all projects to a shared building folder. Me being fixated with XCode 3, switched it to the old method in which the build folder is in your project folder.

Turns out switching XCode to build in a single unique place, allowed the magic to happen to and to the corresponding builds be built together. I've been told it's exactly what it's meant for, but have no link to the reference.

XCode Menu -> Preferences -> Locations -> Build Location:
- Place build in derived data location (recommended)
- Unique subfolder

Cheers,
Oded.


问:
Align dataframe columns according to row values
I have a textfile which i read in as a dataframe where the first row and then every second row, i.e. row 1,3,5 and so on contains a quality score.

Then every second row starting from row 2 contains a count of that given quality score, i.e. row 2,4,6

As an example

```<code>      V3       V4       V5       V6       V7       V8       V9      V10       V11       V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25
1      2       18       25       27       28       30       31       32        33        34  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
2     501   14528     21512    27892   30462   34933.     39589    76712    205029  499660 NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
.
.
.
199     2      13      14       15       16       21       22       23       24       25       26       27       28       29       30       31       32       33       34       35        36        37        38
200  967 5361 9064 24743 24853 25897 26115 30293 31068 33030 35463 37838 40588 45483 45877 51572 52497 59295 72964 85302 102564 125874 499660
</code>```

In line 1 the quality values range between 2 - 34. Line 199 are another line with qualities and it ranges from 2 - 38 with values between 2 and 18, namely 13,14,15,16 which is not present in line 1. Similar line 199 doesn't contain quality value 18 present in line 1.
And as can be seen, column "V4" contains the quality 18 in line 1 and 13 in line 199.

So my issue is I would like to align the counts (so every second line, starting from line 2) according to the qualities (in the line above), such that all columns contain the same quality score.

I would like something along these lines (just showing a few columns)

```<code>1      2       13      14       15       16       18 . . .
2     501      NA      NA       NA       NA     14528
.
.
.
199     2       13      14       15       16       18 . . .
200   967      5361    9064    24743    24853      NA
</code>```

I have read about the apply functions, but I have no idea how to attack this specific problem, and I cannot really find any similar questions

```<code>> dput(head(Occurence, 20))
structure(list(V3 = c(2L, 501540L, 18L, 14942133L, 18L, 15333830L,
15L, 14534463L, 2L, 67356L, 2L, 21283L, 2L, 693L, 2L, 11591L,
2L, 10735L, 2L, 1357L), V4 = c(18L, 14528493L, 25L, 20570845L,
25L, 20770770L, 25L, 19772180L, 15L, 14549162L, 14L, 3733153L,
14L, 3314490L, 14L, 2954483L, 14L, 2582053L, 14L, 2422585L),
    V5 = c(25L, 21512178L, 27L, 26698655L, 27L, 26229231L, 27L,
    24871325L, 25L, 19678213L, 15L, 5418224L, 15L, 4892911L,
    15L, 4475734L, 15L, 3959680L, 15L, 3783535L), V6 = c(27L,
    27892666L, 28L, 30553444L, 28L, 30238008L, 28L, 28881657L,
    27L, 24509361L, 16L, 15734383L, 16L, 15922208L, 16L, 15292678L,
    16L, 14754664L, 16L, 14825386L), V7 = c(28L, 30462569L, 30L,
    35551769L, 30L, 35425235L, 30L, 34011574L, 28L, 28470507L,
    24L, 15735995L, 24L, 15936954L, 24L, 15328991L, 24L, 14803665L,
    24L, 14894503L), V8 = c(30L, 34933739L, 31L, 43332862L, 31L,
    44100550L, 31L, 43008899L, 30L, 33618696L, 26L, 21724499L,
    25L, 15937493L, 25L, 15330548L, 25L, 14813003L, 25L, 14912047L
    ), V9 = c(31L, 39589167L, 32L, 74856672L, 32L, 74198843L,
    32L, 73167369L, 31L, 42602404L, 27L, 22451599L, 26L, 20931741L,
    26L, 19685005L, 26L, 18821729L, 26L, 18689699L), V10 = c(32L,
    76712990L, 33L, 188084794L, 33L, 182503127L, 33L, 179841094L,
    32L, 72983555L, 28L, 27361625L, 27L, 21586370L, 27L, 20346737L,
    27L, 19445796L, 27L, 19328901L), V11 = c(33L, 205029125L,
    34L, 499660772L, 34L, 499660772L, 34L, 499660772L, 33L, 181252829L,
    29L, 32594176L, 28L, 24463465L, 28L, 22726939L, 28L, 21562094L,
    28L, 21239287L), V12 = c(34L, 499660772L, NA, NA, NA, NA,
    NA, NA, 34L, 499660772L, 30L, 37445130L, 29L, 28923072L,
    29L, 26758396L, 29L, 25534527L, 29L, 25347792L), V13 = c(NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, 31L, 43590775L, 30L,
    30982652L, 30L, 28653896L, 30L, 27153473L, 30L, 26651137L
    ), V14 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 32L, 44152908L,
    31L, 35625787L, 31L, 33029196L, 31L, 31207384L, 31L, 30528291L
    ), V15 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 33L, 50873330L,
    32L, 36061896L, 32L, 33422769L, 32L, 31553033L, 32L, 30862392L
    ), V16 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 34L, 63906416L,
    33L, 42006699L, 33L, 38759787L, 33L, 36348747L, 33L, 35496033L
    ), V17 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 35L, 72684296L,
    34L, 51548498L, 34L, 46689337L, 34L, 43680971L, 34L, 42730430L
    ), V18 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 36L, 105169117L,
    35L, 59677004L, 35L, 53868900L, 35L, 50076642L, 35L, 48912839L
    ), V19 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 37L, 171796607L,
    36L, 75648002L, 36L, 66246037L, 36L, 61636771L, 36L, 60176054L
    ), V20 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 38L, 499660772L,
    37L, 113735617L, 37L, 90246995L, 37L, 82047368L, 37L, 79133165L
    ), V21 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    38L, 499660772L, 38L, 499660772L, 38L, 499660772L, 38L, 499660772L
    ), V22 = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_), V23 = c(NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_), V24 = c(NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), V25 = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_)), row.names = c(NA,
20L), class = "data.frame")
</code>```

答:
This answer makes heavy use of the tidyverse framework. The operations performed in order to transform the example are the following:

assign a pairID to pairs of consecutive rows using a simple function of row_number

split the dataframe according to pairID into a named list of dataframes with names taken from pairID

transform each dataframe and collect them into one big dataframe

sort and reshape the dataframe pivoting on Quality

library(dplyr)
library(tidyr)
library(purrr)

df |>
  mutate(pairID = 3 + 2*as.integer((row_number() - 1) /2)) %>%
  {split(select(., -pairID), pull(., pairID))} %>%
  purrr::map_dfr(~{data.frame(Quality = unlist(.x[1,]),
                              Occurrence = unlist(.x[2,]))},
                 .id = "pairID") %>%
  na.omit() %>%
  arrange(as.integer(pairID)) %>%
  pivot_wider(values_from = Occurrence,
              names_from = pairID,
              names_prefix = "Row") %>%
  arrange(Quality) |>
  as.data.frame()

##>   Quality      Row3      Row5      Row7      Row9     Row11     Row13
##>1        2    501540        NA        NA        NA     67356     21283
##>2       14        NA        NA        NA        NA        NA   3733153
##>3       15        NA        NA        NA  14534463  14549162   5418224
##>4       16        NA        NA        NA        NA        NA  15734383
##>5       18  14528493  14942133  15333830        NA        NA        NA
##>6       24        NA        NA        NA        NA        NA  15735995
##>7       25  21512178  20570845  20770770  19772180  19678213        NA
##>8       26        NA        NA        NA        NA        NA  21724499
##>9       27  27892666  26698655  26229231  24871325  24509361  22451599
##>10      28  30462569  30553444  30238008  28881657  28470507  27361625
##>11      29        NA        NA        NA        NA        NA  32594176
##>12      30  34933739  35551769  35425235  34011574  33618696  37445130
##>13      31  39589167  43332862  44100550  43008899  42602404  43590775
##>14      32  76712990  74856672  74198843  73167369  72983555  44152908
##>15      33 205029125 188084794 182503127 179841094 181252829  50873330
##>16      34 499660772 499660772 499660772 499660772 499660772  63906416
##>17      35        NA        NA        NA        NA        NA  72684296
##>18      36        NA        NA        NA        NA        NA 105169117
##>19      37        NA        NA        NA        NA        NA 171796607
##>20      38        NA        NA        NA        NA        NA 499660772
##>       Row15     Row17     Row19     Row21
##>1        693     11591     10735      1357
##>2    3314490   2954483   2582053   2422585
##>3    4892911   4475734   3959680   3783535
##>4   15922208  15292678  14754664  14825386
##>5         NA        NA        NA        NA
##>6   15936954  15328991  14803665  14894503
##>7   15937493  15330548  14813003  14912047
##>8   20931741  19685005  18821729  18689699
##>9   21586370  20346737  19445796  19328901
##>10  24463465  22726939  21562094  21239287
##>11  28923072  26758396  25534527  25347792
##>12  30982652  28653896  27153473  26651137
##>13  35625787  33029196  31207384  30528291
##>14  36061896  33422769  31553033  30862392
##>15  42006699  38759787  36348747  35496033
##>16  51548498  46689337  43680971  42730430
##>17  59677004  53868900  50076642  48912839
##>18  75648002  66246037  61636771  60176054
##>19 113735617  90246995  82047368  79133165
##>20 499660772 499660772 499660772 499660772

```

Body:
I have a textfile which i read in as a dataframe where the first row and then every second row, i.e. row 1,3,5 and so on contains a quality score.

Then every second row starting from row 2 contains a count of that given quality score, i.e. row 2,4,6

As an example

      V3       V4       V5       V6       V7       V8       V9      V10       V11       V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25
1      2       18       25       27       28       30       31       32        33        34  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
2     501   14528     21512    27892   30462   34933.     39589    76712    205029  499660 NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
.
.
.
199     2      13      14       15       16       21       22       23       24       25       26       27       28       29       30       31       32       33       34       35        36        37        38
200  967 5361 9064 24743 24853 25897 26115 30293 31068 33030 35463 37838 40588 45483 45877 51572 52497 59295 72964 85302 102564 125874 499660

In line 1 the quality values range between 2 - 34. Line 199 are another line with qualities and it ranges from 2 - 38 with values between 2 and 18, namely 13,14,15,16 which is not present in line 1. Similar line 199 doesn't contain quality value 18 present in line 1.
And as can be seen, column "V4" contains the quality 18 in line 1 and 13 in line 199.

So my issue is I would like to align the counts (so every second line, starting from line 2) according to the qualities (in the line above), such that all columns contain the same quality score.

I would like something along these lines (just showing a few columns)

1      2       13      14       15       16       18 . . .
2     501      NA      NA       NA       NA     14528
.
.
.
199     2       13      14       15       16       18 . . .
200   967      5361    9064    24743    24853      NA

I have read about the apply functions, but I have no idea how to attack this specific problem, and I cannot really find any similar questions

> dput(head(Occurence, 20))
structure(list(V3 = c(2L, 501540L, 18L, 14942133L, 18L, 15333830L,
15L, 14534463L, 2L, 67356L, 2L, 21283L, 2L, 693L, 2L, 11591L,
2L, 10735L, 2L, 1357L), V4 = c(18L, 14528493L, 25L, 20570845L,
25L, 20770770L, 25L, 19772180L, 15L, 14549162L, 14L, 3733153L,
14L, 3314490L, 14L, 2954483L, 14L, 2582053L, 14L, 2422585L),
    V5 = c(25L, 21512178L, 27L, 26698655L, 27L, 26229231L, 27L,
    24871325L, 25L, 19678213L, 15L, 5418224L, 15L, 4892911L,
    15L, 4475734L, 15L, 3959680L, 15L, 3783535L), V6 = c(27L,
    27892666L, 28L, 30553444L, 28L, 30238008L, 28L, 28881657L,
    27L, 24509361L, 16L, 15734383L, 16L, 15922208L, 16L, 15292678L,
    16L, 14754664L, 16L, 14825386L), V7 = c(28L, 30462569L, 30L,
    35551769L, 30L, 35425235L, 30L, 34011574L, 28L, 28470507L,
    24L, 15735995L, 24L, 15936954L, 24L, 15328991L, 24L, 14803665L,
    24L, 14894503L), V8 = c(30L, 34933739L, 31L, 43332862L, 31L,
    44100550L, 31L, 43008899L, 30L, 33618696L, 26L, 21724499L,
    25L, 15937493L, 25L, 15330548L, 25L, 14813003L, 25L, 14912047L
    ), V9 = c(31L, 39589167L, 32L, 74856672L, 32L, 74198843L,
    32L, 73167369L, 31L, 42602404L, 27L, 22451599L, 26L, 20931741L,
    26L, 19685005L, 26L, 18821729L, 26L, 18689699L), V10 = c(32L,
    76712990L, 33L, 188084794L, 33L, 182503127L, 33L, 179841094L,
    32L, 72983555L, 28L, 27361625L, 27L, 21586370L, 27L, 20346737L,
    27L, 19445796L, 27L, 19328901L), V11 = c(33L, 205029125L,
    34L, 499660772L, 34L, 499660772L, 34L, 499660772L, 33L, 181252829L,
    29L, 32594176L, 28L, 24463465L, 28L, 22726939L, 28L, 21562094L,
    28L, 21239287L), V12 = c(34L, 499660772L, NA, NA, NA, NA,
    NA, NA, 34L, 499660772L, 30L, 37445130L, 29L, 28923072L,
    29L, 26758396L, 29L, 25534527L, 29L, 25347792L), V13 = c(NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, 31L, 43590775L, 30L,
    30982652L, 30L, 28653896L, 30L, 27153473L, 30L, 26651137L
    ), V14 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 32L, 44152908L,
    31L, 35625787L, 31L, 33029196L, 31L, 31207384L, 31L, 30528291L
    ), V15 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 33L, 50873330L,
    32L, 36061896L, 32L, 33422769L, 32L, 31553033L, 32L, 30862392L
    ), V16 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 34L, 63906416L,
    33L, 42006699L, 33L, 38759787L, 33L, 36348747L, 33L, 35496033L
    ), V17 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 35L, 72684296L,
    34L, 51548498L, 34L, 46689337L, 34L, 43680971L, 34L, 42730430L
    ), V18 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 36L, 105169117L,
    35L, 59677004L, 35L, 53868900L, 35L, 50076642L, 35L, 48912839L
    ), V19 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 37L, 171796607L,
    36L, 75648002L, 36L, 66246037L, 36L, 61636771L, 36L, 60176054L
    ), V20 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 38L, 499660772L,
    37L, 113735617L, 37L, 90246995L, 37L, 82047368L, 37L, 79133165L
    ), V21 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    38L, 499660772L, 38L, 499660772L, 38L, 499660772L, 38L, 499660772L
    ), V22 = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_), V23 = c(NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_), V24 = c(NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), V25 = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_)), row.names = c(NA,
20L), class = "data.frame")


问:
i want to extract specific section from resume, CVs
I want to extract a specific section from a resume or CV...like education, experience. I did this but when education or any other section is written last in CV then it won't work.

```<code>` def extract_experience(ex_cl):   #create function of experience
     doc= fitz.open(ex_cl)   #open pdf file
     text=""             #crate string
     for page in doc:
     text= text + str(page.getText())  #conver pdf text into string
     words= nltk.word_tokenize(text)  #convert all text of CV into words

     start = 0
     end= 0

     #manually create [exp_list] which contain all CVs titles are possibel [not including
     experience word](lan= german and English)

     exp_list=["FÄHIGKEITEN","KENNTNISSE","AUSBILDUNG","Ausbildung", "BILDUNG", "Bildung",
                "Hobbies","HOBBIES","Personliche","Fahigkeiten",
                "Kenntnisse","Ehrenamtliches","Engagement",
                 "Sprachen","SPRACHEN","EHRENAMTLICHES",
                  "ENGAGEEMENT","EDUCATION" ,"Education","Hochschul",
                    "HOCHSCHUL","Studium","STUDIUM","Sprachkurse","Computerkenntnisse",
                  "SPRACHEN","SPRACHKURSE","COMPUTERKENNTNISSE",
           "AWARDS","Awards","PERSONAL","Personal","Information", "INFORMATION",
           "SKILLS","Skills","SKILL","Skill",'Soziales']

     #manually create  [exp] list which contain experience title and also synonym words of
     experiance word

     exp=['Erfahrung' ,'Laufbahn','ERFAHRUNG' ," Erfahrungen" ,'LAUFBAHN','Praktische',

          'PRAKTISCHE','ERFAHRUNGEN','Praktika','PRAKTIKA' ,
         'Berufserfahrung' ,'EXPERIENCE','Experience' ,'BERÜFSERFAHRUNG','Berufserfahrung']

     for vari in words:        # Match experience word or synonym word from CV and manually
                                                         created list[exp]
        if vari in exp:         # if match then find index of that word
          st=words.index(vari)
          start= st+1           #(st+1)for take next word
                            # get index of experience word of CV
          i = start             #give another variable(i)
     for j in words:                          #create for loop
        if words[i]  not in exp_list:   #if  start index is not in [exp_list(without
                                                             experience
                                                                                word)]
           i += 1                        #then take next index untill it match the word
                                                                       of[exp_list]
           end= start+(i-start)               # find end index

      f_list=[]  #create list
      for item in words[start:end]: #give slicing for take start index and end index
         f_list.append(item)  #append into list
      stringlist = ' '.join(f_list )  #convert into string

      return stringlist

extract_experience('020.pdf')
</code>```

`

答:
You can use Apache Tika to extract the text from the pdf first. It helps collate the text correctly. But to extract the sections will require some dirty code.

Something I'd try is to extract sections based on multiple newline (/n/n or more). A dirtier route would be to cut out sections based on heuristics like

create of list of possible title sections

loop  through the text

if title section:

start counting from that index up until it meets another section title capitalised or in upper case (this helps avoid cases like skills vs Skills or SKILLS)
Like I mentioned - dirty

A probably cleaner approach is to use NER (Named Entity Recognition) with SpaCy. But you'll have to create a dataset of CVs and manually label each section.

See this repo using NER to extract information needed

Body:
I want to extract a specific section from a resume or CV...like education, experience. I did this but when education or any other section is written last in CV then it won't work.

` def extract_experience(ex_cl):   #create function of experience
     doc= fitz.open(ex_cl)   #open pdf file
     text=""             #crate string
     for page in doc:
     text= text + str(page.getText())  #conver pdf text into string
     words= nltk.word_tokenize(text)  #convert all text of CV into words

     start = 0
     end= 0

     #manually create [exp_list] which contain all CVs titles are possibel [not including
     experience word](lan= german and English)

     exp_list=["FÄHIGKEITEN","KENNTNISSE","AUSBILDUNG","Ausbildung", "BILDUNG", "Bildung",
                "Hobbies","HOBBIES","Personliche","Fahigkeiten",
                "Kenntnisse","Ehrenamtliches","Engagement",
                 "Sprachen","SPRACHEN","EHRENAMTLICHES",
                  "ENGAGEEMENT","EDUCATION" ,"Education","Hochschul",
                    "HOCHSCHUL","Studium","STUDIUM","Sprachkurse","Computerkenntnisse",
                  "SPRACHEN","SPRACHKURSE","COMPUTERKENNTNISSE",
           "AWARDS","Awards","PERSONAL","Personal","Information", "INFORMATION",
           "SKILLS","Skills","SKILL","Skill",'Soziales']

     #manually create  [exp] list which contain experience title and also synonym words of
     experiance word

     exp=['Erfahrung' ,'Laufbahn','ERFAHRUNG' ," Erfahrungen" ,'LAUFBAHN','Praktische',

          'PRAKTISCHE','ERFAHRUNGEN','Praktika','PRAKTIKA' ,
         'Berufserfahrung' ,'EXPERIENCE','Experience' ,'BERÜFSERFAHRUNG','Berufserfahrung']

     for vari in words:        # Match experience word or synonym word from CV and manually
                                                         created list[exp]
        if vari in exp:         # if match then find index of that word
          st=words.index(vari)
          start= st+1           #(st+1)for take next word
                            # get index of experience word of CV
          i = start             #give another variable(i)
     for j in words:                          #create for loop
        if words[i]  not in exp_list:   #if  start index is not in [exp_list(without
                                                             experience
                                                                                word)]
           i += 1                        #then take next index untill it match the word
                                                                       of[exp_list]
           end= start+(i-start)               # find end index

      f_list=[]  #create list
      for item in words[start:end]: #give slicing for take start index and end index
         f_list.append(item)  #append into list
      stringlist = ' '.join(f_list )  #convert into string

      return stringlist

extract_experience('020.pdf')

`


问:
npm ERR! 403 403 Forbidden npm publish
I try to publish public package on npm but I have this error

```<code>npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@clem_b%2fweather - Forbidden
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy, or
npm ERR! 403 on a server you do not have access to.
</code>```

So in first watch my package.jsonbelow.

{
  "name": "@clem_b/weather",
  "version": "1.0.6",
  "description": "weather cli",
  "main": "build/main.js",
  "types": "build/main.d.ts",
  "homepage": "https://github.com/ClementBolin/weatherCLI#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ClementBolin/weatherCLI.git"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rimraf ./build && tsc",
    "start": "npm run build && node build/mai.js"
  },
  "bin": {
    "app": "bin/weatherCLI"
  },
  "keywords": [
    "weather",
    "today",
    "rain",
    "sun"
  ],
  "author": "clem_b",
  "license": "MIT",
  "devDependencies": {
    "@types/minimist": "^1.2.0",
    "@types/node": "^14.14.6",
    "@types/oauth": "^0.9.1",
    "@types/ora": "^3.2.0",
    "rimraf": "^3.0.2",
    "tslint": "^6.1.3",
    "typescript": "^4.0.5"
  },
  "prepublish": "npm run build",
  "dependencies": {
    "minimist": "^1.2.5",
    "oauth": "^0.9.15",
    "ora": "^0.3.0"
  }
}
```

So after end to write my code, I decide to publish my code on npm, so I create npm account, I use npm loginfor connect to my account. After this I run the following command npm publish --access publicand I have error write in top.
I search on many topics, but I don't find solution

答:
In npm profile, in ACCOUNT section, you must activate 2FA and after select "Enabled for authorization and publishing" inside of 2FA options.

If already do this, verify if your project has the same name of another project registered. In this case if has, just change the name.

Title: npm ERR! 403 403 Forbidden npm publish

Body:
I try to publish public package on npm but I have this error

npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@clem_b%2fweather - Forbidden
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy, or
npm ERR! 403 on a server you do not have access to.

So in first watch my package.jsonbelow.

{
  "name": "@clem_b/weather",
  "version": "1.0.6",
  "description": "weather cli",
  "main": "build/main.js",
  "types": "build/main.d.ts",
  "homepage": "https://github.com/ClementBolin/weatherCLI#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ClementBolin/weatherCLI.git"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rimraf ./build && tsc",
    "start": "npm run build && node build/mai.js"
  },
  "bin": {
    "app": "bin/weatherCLI"
  },
  "keywords": [
    "weather",
    "today",
    "rain",
    "sun"
  ],
  "author": "clem_b",
  "license": "MIT",
  "devDependencies": {
    "@types/minimist": "^1.2.0",
    "@types/node": "^14.14.6",
    "@types/oauth": "^0.9.1",
    "@types/ora": "^3.2.0",
    "rimraf": "^3.0.2",
    "tslint": "^6.1.3",
    "typescript": "^4.0.5"
  },
  "prepublish": "npm run build",
  "dependencies": {
    "minimist": "^1.2.5",
    "oauth": "^0.9.15",
    "ora": "^0.3.0"
  }
}

So after end to write my code, I decide to publish my code on npm, so I create npm account, I use npm loginfor connect to my account. After this I run the following command npm publish --access publicand I have error write in top.
I search on many topics, but I don't find solution


问:
Rotate a batch of images using `scipy.ndimage.interpolation.rotate`
Let's suppose that X is a numpy.ndarray tensor that holds a set of color images. For instance, X's shape is (100, 3, 32, 32); i.e., we have 100 32x32 rgb images (such as those provided by the CIFAR dataset).

I want to rotate the images in X and I found out that this could be done using the scipy.ndimage.interpolation.rotate function of scipy.

However, I can do it correctly only for a single image and a single color channel each time, while I would like to apply the function for all images and all color channels at once.

What I tried and it works so far is the following:

```<code>import scipy.ndimage.interpolation

image = X[0,0,:,:]
rotated_image = scipy.ndimage.interpolation.rotate(input=image, angle=45, reshape=False)
</code>```

but what I want to do, which could look like this

```<code>X_rot = scipy.ndimage.interpolation.rotate(input=X, angle=45, reshape=False)
</code>```

does not work.

Is there any way to apply scipy.ndimage.interpolation.rotate for a batch of images like the numpy.ndarray tensor X?

In any case, is there any better way to rotate a batch of images (stored in a numpy.ndarray) efficiently?

答:
If you want a one-liner,

```<code>import scipy.ndimage.interpolation as intrp

rotated_imgs = [intrp.rotate(input=img, angle=45, reshape=False) for img in X]
</code>```

assumed your X has the more standard shape (n_images, w, h, color_channels).

If you want to get your hands on matrices, I suggest you to generate your rotation matrix with cv2.getRotationMatrix2D, replicate/stack it along the first axis, and then apply it to your X, but it can get complicated without cv2.warpAffine, which takes a single image as input.

Body:
Let's suppose that X is a numpy.ndarray tensor that holds a set of color images. For instance, X's shape is (100, 3, 32, 32); i.e., we have 100 32x32 rgb images (such as those provided by the CIFAR dataset).

I want to rotate the images in X and I found out that this could be done using the scipy.ndimage.interpolation.rotate function of scipy.

However, I can do it correctly only for a single image and a single color channel each time, while I would like to apply the function for all images and all color channels at once.

What I tried and it works so far is the following:

import scipy.ndimage.interpolation

image = X[0,0,:,:]
rotated_image = scipy.ndimage.interpolation.rotate(input=image, angle=45, reshape=False)

but what I want to do, which could look like this

X_rot = scipy.ndimage.interpolation.rotate(input=X, angle=45, reshape=False)

does not work.

Is there any way to apply scipy.ndimage.interpolation.rotate for a batch of images like the numpy.ndarray tensor X?

In any case, is there any better way to rotate a batch of images (stored in a numpy.ndarray) efficiently?

Body:
If you want a one-liner,

import scipy.ndimage.interpolation as intrp

rotated_imgs = [intrp.rotate(input=img, angle=45, reshape=False) for img in X]

assumed your X has the more standard shape (n_images, w, h, color_channels).

If you want to get your hands on matrices, I suggest you to generate your rotation matrix with cv2.getRotationMatrix2D, replicate/stack it along the first axis, and then apply it to your X, but it can get complicated without cv2.warpAffine, which takes a single image as input.


问:
Custom CI Directory for gitlab-runner
I have a project on gitlab that uses a custom CI/CD directory like so:

```<code>my-project/
├─ .ci/
│  ├─ gitlab-ci.yml
│  ├─ local-ci.sh
├─ .git/
├─ my-project/
├─ tests/
</code>```

Where local-ci.sh is a script that invokes gitlab-runner on the pipeline in gitlab-ci.yml.

On gitlab you can identify a custom path for the gitlab-ci.yml file, so the pipeline works when I push to the remote repository. I'd like to run the same CI pipeline on my local machine using gitlab-runner and Docker before pushing to the remote repository.

The issue I'm running into is when I run the pieline locally, gitlab-runner expects the .git directory to be in the same directory as the gitlab-ci.yml script. Is there a way to configure where the git directory is when running gitlab-runner?

Specifically, from this command (Linting is a stage of the pipeline):

```<code>gitlab-runner exec docker Linting
</code>```

I get this error:

```<code>fatal: '<absolute path>/my-project/.ci' does not appear to be a git repository
fatal: Could not read from remote repository.
</code>```

When I copy the gitlab-ci.yml script into the root directory, and change the working directory in the local-ci.sh script, the pipeline finishes without issue. Any thoughts?

EDIT: adding notes about the errors and copying the CI script.

答:
I think the easiest solution would be to add a file my-project/gitlab-ci.yml which just includes the real gitlab-ci.yml.

include:
    - local: .ci/gitlab-ci.yml
```
<p>This should solve your problem, because</p>
<ul>
<li>gitlab-ci will find your settings</li>
<li>technically the the <code>gitlab-ci.yml</code> and the <code>.git</code> directory are in the same directory, so <code>gitlab-runner</code> should be fine.</li>
<li>all of your real ci-config is still in one directory</li>
</ul>
<p>You might even get away with using an symbolic link instead:</p>
<pre class="lang-sh prettyprint-override"><code>ln -s .ci/gitlab-ci.yml gitlab-ci.yml
</code>```

This would arguably be even cleaner (because there is no code added to your reposity, just a link). You'd have to try if all of your tools can work with symbolic links (I suspect they can).

Title: Custom CI Directory for gitlab-runner

Body:
I have a project on gitlab that uses a custom CI/CD directory like so:

my-project/
├─ .ci/
│  ├─ gitlab-ci.yml
│  ├─ local-ci.sh
├─ .git/
├─ my-project/
├─ tests/

Where local-ci.sh is a script that invokes gitlab-runner on the pipeline in gitlab-ci.yml.

On gitlab you can identify a custom path for the gitlab-ci.yml file, so the pipeline works when I push to the remote repository. I'd like to run the same CI pipeline on my local machine using gitlab-runner and Docker before pushing to the remote repository.

The issue I'm running into is when I run the pieline locally, gitlab-runner expects the .git directory to be in the same directory as the gitlab-ci.yml script. Is there a way to configure where the git directory is when running gitlab-runner?

Specifically, from this command (Linting is a stage of the pipeline):

gitlab-runner exec docker Linting

I get this error:

fatal: '<absolute path>/my-project/.ci' does not appear to be a git repository
fatal: Could not read from remote repository.

When I copy the gitlab-ci.yml script into the root directory, and change the working directory in the local-ci.sh script, the pipeline finishes without issue. Any thoughts?

EDIT: adding notes about the errors and copying the CI script.

Body:
I think the easiest solution would be to add a file my-project/gitlab-ci.yml which just includes the real gitlab-ci.yml.

include:
    - local: .ci/gitlab-ci.yml

This should solve your problem, because

gitlab-ci will find your settings

technically the the gitlab-ci.yml and the .git directory are in the same directory, so gitlab-runner should be fine.

all of your real ci-config is still in one directory

You might even get away with using an symbolic link instead:

ln -s .ci/gitlab-ci.yml gitlab-ci.yml

This would arguably be even cleaner (because there is no code added to your reposity, just a link). You'd have to try if all of your tools can work with symbolic links (I suspect they can).


问:
How to download all the images from the website in order, naming them from 1 to 1000
I want to download all the jpg and png images from the website but I need them to download in order and maybe if it's possible naming them during the download. For example download 1000 images, in order from 1 to 1000 with the name of order. For example 3rd picture will be named 3, or 300 picture will be named 300. I'm newbie in coding and I need this for my project. I can download them manually, but it will take time and I want to learn how to automate such process.</p>

答:
You may use the following approach</p>
```<code># IMPORT LIBRARIES
# choose libraries to be used

def download_images_from_url(url):
    count = 1  # initialize counter
    # loop

        # write code to download the image from website

        # write code to store it locally

        #  rename the image using count variable

    count+=1 #update counter

url = "https://www.website.com"
download_images_from_url(url)
</code>```

Body:
You may use the following approach

# IMPORT LIBRARIES
# choose libraries to be used

def download_images_from_url(url):
    count = 1  # initialize counter
    # loop

        # write code to download the image from website

        # write code to store it locally

        #  rename the image using count variable

    count+=1 #update counter

url = "https://www.website.com"
download_images_from_url(url)


问:
set a dynamically created bash variable
Good morning,
i need to dynamically change the name of a variable. I did some tests. my test script is this:

```<code>i=5
range5min=777
varname="range${i}min"
echo ${!varname}
#$`echo $varname`=555
$varname=555
echo $range5min
</code>```

I can access its content with:

```<code>echo $ {! Varname}
</code>```

But I can't set a dynamically created variable with a value, that is, I can't make the assignment of a value with the equal.
I tried both of these ways:

```<code>$ `echo $ varname` = 555
</code>```
```<code>$ varname = 555
</code>```

What I would like to do is create new variables inside a for, depending on how many loops the for expects.

答:
you can use printf:

```<code>printf -v "$varname" '%s' "555"
</code>```

Note, though, that this type of programming is not really recommended, since it makes code hard to read and understand.

An array or associative array might be more appropriate.

Title: set a dynamically created bash variable

Body:
Good morning,
i need to dynamically change the name of a variable. I did some tests. my test script is this:

i=5
range5min=777
varname="range${i}min"
echo ${!varname}
#$`echo $varname`=555
$varname=555
echo $range5min

I can access its content with:

echo $ {! Varname}

But I can't set a dynamically created variable with a value, that is, I can't make the assignment of a value with the equal.
I tried both of these ways:

$ `echo $ varname` = 555

$ varname = 555

What I would like to do is create new variables inside a for, depending on how many loops the for expects.

Body:
you can use printf:

printf -v "$varname" '%s' "555"

Note, though, that this type of programming is not really recommended, since it makes code hard to read and understand.

An array or associative array might be more appropriate.


问:
Could not create program address with signer seeds when creating a token account
I have a PDA and I'm trying to create a token account for it, using Solana Spl Associated Token Account(https://spl.solana.com/associated-token-account):

```<code>let (token_account_key, token_account_key_bump_seed) = Pubkey::find_program_address(&[&stake_info_bytes, &token_program_bytes, &mint_address_bytes], spl_associated_token_program.key);
</code>```

Now I'm trying to create the account:

```<code>        let account_rent = rent.minimum_balance(Account::LEN);

        let authority_signature_seeds = [&stake_info_bytes[..32], &token_program_bytes[..32], &mint_address_bytes[..32], &[token_account_key_bump_seed]];
        let signers = &[&authority_signature_seeds[..]];

        let create_ix = create_account(
            feepayer.key,
            token_account.key,
            account_rent,
            Account::LEN as u64,
            spl_associated_token_program.key
        );

        invoke_signed(&create_ix, &[
            spl_associated_token_program.clone(),
            feepayer.clone(),
            token_account.clone()
        ], signers);
</code>```

But I'm getting this error:

> Program returned error: Could not create program address with signer seeds: Provided seeds do not result in a valid address

答:
With PDAs, your program can only "sign" for PDAs generated using its program id.  In this case, your program is using the associated token account program as the program id, when it should be using itself.  So this should become:

```<code>let (token_account_key, token_account_key_bump_seed) = Pubkey::find_program_address(&[&stake_info_bytes, &token_program_bytes, &mint_address_bytes], my_program_id);
</code>```

Using your program's id as my_program_id, and then you would actually use this as:

```<code>let create_ix = create_account(
            feepayer.key,
            token_account.key,
            account_rent,
            Account::LEN as u64,
            spl_token_program.key
        );
invoke_signed(&create_ix, &[
            feepayer.clone(),
            token_account.clone()
        ], signers);
</code>```

Note: I'm assuming that you're trying to create a token account, which must be owned by the token program.

Otherwise, it would be possible to fake "signatures" for another program, which would be a huge security risk.  For example, associated token accounts must be signed and created by the associated token account program.

Body:
I have a PDA and I'm trying to create a token account for it, using Solana Spl Associated Token Account(https://spl.solana.com/associated-token-account):

let (token_account_key, token_account_key_bump_seed) = Pubkey::find_program_address(&[&stake_info_bytes, &token_program_bytes, &mint_address_bytes], spl_associated_token_program.key);

Now I'm trying to create the account:

        let account_rent = rent.minimum_balance(Account::LEN);

        let authority_signature_seeds = [&stake_info_bytes[..32], &token_program_bytes[..32], &mint_address_bytes[..32], &[token_account_key_bump_seed]];
        let signers = &[&authority_signature_seeds[..]];

        let create_ix = create_account(
            feepayer.key,
            token_account.key,
            account_rent,
            Account::LEN as u64,
            spl_associated_token_program.key
        );

        invoke_signed(&create_ix, &[
            spl_associated_token_program.clone(),
            feepayer.clone(),
            token_account.clone()
        ], signers);

But I'm getting this error:

> Program returned error: Could not create program address with signer seeds: Provided seeds do not result in a valid address

Body:
With PDAs, your program can only "sign" for PDAs generated using its program id.  In this case, your program is using the associated token account program as the program id, when it should be using itself.  So this should become:

let (token_account_key, token_account_key_bump_seed) = Pubkey::find_program_address(&[&stake_info_bytes, &token_program_bytes, &mint_address_bytes], my_program_id);

Using your program's id as my_program_id, and then you would actually use this as:

let create_ix = create_account(
            feepayer.key,
            token_account.key,
            account_rent,
            Account::LEN as u64,
            spl_token_program.key
        );
invoke_signed(&create_ix, &[
            feepayer.clone(),
            token_account.clone()
        ], signers);

Note: I'm assuming that you're trying to create a token account, which must be owned by the token program.

Otherwise, it would be possible to fake "signatures" for another program, which would be a huge security risk.  For example, associated token accounts must be signed and created by the associated token account program.


问:
SQL to deal with Duplicate Record Management
I have an Oracle database application which creates lists of duplicate records for people to review, with users being able to deduplcate, leave or mark the record as being different to each other (legitimate duplicates). I need to report on the number of records in this queue.
The challenge is the legitimate duplicates as these are held on a second table of data and are held as two rows for each pair marked up (a≠b). However as duplicate groups can contain a number of duplicates, and records could be marked up a being a legitimate duplicate more than once I need to somehow remove the records that are marked up as legitimate duplicates from all the other records in a candidate group. Hopefully that is making sense.

So a simplified view of the two tables would be:
Duplicate Candidates

```<code>Group   Key
Dup-1   123
Dup-1   234
Dup-2   123
Dup-2   345
Dup-2   567
Dup-3   234
Dup-3   567
Dup-4   123
Dup-4   567
Dup-4   235
</code>```

Legitimate Duplicates:

```<code>Group   Key
A       123
A       234
B       345
B       456
C       123
C       567
D       123
D       235
</code>```

The results I would like to return from this example would be:

Duplicate Candidates

```<code>Group   Key
Dup-2   123
Dup-2   345
Dup-2   567
Dup-3   234
Dup-3   567
Dup-4   567
Dup-4   235
</code>```

Dup-1 would not be returned as Legitimate Group A has both Keys, Dup-2 would be returned as while both Key 123 and 345 are marked up as legitimate duplicates they are not currently marked as different to each other. Dup-3 again should be returned as the two records are not marked as legitimate duplicates. Finally the row Dup-4 123 should not be returned as it is marked up as legitimate duplicate to both of the other records in the group, but they should be returned as they are not marked a legitimate duplicates of each other.

I really need to carry this out in SQL as I will feed this data into a reporting solution (Business Objects or Tablaux) directly. Is anyone able to give me a nudge in the right direction on this. Unfortunately our software is completely black box so I cannot reverse engineer this from the code that deals with this for users.

答:
Generate pairs of duplicate candidates using:

SELECT "GROUP",
       PRIOR key AS key1,
       key       AS key2
FROM   duplicate_candidates
WHERE  LEVEL = 2
CONNECT BY PRIOR "GROUP" = "GROUP"
AND    PRIOR key < key
```
<p>and pairs of legitimate candidates using:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT MIN(key), MAX(key)
FROM   legitimate_duplicates
GROUP BY "GROUP"
</code>```

Then you can find the duplicate pairs that are not in the legitimate candidate pairs and UNPIVOT the pairs and find the DISTINCT keys. In a single query:

SELECT DISTINCT
       "GROUP",
       key
FROM   (
  SELECT "GROUP",
         PRIOR key AS key1,
         key       AS key2
  FROM   duplicate_candidates
  WHERE  LEVEL = 2
  AND    (PRIOR key, key) NOT IN (SELECT MIN(key), MAX(key)
                                  FROM   legitimate_duplicates
                                  GROUP BY "GROUP")
  CONNECT BY PRIOR "GROUP" = "GROUP"
  AND    PRIOR key < key
)
UNPIVOT (key FOR id IN (key1, key2))
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE duplicate_candidates ("GROUP", Key) AS
SELECT 'Dup-1', 123 FROM DUAL UNION ALL
SELECT 'Dup-1', 234 FROM DUAL UNION ALL
SELECT 'Dup-2', 123 FROM DUAL UNION ALL
SELECT 'Dup-2', 345 FROM DUAL UNION ALL
SELECT 'Dup-2', 567 FROM DUAL UNION ALL
SELECT 'Dup-3', 234 FROM DUAL UNION ALL
SELECT 'Dup-3', 567 FROM DUAL UNION ALL
SELECT 'Dup-4', 123 FROM DUAL UNION ALL
SELECT 'Dup-4', 567 FROM DUAL UNION ALL
SELECT 'Dup-4', 235 FROM DUAL;

CREATE TABLE Legitimate_Duplicates ("GROUP", Key) AS
SELECT 'A', 123 FROM DUAL UNION ALL
SELECT 'A', 234 FROM DUAL UNION ALL
SELECT 'B', 345 FROM DUAL UNION ALL
SELECT 'B', 456 FROM DUAL UNION ALL
SELECT 'C', 123 FROM DUAL UNION ALL
SELECT 'C', 567 FROM DUAL UNION ALL
SELECT 'D', 123 FROM DUAL UNION ALL
SELECT 'D', 235 FROM DUAL;
</code>```

Note: GROUP is a reserved word and cannot be an unquoted identifier. It would be better to use a different name for the columns but you can use a quoted identifier (but its not best practice).

Outputs:

GROUP
KEY

Dup-2
123

Dup-2
345

Dup-2
567

Dup-3
234

Dup-3
567

Dup-4
235

Dup-4
567

db<>fiddle here

Body:
I have an Oracle database application which creates lists of duplicate records for people to review, with users being able to deduplcate, leave or mark the record as being different to each other (legitimate duplicates). I need to report on the number of records in this queue.
The challenge is the legitimate duplicates as these are held on a second table of data and are held as two rows for each pair marked up (a≠b). However as duplicate groups can contain a number of duplicates, and records could be marked up a being a legitimate duplicate more than once I need to somehow remove the records that are marked up as legitimate duplicates from all the other records in a candidate group. Hopefully that is making sense.

So a simplified view of the two tables would be:
Duplicate Candidates

Group   Key
Dup-1   123
Dup-1   234
Dup-2   123
Dup-2   345
Dup-2   567
Dup-3   234
Dup-3   567
Dup-4   123
Dup-4   567
Dup-4   235

Legitimate Duplicates:

Group   Key
A       123
A       234
B       345
B       456
C       123
C       567
D       123
D       235

The results I would like to return from this example would be:

Duplicate Candidates

Group   Key
Dup-2   123
Dup-2   345
Dup-2   567
Dup-3   234
Dup-3   567
Dup-4   567
Dup-4   235

Dup-1 would not be returned as Legitimate Group A has both Keys, Dup-2 would be returned as while both Key 123 and 345 are marked up as legitimate duplicates they are not currently marked as different to each other. Dup-3 again should be returned as the two records are not marked as legitimate duplicates. Finally the row Dup-4 123 should not be returned as it is marked up as legitimate duplicate to both of the other records in the group, but they should be returned as they are not marked a legitimate duplicates of each other.

I really need to carry this out in SQL as I will feed this data into a reporting solution (Business Objects or Tablaux) directly. Is anyone able to give me a nudge in the right direction on this. Unfortunately our software is completely black box so I cannot reverse engineer this from the code that deals with this for users.

Body:
Generate pairs of duplicate candidates using:

SELECT "GROUP",
       PRIOR key AS key1,
       key       AS key2
FROM   duplicate_candidates
WHERE  LEVEL = 2
CONNECT BY PRIOR "GROUP" = "GROUP"
AND    PRIOR key < key

and pairs of legitimate candidates using:

SELECT MIN(key), MAX(key)
FROM   legitimate_duplicates
GROUP BY "GROUP"

Then you can find the duplicate pairs that are not in the legitimate candidate pairs and UNPIVOT the pairs and find the DISTINCT keys. In a single query:

SELECT DISTINCT
       "GROUP",
       key
FROM   (
  SELECT "GROUP",
         PRIOR key AS key1,
         key       AS key2
  FROM   duplicate_candidates
  WHERE  LEVEL = 2
  AND    (PRIOR key, key) NOT IN (SELECT MIN(key), MAX(key)
                                  FROM   legitimate_duplicates
                                  GROUP BY "GROUP")
  CONNECT BY PRIOR "GROUP" = "GROUP"
  AND    PRIOR key < key
)
UNPIVOT (key FOR id IN (key1, key2))

Which, for the sample data:

CREATE TABLE duplicate_candidates ("GROUP", Key) AS
SELECT 'Dup-1', 123 FROM DUAL UNION ALL
SELECT 'Dup-1', 234 FROM DUAL UNION ALL
SELECT 'Dup-2', 123 FROM DUAL UNION ALL
SELECT 'Dup-2', 345 FROM DUAL UNION ALL
SELECT 'Dup-2', 567 FROM DUAL UNION ALL
SELECT 'Dup-3', 234 FROM DUAL UNION ALL
SELECT 'Dup-3', 567 FROM DUAL UNION ALL
SELECT 'Dup-4', 123 FROM DUAL UNION ALL
SELECT 'Dup-4', 567 FROM DUAL UNION ALL
SELECT 'Dup-4', 235 FROM DUAL;

CREATE TABLE Legitimate_Duplicates ("GROUP", Key) AS
SELECT 'A', 123 FROM DUAL UNION ALL
SELECT 'A', 234 FROM DUAL UNION ALL
SELECT 'B', 345 FROM DUAL UNION ALL
SELECT 'B', 456 FROM DUAL UNION ALL
SELECT 'C', 123 FROM DUAL UNION ALL
SELECT 'C', 567 FROM DUAL UNION ALL
SELECT 'D', 123 FROM DUAL UNION ALL
SELECT 'D', 235 FROM DUAL;

Note: GROUP is a reserved word and cannot be an unquoted identifier. It would be better to use a different name for the columns but you can use a quoted identifier (but its not best practice).

Outputs:

GROUP
KEY

Dup-2
123

Dup-2
345

Dup-2
567

Dup-3
234

Dup-3
567

Dup-4
235

Dup-4
567

db<>fiddle here


问:
Resize image grid
I have a gallery with a image grid that I cannot resize to auto cut the images with the same format in the browser and on phone.

5th element with bigger height than normal

CSS

```<code>.grid figure {
    position: relative;

    overflow: hidden;

    background: #3085a3;
    text-align: center;
    cursor: pointer;
}

.grid figure img {
    position: relative;
    display: block;
    max-width: 100%;
    opacity: 0.8;
}
</code>```

HTML

```<code><li class="grid">
    <a href="#image-6">
        <figure class="effect-apollo">
            <img src="{$e}" alt="image6">
            <figcaption></figcaption>
        </figure>
    </a>

    <div class="lb-overlay" id="image-6">
        <img src="{$e}" alt="image6" />
        <div class="gal-info">
            <h3>Tilling</h3>
            <p>Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.</p>
        </div>
        <a href="#" class="lb-close">Close</a>
    </div>
</li>
</code>```

答:
I personally would use the CSS property "height" and "width". Since if I understand your question correctly the 5th image has a greater height value then the other 6.
But also maybe this post will help you:

How can I make all images of different height and width the same via CSS?

Title: Resize image grid

Body:
I have a gallery with a image grid that I cannot resize to auto cut the images with the same format in the browser and on phone.

5th element with bigger height than normal

CSS

.grid figure {
    position: relative;

    overflow: hidden;

    background: #3085a3;
    text-align: center;
    cursor: pointer;
}

.grid figure img {
    position: relative;
    display: block;
    max-width: 100%;
    opacity: 0.8;
}

HTML

Tilling

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

        Close


问:
jQuery, new line and enter button
I'm using following code for textarea:

```<code>$('#ajaxSendMessage').live('keyup', function(event) {
    if (event.keyCode == 13) {
        controller.sendMessage($(this).val(), $("#ajaxAnswerTo").val());
    }
});
</code>```

This code works, but $("#ajaxAnswerTo").val() have new line characte when I click enter...
For example: I entered: helo world and then moved cursor to helo world, updated it to hello and clicked enter. The result code will be: hell\no world.

How to remove this \n?

答:
A simple Regular Expression should do the trick:</p>

```<code>$("#ajaxAnswerTo").val().replace(/\r?\n/, '');
</code>```

Title: jQuery, new line and enter button

Body:
I'm using following code for textarea:

$('#ajaxSendMessage').live('keyup', function(event) {
    if (event.keyCode == 13) {
        controller.sendMessage($(this).val(), $("#ajaxAnswerTo").val());
    }
});

This code works, but $("#ajaxAnswerTo").val() have new line characte when I click enter...
For example: I entered: helo world and then moved cursor to helo world, updated it to hello and clicked enter. The result code will be: hell\no world.

How to remove this \n?

Body:
A simple Regular Expression should do the trick:

$("#ajaxAnswerTo").val().replace(/\r?\n/, '');


问:
Is it possible to use await without async in Js
Await is a amazing feature in es7.

However,everytime I use await I found that I have to define a async function and call this function.

Such as

```<code>    async function asy(){
        const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
                        this.http.get('api/v1/cities?type=guess'),
                        this.http.get('api/v1/cities?type=hot'),
                        this.http.get('api/v1/cities?type=group')
        ])
        this.cityGuessName=resCityGuess.data.name;
        this.cityGuessId=resCityGuess.data.id;
        this.cityHot=resCityHot.data;
        this.cityAll=resCityAll.data;
    }
    asy.apply(this);
</code>```

What I want is use await without async function such as

```<code>        // the async function definition is deleted
        const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
                        this.http.get('api/v1/cities?type=guess'),
                        this.http.get('api/v1/cities?type=hot'),
                        this.http.get('api/v1/cities?type=group')
        ])
        this.cityGuessName=resCityGuess.data.name;
        this.cityGuessId=resCityGuess.data.id;
        this.cityHot=resCityHot.data;
        this.cityAll=resCityAll.data;
        // without call fn
</code>```

I think define the function fn and call this fn is repeated sometimes so I want to know is it possible to optimize the situation？

Can I use await without async?

Thank you so much!

答:
Solution

Not exactly without async but take a look, this may illuminate.

You can effectively create an arrow function (that is intentionally anonymous).

Arrow functions are an ECMAScript2015 syntax for writing anonymous functions. They have a lot of features that separate them from the original function keyword in JavaScript, but in many cases they can be a drop-in replacement for anonymous functions.

Add the async keyword, surround the function with parentheses and add another parentheses set to run the function.

Inside the function, use the await keyword.

Like this:

```<code>(async () => {
    console.log("Message in 5s");
    await new Promise((resolve) => setTimeout(() => resolve(), 5000));
    console.log("If you like it, show it");
})();
</code>```

Body:
Await is a amazing feature in es7.

However,everytime I use await I found that I have to define a async function and call this function.

Such as

    async function asy(){
        const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
                        this.http.get('api/v1/cities?type=guess'),
                        this.http.get('api/v1/cities?type=hot'),
                        this.http.get('api/v1/cities?type=group')
        ])
        this.cityGuessName=resCityGuess.data.name;
        this.cityGuessId=resCityGuess.data.id;
        this.cityHot=resCityHot.data;
        this.cityAll=resCityAll.data;
    }
    asy.apply(this);

What I want is use await without async function such as

        // the async function definition is deleted
        const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
                        this.http.get('api/v1/cities?type=guess'),
                        this.http.get('api/v1/cities?type=hot'),
                        this.http.get('api/v1/cities?type=group')
        ])
        this.cityGuessName=resCityGuess.data.name;
        this.cityGuessId=resCityGuess.data.id;
        this.cityHot=resCityHot.data;
        this.cityAll=resCityAll.data;
        // without call fn

I think define the function fn and call this fn is repeated sometimes so I want to know is it possible to optimize the situation？

Can I use await without async?

Thank you so much!

Body:
Solution

Not exactly without async but take a look, this may illuminate.

You can effectively create an arrow function (that is intentionally anonymous).

Arrow functions are an ECMAScript2015 syntax for writing anonymous functions. They have a lot of features that separate them from the original function keyword in JavaScript, but in many cases they can be a drop-in replacement for anonymous functions.

Add the async keyword, surround the function with parentheses and add another parentheses set to run the function.

Inside the function, use the await keyword.

Like this:

(async () => {
    console.log("Message in 5s");
    await new Promise((resolve) => setTimeout(() => resolve(), 5000));
    console.log("If you like it, show it");
})();