问:
Count which cycle of the alphabet this letter is in [python]
I have this alphabetic cycle A B C D which represent the phase an item is in. An item can cycle through the phase more than once, so I need to find out if an item is in its first phase A, or its second phase A.

Letters can be missing which makes this a bit tricky. See correct outputs:

```<code>test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]
</code>```

Note that in test_2 we accurately note the first occurrence of phase C is in the 2nd cycle.

My attempts are below:

```<code>import itertools

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

valid_phase_seq=['A','B','C','D']

def count_phases(phase_list):
    '''
    We will see whether this is the 1st phase A, or the 2nd phase A.
    :param phase_list:
    :return: int list
    '''
    phase_counts = []
    valid_iter = itertools.cycle(valid_phase_seq)
    count = 1

    # failed approach #2
    while len(phase_counts) != len(phase_list):
        for valid_phase in valid_iter:
            for curr_phase in phase_list:
                if valid_phase == curr_phase:
                    phase_counts.append(count)
            count += 1

    # failed approach #1
    # for curr_phase in phase_list:
    #     # Look at a phase
    #     curr_valid = next(valid_iter)
    #
    #     # We are in another cycle
    #     if curr_valid == 'A' and len(phase_counts) > 1:
    #         count += 1
    #         valid_iter = itertools.cycle(valid_phase_seq)
    #         curr_valid = next(valid_iter)
    #
    #     # We are in the same cycle
    #     #if curr_phase == curr_valid:
    #     phase_counts.append(count)

    return phase_counts

</code>```

答:
I think you have too many loops. In psuedocode, I would do something like this:</p>

```<code>for letter in phase_list
    if letter starts a new phase
        count += 1
    phase_counts.append(count)
</code>```

Body:
I have this alphabetic cycle A B C D which represent the phase an item is in. An item can cycle through the phase more than once, so I need to find out if an item is in its first phase A, or its second phase A.

Letters can be missing which makes this a bit tricky. See correct outputs:

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

Note that in test_2 we accurately note the first occurrence of phase C is in the 2nd cycle.

My attempts are below:

import itertools

test_1 = ['A','B','C','D','A','B']
output_1 = [1,1,1,1,2,2]

test_2 = ['A','B','D','A','B','C']
output_2 = [1,1,1,2,2,2]

test_3 = ['B','A','B','C']
output_3 = [1,2,2,2]

valid_phase_seq=['A','B','C','D']

def count_phases(phase_list):
    '''
    We will see whether this is the 1st phase A, or the 2nd phase A.
    :param phase_list:
    :return: int list
    '''
    phase_counts = []
    valid_iter = itertools.cycle(valid_phase_seq)
    count = 1

    # failed approach #2
    while len(phase_counts) != len(phase_list):
        for valid_phase in valid_iter:
            for curr_phase in phase_list:
                if valid_phase == curr_phase:
                    phase_counts.append(count)
            count += 1

    # failed approach #1
    # for curr_phase in phase_list:
    #     # Look at a phase
    #     curr_valid = next(valid_iter)
    #
    #     # We are in another cycle
    #     if curr_valid == 'A' and len(phase_counts) > 1:
    #         count += 1
    #         valid_iter = itertools.cycle(valid_phase_seq)
    #         curr_valid = next(valid_iter)
    #
    #     # We are in the same cycle
    #     #if curr_phase == curr_valid:
    #     phase_counts.append(count)

    return phase_counts

Body:
I think you have too many loops. In psuedocode, I would do something like this:

for letter in phase_list
    if letter starts a new phase
        count += 1
    phase_counts.append(count)


来源: stackexchange

问:
AS3 JPGEncoder: I don't want black background
I have the following code to create a jpg file from a movieclip:

```<code>var translateMatrix:Matrix = new Matrix();
translateMatrix.scale(1, 1); // (0.746, 0.746);
translateMatrix.translate(100, 150);

var myBitmap:BitmapData = new BitmapData(500, 500, false, 0x00000000);
myBitmap.draw(muneca, translateMatrix, null, "normal", null, true);
var encoder:JPGEncoder = new JPGEncoder(80);
var byteArray:ByteArray = encoder.encode(myBitmap);

var file:FileReference = new FileReference();
file.save(byteArray, "photo.jpg");
</code>```

However, the transparent parts of the movieclip (background) are black in the final jpg. How can I transform those black parts into white?

Thank you very much

答:
Initialize BitmapData with white : </p>

```<code>var myBitmap:BitmapData = new BitmapData(500, 500, false, 0xFFFFFFFF);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code to create a jpg file from a movieclip:

var translateMatrix:Matrix = new Matrix();
translateMatrix.scale(1, 1); // (0.746, 0.746);
translateMatrix.translate(100, 150);

var myBitmap:BitmapData = new BitmapData(500, 500, false, 0x00000000);
myBitmap.draw(muneca, translateMatrix, null, "normal", null, true);
var encoder:JPGEncoder = new JPGEncoder(80);
var byteArray:ByteArray = encoder.encode(myBitmap);

var file:FileReference = new FileReference();
file.save(byteArray, "photo.jpg");

However, the transparent parts of the movieclip (background) are black in the final jpg. How can I transform those black parts into white?

Thank you very much

Body:
Initialize BitmapData with white :

var myBitmap:BitmapData = new BitmapData(500, 500, false, 0xFFFFFFFF);


问:
How can I make this CSS animation smooth?
Instead of teetering in a jagged way I'd like it to interpolate between each rotation.

div {
  border: 1px solid red;
  width: 600px;
  height: 300px;

  animation: shake 0.75s;
  animation-iteration-count: infinite;
}

@keyframes shake {
  0% { transform: rotate(0deg); }
  25% { transform: rotate(-4deg); }
  50% { transform: rotate(0deg); }
  75% { transform: rotate(4deg); }
  100% { transform: rotate(0deg); }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div></div>

</body>
</html></code>```

Preferably no JS but JS or jQuery is fine.

答:
you have to add the transition property and your CSS and thereafter it will looks like this

```<code>div {
  border: 1px solid red;
  width: 600px;
  height: 300px;
  transition: 1s ease-in-out all;
  animation: shake 0.75s;
  animation-iteration-count: infinite;
}

@keyframes shake {
  0% { transform: rotate(0deg); }
 25% { transform: rotate(-4deg); }
 50% { transform: rotate(0deg); }
 75% { transform: rotate(4deg); }
100% { transform: rotate(0deg); }
}
</code>```

if you found it hard to see changes reduce your animation time and increase the transition one

ContentLicense: CC BY-SA 4.0

Body:
Instead of teetering in a jagged way I'd like it to interpolate between each rotation.

div {
  border: 1px solid red;
  width: 600px;
  height: 300px;

  animation: shake 0.75s;
  animation-iteration-count: infinite;
}

@keyframes shake {
  0% { transform: rotate(0deg); }
  25% { transform: rotate(-4deg); }
  50% { transform: rotate(0deg); }
  75% { transform: rotate(4deg); }
  100% { transform: rotate(0deg); }

}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Preferably no JS but JS or jQuery is fine.

Body:
you have to add the transition property and your CSS and thereafter it will looks like this

div {
  border: 1px solid red;
  width: 600px;
  height: 300px;
  transition: 1s ease-in-out all;
  animation: shake 0.75s;
  animation-iteration-count: infinite;
}

@keyframes shake {
  0% { transform: rotate(0deg); }
 25% { transform: rotate(-4deg); }
 50% { transform: rotate(0deg); }
 75% { transform: rotate(4deg); }
100% { transform: rotate(0deg); }
}

if you found it hard to see changes reduce your animation time and increase the transition one


问:
Django celery beat attributeError: 'NoneType' object has no attribute 'localize'
I'm trying to get periodic tasks running with my Django project as per this tutorial.

When running celery beat with the command below:

```<code>celery -A proj beat -l info -S django
</code>```

I get the following error:

```<code>celery beat v4.0.2 (latentcall) is starting.
    __    -    ... __   -        _
    LocalTime -> 2018-02-24 13:42:37
    Configuration ->
        . broker -> redis://localhost:6379//
        . loader -> celery.loaders.app.AppLoader
        . scheduler -> django_celery_beat.schedulers.DatabaseScheduler
        . logfile -> [stderr]@%INFO
        . maxinterval -> 5.00 seconds (5s)
    [2018-02-24 13:42:37,244: INFO/MainProcess] beat: Starting...
    [2018-02-24 13:42:37,245: INFO/MainProcess] Writing entries...
    [2018-02-24 13:42:37,255: CRITICAL/MainProcess] beat raised exception <type 'exceptions.AttributeError'>: AttributeError("'NoneType' object has no attribute 'localize'",)
    Traceback (most recent call last):
      File "...lib/python2.7/site-packages/celery/apps/beat.py", line 107, in start_scheduler
        service.start()
      File "...lib/python2.7/site-packages/celery/beat.py", line 528, in start
        humanize_seconds(self.scheduler.max_interval))
      File "...lib/python2.7/site-packages/kombu/utils/objects.py", line 44, in __get__
        value = obj.__dict__[self.__name__] = self.__get(obj)
      File "...lib/python2.7/site-packages/celery/beat.py", line 572, in scheduler
        return self.get_scheduler()
      File "...lib/python2.7/site-packages/celery/beat.py", line 567, in get_scheduler
        lazy=lazy,
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 183, in __init__
        Scheduler.__init__(self, *args, **kwargs)
      File "...lib/python2.7/site-packages/celery/beat.py", line 204, in __init__
        self.setup_schedule()
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 191, in setup_schedule
        self.install_default_entries(self.schedule)
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 290, in schedule
        self._schedule = self.all_as_schedule()
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 199, in all_as_schedule
        s[model.name] = self.Entry(model, app=self.app)
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 88, in __init__
        model.last_run_at = self._default_now()
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 106, in _default_now
        return now.tzinfo.localize(now.replace(tzinfo=None))
    AttributeError: 'NoneType' object has no attribute 'localize'
</code>```

Researching other StackOverflow posts suggests that an object is not being passed through somewhere which is causing the attribute error on a NoneType. I suspect the problem may have something to do with my nested local.py and production.py settings modules differing from what Celery may expect from a more typical settings module in the project app directory.

Below is my project structure and code. My virtualenv is enabled and all dependencies have been installed and are running. Any help or advice would be much appreciated.

Directory structure:

```<code>├── myproject
│   ├── myproject
│   │   ├── __init__.py
│   │   ├── settings
│   │   │   ├── __init__.py
│   │   │   ├── base.py
│   │   │   ├── celery.py
│   │   │   ├── local.py
│   │   │   ├── production.py
│   ├── manage.py
</code>```

myproject/myproject/settings/__init__.py

```<code># myproject/myproject/settings/__init__.py

from __future__ import absolute_import, unicode_literals

from .base import *

try:
    from .local import *
    live = False
except:
    live = True

if live:
    from .production import *
</code>```

myproject/myproject/__init__.py

```<code># myproject/myproject/__init__.py

from __future__ import absolute_import

from myproject.settings.celery import app as celery_app
</code>```

celery.py

```<code># myproject/myproject/settings/celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.local')

app = Celery('myproject')

# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
  print('Request: {0!r}'.format(self.request))

from celery.schedules import crontab
app.conf.beat_schedule = {
    'add-every-minute-crontab': {
        'task': 'fetch_news',
        'schedule': crontab()
    }
}
</code>```

答:
I successfully overcame the problem by adding in the settings:

```<code>DJANGO_CELERY_BEAT_TZ_AWARE=False
</code>```

Then, I got an exception

```<code>kombu.exceptions.VersionMismatch: Redis transport requires redis-py versions
</code>```

This was solved by https://github.com/celery/celery/issues/5369#issuecomment-469302960

I also have also noticed that django-celery-beat version 1.1.0 don't have this specific issue, but it will NOT send signals using crontabs. So you shoud use a higher version.

Body:
I'm trying to get periodic tasks running with my Django project as per this tutorial.

When running celery beat with the command below:

celery -A proj beat -l info -S django

I get the following error:

celery beat v4.0.2 (latentcall) is starting.
    __    -    ... __   -        _
    LocalTime -> 2018-02-24 13:42:37
    Configuration ->
        . broker -> redis://localhost:6379//
        . loader -> celery.loaders.app.AppLoader
        . scheduler -> django_celery_beat.schedulers.DatabaseScheduler
        . logfile -> [stderr]@%INFO
        . maxinterval -> 5.00 seconds (5s)
    [2018-02-24 13:42:37,244: INFO/MainProcess] beat: Starting...
    [2018-02-24 13:42:37,245: INFO/MainProcess] Writing entries...
    [2018-02-24 13:42:37,255: CRITICAL/MainProcess] beat raised exception <type 'exceptions.AttributeError'>: AttributeError("'NoneType' object has no attribute 'localize'",)
    Traceback (most recent call last):
      File "...lib/python2.7/site-packages/celery/apps/beat.py", line 107, in start_scheduler
        service.start()
      File "...lib/python2.7/site-packages/celery/beat.py", line 528, in start
        humanize_seconds(self.scheduler.max_interval))
      File "...lib/python2.7/site-packages/kombu/utils/objects.py", line 44, in __get__
        value = obj.__dict__[self.__name__] = self.__get(obj)
      File "...lib/python2.7/site-packages/celery/beat.py", line 572, in scheduler
        return self.get_scheduler()
      File "...lib/python2.7/site-packages/celery/beat.py", line 567, in get_scheduler
        lazy=lazy,
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 183, in __init__
        Scheduler.__init__(self, *args, **kwargs)
      File "...lib/python2.7/site-packages/celery/beat.py", line 204, in __init__
        self.setup_schedule()
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 191, in setup_schedule
        self.install_default_entries(self.schedule)
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 290, in schedule
        self._schedule = self.all_as_schedule()
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 199, in all_as_schedule
        s[model.name] = self.Entry(model, app=self.app)
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 88, in __init__
        model.last_run_at = self._default_now()
      File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 106, in _default_now
        return now.tzinfo.localize(now.replace(tzinfo=None))
    AttributeError: 'NoneType' object has no attribute 'localize'

Researching other StackOverflow posts suggests that an object is not being passed through somewhere which is causing the attribute error on a NoneType. I suspect the problem may have something to do with my nested local.py and production.py settings modules differing from what Celery may expect from a more typical settings module in the project app directory.

Below is my project structure and code. My virtualenv is enabled and all dependencies have been installed and are running. Any help or advice would be much appreciated.

Directory structure:

├── myproject
│   ├── myproject
│   │   ├── __init__.py
│   │   ├── settings
│   │   │   ├── __init__.py
│   │   │   ├── base.py
│   │   │   ├── celery.py
│   │   │   ├── local.py
│   │   │   ├── production.py
│   ├── manage.py

myproject/myproject/settings/__init__.py

# myproject/myproject/settings/__init__.py

from __future__ import absolute_import, unicode_literals

from .base import *

try:
    from .local import *
    live = False
except:
    live = True

if live:
    from .production import *

myproject/myproject/__init__.py

# myproject/myproject/__init__.py

from __future__ import absolute_import

from myproject.settings.celery import app as celery_app

celery.py

# myproject/myproject/settings/celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.local')

app = Celery('myproject')

# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
  print('Request: {0!r}'.format(self.request))

from celery.schedules import crontab
app.conf.beat_schedule = {
    'add-every-minute-crontab': {
        'task': 'fetch_news',
        'schedule': crontab()
    }
}

Body:
I successfully overcame the problem by adding in the settings:

DJANGO_CELERY_BEAT_TZ_AWARE=False

Then, I got an exception

kombu.exceptions.VersionMismatch: Redis transport requires redis-py versions

This was solved by https://github.com/celery/celery/issues/5369#issuecomment-469302960

I also have also noticed that django-celery-beat version 1.1.0 don't have this specific issue, but it will NOT send signals using crontabs. So you shoud use a higher version.


问:
How to add thumbnails to Discord embeds?
I am creating a Discord bot that displays player statistics from Hypixel, a Minecraft server. I am trying to add their player's avatars as well, as a thumbnail in the embeds the bot sends. To get the avatars I am using Crafatar. This is the code I am using, however, the thumbnail doesn't show up on the embed. I believe this has something to do with the fact that I am using an URL with a variable in it, as I tried with just a regular URL and it worked fine.

.setThumbnail(`https://crafatar.com/avatars/${uuid}.jpg`)
```

<p>The variable <code>uuid</code> is declared and assigned to a value further up in my code. </p>

<p><strong>EDIT 1</strong></p>

<p>This is the code where I get the <code>uuid</code> variable from. I can't see anything wrong with it, however, I am not particularly skilled in JavaScript.</p>

<pre class="lang-js prettyprint-override"><code>var uuid = '';
getId(args[1]).then(id => {
  uuid = id;
})
</code>```

getId is a function defined below, which looks like this:

function getId(playername) {
  return fetch(`https://api.mojang.com/users/profiles/minecraft/${playername}`)
    .then(data => data.json())
    .then(player => player.id);
}
```

This uses the Mojang API to convert the player's display name, which is entered as a command parameter, to their UUID.

答:
From what you've posted, it seems like the problem is from the fact that you're correctly using Promises to set the value of uuid, but you're not waiting for it to be set before setting your embed thumbnail.

You should wait for it either using Promise.then() (as you did elsewhere), or async/await.

Here's an example:

// Using .then():
getId(args[1]).then(uuid => {
  let embed = new MessageEmbed()

  // You have to set the thumbnail after you get the actual ID:
  embed.setThumbnail(`https://crafatar.com/avatars/${uuid}.jpg`)

  // You can now send the embed
})

// Using async/await:
let uuid = await getId(args[1])
let embed = new MessageEmbed()
embed.setThumbnail(`https://crafatar.com/avatars/${uuid}.jpg`)
```

Body:
I am creating a Discord bot that displays player statistics from Hypixel, a Minecraft server. I am trying to add their player's avatars as well, as a thumbnail in the embeds the bot sends. To get the avatars I am using Crafatar. This is the code I am using, however, the thumbnail doesn't show up on the embed. I believe this has something to do with the fact that I am using an URL with a variable in it, as I tried with just a regular URL and it worked fine.

.setThumbnail(`https://crafatar.com/avatars/${uuid}.jpg`)

The variable uuid is declared and assigned to a value further up in my code.

EDIT 1

This is the code where I get the uuid variable from. I can't see anything wrong with it, however, I am not particularly skilled in JavaScript.

var uuid = '';
getId(args[1]).then(id => {
  uuid = id;
})

getId is a function defined below, which looks like this:

function getId(playername) {
  return fetch(`https://api.mojang.com/users/profiles/minecraft/${playername}`)
    .then(data => data.json())
    .then(player => player.id);
}

This uses the Mojang API to convert the player's display name, which is entered as a command parameter, to their UUID.


问:
HTML to PDF in JS using a variable
This is my first post because I am stuck and I didn't find the solution neither here or the web.

I want to convert HTML to PDF using JS. I was searching and the best option seems to be HTML2canvas and JSpdf. But the think is my HTML is storage in a variable:

```<code>var test = '<html><head><script type="text/javscript">var number = 123;</script></head><body>
<h1>"the value for number is: " + number</h1></body></html>'
</code>```

My variable is much more complex and it contains CSS and styles but this is just to get the idea. Then when I try to convert this into canvas it doesn't convert.

```<code>const filename  = 'ThisIsYourPDFFilename.pdf';

html2canvas(test).then(canvas => {
    let pdf = new jsPDF('p', 'mm', 'a4');
    pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
    pdf.save(filename);
});
</code>```

Does anyone know why this happens? Maybe it is a really stupid question but I don't know how to avoid the errors.

Thank you in advance.

答:
You use string as a parameter for html2canvas, but it takes HTML element:

```<code>html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});
</code>```

Look at their documentation

I have modified your code:

```<code>const html2canvas = require("html2canvas");
const jsPDF = require("jspdf");

html2canvas(document.getElementById("screenshot"), { scale: 1 }).then(
  (canvas) => {
    document.body.appendChild(canvas);
    const filename = "ThisIsYourPDFFilename.pdf";
    let pdf = new jsPDF("p", "mm", "a4");
    pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0);
    pdf.save(filename);
    document.body.removeChild(canvas);
  }
);
</code>```

body should contain element with id screenshot:

```<code><div id="screenshot">
    Content
</div>
</code>```

UPDATE:

According to this resource jsPDF has method fromHTML, so you might not need html2canvas

```<code>var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
    '#elementH': function (element, renderer) {
        return true;
    }
};
// note here that it uses html
doc.fromHTML(elementHTML, 15, 15, {
    'width': 170,
    'elementHandlers': specialElementHandlers
});

// Save the PDF
doc.save('sample-document.pdf');
</code>```

Title: HTML to PDF in JS using a variable

Body:
This is my first post because I am stuck and I didn't find the solution neither here or the web.

I want to convert HTML to PDF using JS. I was searching and the best option seems to be HTML2canvas and JSpdf. But the think is my HTML is storage in a variable:

var test = '

"the value for number is: " + number
'

My variable is much more complex and it contains CSS and styles but this is just to get the idea. Then when I try to convert this into canvas it doesn't convert.

const filename  = 'ThisIsYourPDFFilename.pdf';

html2canvas(test).then(canvas => {
    let pdf = new jsPDF('p', 'mm', 'a4');
    pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
    pdf.save(filename);
});

Does anyone know why this happens? Maybe it is a really stupid question but I don't know how to avoid the errors.

Thank you in advance.

Body:
You use string as a parameter for html2canvas, but it takes HTML element:

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

Look at their documentation

I have modified your code:

const html2canvas = require("html2canvas");
const jsPDF = require("jspdf");

html2canvas(document.getElementById("screenshot"), { scale: 1 }).then(
  (canvas) => {
    document.body.appendChild(canvas);
    const filename = "ThisIsYourPDFFilename.pdf";
    let pdf = new jsPDF("p", "mm", "a4");
    pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0);
    pdf.save(filename);
    document.body.removeChild(canvas);
  }
);

body should contain element with id screenshot:

<div id="screenshot">
    Content
</div>

UPDATE:

According to this resource jsPDF has method fromHTML, so you might not need html2canvas

var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
    '#elementH': function (element, renderer) {
        return true;
    }
};
// note here that it uses html
doc.fromHTML(elementHTML, 15, 15, {
    'width': 170,
    'elementHandlers': specialElementHandlers
});

// Save the PDF
doc.save('sample-document.pdf');


问:
How to extract value from selected TextBlock element in a ListBox?
I'm using a ListBox to display all values contained in Dictionary<> object:

```<code><ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>
</code>```

Content is filled by the following code:

```<code>Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
</code>```

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

I tried doing something like that, but obviosly it doesn't work:

```<code>private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
</code>```

I would really appreciate your help!

答:
Your code is good, using ListBox.SelectedItem is the right approach.

I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):

```<code>private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
    var dataContext = lbi.DataContext;
    this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}
</code>```

Body:
I'm using a ListBox to display all values contained in Dictionary<> object:

<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

Content is filled by the following code:

Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

I tried doing something like that, but obviosly it doesn't work:

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}

I would really appreciate your help!

Body:
Your code is good, using ListBox.SelectedItem is the right approach.

I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
    var dataContext = lbi.DataContext;
    this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}


问:
How can I combine these HTML files in order to run them at the same time on a single webpage?
My knowledge of HTML/Javascript is extremely limited. I was working with this code I found online, and wanted to combine the two programs so that I had the brickbreaker game on top, and the live data updating beneath it. The two activities don't need to be linked, but want them to appear on the same webpage, both within view without having to scroll. I appreciate any help!

```<code><!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {

var dataPoints1 = [];
var dataPoints2 = [];
var dataPoints3 = [];

var chart = new CanvasJS.Chart("chartContainer", {
    zoomEnabled: true,
    title: {
        text: "Protein Activity"
    },
    axisX: {
        title: "chart updates every 1 secs"
    },
    axisY:{
        prefix: "",
        includeZero: false
    },
    toolTip: {
        shared: true
    },
    legend: {
        cursor:"pointer",
        verticalAlign: "top",
        fontSize: 22,
        fontColor: "dimGrey",
        itemclick : toggleDataSeries
    },
    data: [{
        type: "line",
        xValueType: "dateTime",
        yValueFormatString: "####.00",
        xValueFormatString: "hh:mm:ss",
        showInLegend: true,
        name: "Blue Protein",
        dataPoints: dataPoints1
        },
        {
            type: "line",
            xValueType: "dateTime",
            yValueFormatString: "####.00",
            xValueFormatString: "hh:mm:ss",
            showInLegend: true,
            name: "Red Protein" ,
            dataPoints: dataPoints2
    },
    {
        type: "line",
        xValueType: "dateTime",
        yValueFormatString: "####.00",
        xValueFormatString: "hh:mm:ss",
        showInLegend: true,
        name: "Green Protein" ,
        dataPoints: dataPoints3
}]
});

function toggleDataSeries(e) {
    if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
        e.dataSeries.visible = false;
    }
    else {
        e.dataSeries.visible = true;
    }
    chart.render();
}
//initial interval was 3000 (every 3 seconds)
var updateInterval = 1000; // 1 second interval 1000
// initial value originally 600 and 605
var yValue1 = 0;
var yValue2 = 0
var yValue3 = 0;

var time = new Date;
// starting at 9.30 am

time.setMinutes(00);
time.setSeconds(00);

function updateChart(count) {

    count = count || 1;
    var deltaY1, deltaY2, deltaY3;
    for (var i = 0; i < count; i++) {
        time.setTime(time.getTime() + updateInterval);
        // dropping the parenthetical manipulators
        // the change is between 0 and 1 ... place holder until we connect with the game
        deltaY1 =  Math.random() ;
        deltaY2 =  Math.random();
        deltaY3 =  Math.random();

    // adding random value and rounding it to two digits.
    yValue1 = Math.round((yValue1 + deltaY1)*100)/100;
    yValue2 = Math.round((yValue2 + deltaY2)*100)/100;
    yValue3 = Math.round((yValue3 + deltaY3)*100)/100;
    // pushing the new values
    dataPoints1.push({
        x: time.getTime(),
        y: yValue1
    });
    dataPoints2.push({
        x: time.getTime(),
        y: yValue2
    });
    dataPoints3.push({
        x: time.getTime(),
        y: yValue3
    });
    }

    // updating legend text with  updated with y Value
    chart.options.data[0].legendText = " Blue Protein:  " + yValue1;
    chart.options.data[1].legendText = " Red Protein:  " + yValue2;
    chart.options.data[2].legendText = " Green Protein:  " + yValue3;
    chart.render();

}
// generates first set of dataPoints
updateChart(0);
setInterval(function(){updateChart()}, updateInterval);

}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
</code>```

and

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>
    <style>
        * { padding: 0; margin: 0; }
        canvas { background: #eee; display: block; margin: 0 auto; }
    </style>
</head>
<body>

<canvas id="myCanvas" width="480" height="320"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 5;
var brickColumnCount = 3;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;

var bricks = [];
for(var c=0; c<brickColumnCount; c++) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r++) {
    bricks[c][r] = { x: 0, y: 0, status: 1 };
  }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);

function keyDownHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = true;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = false;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = false;
    }
}

function mouseMoveHandler(e) {
  var relativeX = e.clientX - canvas.offsetLeft;
  if(relativeX > 0 && relativeX < canvas.width) {
    paddleX = relativeX - paddleWidth/2;
  }
}
function collisionDetection() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      var b = bricks[c][r];
      if(b.status == 1) {
        if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
          dy = -dy;
          b.status = 0;
          score++;
          if(score == brickRowCount*brickColumnCount) {
            alert("YOU WIN, CONGRATS!");
            document.location.reload();
          }
        }
      }
    }
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}
function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}
function drawBricks() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      if(bricks[c][r].status == 1) {
        var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
        var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
      }
    }
  }
}
function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Score: "+score, 8, 20);
}
function drawLives() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBricks();
  drawBall();
  drawPaddle();
  drawScore();
  drawLives();
  collisionDetection();

  if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
    dx = -dx;
  }
  if(y + dy < ballRadius) {
    dy = -dy;
  }
  else if(y + dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
      dy = -dy;
    }
    else {
      lives--;
      if(!lives) {
        alert("GAME OVER");
        document.location.reload();
      }
      else {
        x = canvas.width/2;
        y = canvas.height-30;
        dx = 3;
        dy = -3;
        paddleX = (canvas.width-paddleWidth)/2;
      }
    }
  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
  requestAnimationFrame(draw);
}

draw();
</script>

</body>
</html>
</code>```

答:
At a high level, this is the approach you'll want to take in creating a new HTML page that combines the original two:

```

Make sure you don't have any duplicate code (such as redundant <title> tags), make sure any elements with id="" attributes have unique ids, and you should be off to a good start.

Body:
My knowledge of HTML/Javascript is extremely limited. I was working with this code I found online, and wanted to combine the two programs so that I had the brickbreaker game on top, and the live data updating beneath it. The two activities don't need to be linked, but want them to appear on the same webpage, both within view without having to scroll. I appreciate any help!

<!DOCTYPE HTML>

and

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>

<canvas id="myCanvas" width="480" height="320"></canvas>

Body:
At a high level, this is the approach you'll want to take in creating a new HTML page that combines the original two:

<html>
<head>
  <!-- contents of first page's <head> -->
  <!-- contents of second page's <head> -->
</head>
<body>
  <!-- contents of first page's <body> -->
  <!-- contents of second page's <body> -->
</body>
</html>

Make sure you don't have any duplicate code (such as redundant <title> tags), make sure any elements with id="" attributes have unique ids, and you should be off to a good start.


问:
Print all subsets in an array that equal to a given sum recursively
I have to write a code with a two methods that takes an array (non-negative) and a value sum as parameters.
I have to use the methods:

```<code>public static void printSubsetSums(int[] arr, int sum) {

}

public static void printSubsetSums(int[] arr, int sum, int i, String acc)
{

}
</code>```

We are not allowed to add methods or any more parameters for the current methods.
I did something similar that just prints the number of subsets that are from a given array according to a sum. but i'm having a hard time to change it to do this task...
my array is limited to the length of 5.

ecxample:
"Enter 5 numbers to array"
input:1 2 3 4 5
"Enter a number into sum"
input:8
3

why 3? (3,5) , (1,3,4) , (1,2,5)

Thank you for your help!!!

答:
The requirement imposed in the question is a little difficult to interpret. However, I have coded to fulfill your use case.

The approach which I have used is the following:

Find all the possible subset of the given array using the bit-manipulation method.

Check if the sum of the subset is equal to the given sum. If it is yes, then print it on the console.

Check the snippet below for more clarity.

```<code>import java.util.Scanner;

public class SubsetSum {
    public static void printSubsetSums(int[] arr, int sum) {
        printSubsetSums(arr, sum, 0, "NotNeeded");
    }

    public static void printSubsetSums(int[] arr, int sum, int i, String acc) {
        // variable 'i' and 'acc' are not getting used anywhere.
        // Have added because you want to make the same syntax for the function.
        boolean isAnySubsetPossible = false;
        int n = arr.length;

        // Run a loop from 0 to 2^n
        for (int p = 0; p < (1 << n); p++) {
            int[] temporaryArray = new int[n];
            int k = 0;
            int m = 1; // m is used to check set bit in binary representation.
            // Print current subset
            for (int j = 0; j < n; j++) {
                if ((p & m) > 0) {
                    temporaryArray[k++] = arr[j];
                }
                m = m << 1;
            }

            int localSum = 0;
            for (int temp : temporaryArray) {
                localSum += temp;
            }
            if (localSum == sum) { // check if the sum is equal to the desired sum
                isAnySubsetPossible = true;
                for (int item : temporaryArray) {
                    if (item > 0) {
                        System.out.print(item + " ");
                    }
                }
                // print a new line so that next subset starts from new line
                System.out.println();
            }
        }
        if (!isAnySubsetPossible) {
            System.out.println("There is no subset possible for the sum = " + 20);
        }
    }

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println("Enter 5 numbers into array");
        int[] myArr = new int[5];
        for (int i = 0; i < myArr.length; i++) {
            myArr[i] = myScanner.nextInt();
        }
        System.out.println("Enter a number into sum");
        int sum = myScanner.nextInt();
        printSubsetSums(myArr, sum);
    }
}
</code>```

Input1 to the program

```<code>Enter 5 numbers into array
1 2 3 4 5
Enter a number into sum
8
</code>```

Output1 by the program

```<code>1 3 4
1 2 5
3 5
</code>```

Input2 to the program

```<code>Enter 5 numbers into array
1 2 3 4 5
Enter a number into sum
20
</code>```

Output2 by the program

```<code>There is no subset possible for the sum = 20
</code>```

I hope this helps.

Body:
I have to write a code with a two methods that takes an array (non-negative) and a value sum as parameters.
I have to use the methods:

public static void printSubsetSums(int[] arr, int sum) {

}

public static void printSubsetSums(int[] arr, int sum, int i, String acc)
{

}

We are not allowed to add methods or any more parameters for the current methods.
I did something similar that just prints the number of subsets that are from a given array according to a sum. but i'm having a hard time to change it to do this task...
my array is limited to the length of 5.

ecxample:
"Enter 5 numbers to array"
input:1 2 3 4 5
"Enter a number into sum"
input:8
3

why 3? (3,5) , (1,3,4) , (1,2,5)

Thank you for your help!!!

Body:
The requirement imposed in the question is a little difficult to interpret. However, I have coded to fulfill your use case.

The approach which I have used is the following:

Find all the possible subset of the given array using the bit-manipulation method.

Check if the sum of the subset is equal to the given sum. If it is yes, then print it on the console.

Check the snippet below for more clarity.

import java.util.Scanner;

public class SubsetSum {
    public static void printSubsetSums(int[] arr, int sum) {
        printSubsetSums(arr, sum, 0, "NotNeeded");
    }

    public static void printSubsetSums(int[] arr, int sum, int i, String acc) {
        // variable 'i' and 'acc' are not getting used anywhere.
        // Have added because you want to make the same syntax for the function.
        boolean isAnySubsetPossible = false;
        int n = arr.length;

        // Run a loop from 0 to 2^n
        for (int p = 0; p < (1 << n); p++) {
            int[] temporaryArray = new int[n];
            int k = 0;
            int m = 1; // m is used to check set bit in binary representation.
            // Print current subset
            for (int j = 0; j < n; j++) {
                if ((p & m) > 0) {
                    temporaryArray[k++] = arr[j];
                }
                m = m << 1;
            }

            int localSum = 0;
            for (int temp : temporaryArray) {
                localSum += temp;
            }
            if (localSum == sum) { // check if the sum is equal to the desired sum
                isAnySubsetPossible = true;
                for (int item : temporaryArray) {
                    if (item > 0) {
                        System.out.print(item + " ");
                    }
                }
                // print a new line so that next subset starts from new line
                System.out.println();
            }
        }
        if (!isAnySubsetPossible) {
            System.out.println("There is no subset possible for the sum = " + 20);
        }
    }

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println("Enter 5 numbers into array");
        int[] myArr = new int[5];
        for (int i = 0; i < myArr.length; i++) {
            myArr[i] = myScanner.nextInt();
        }
        System.out.println("Enter a number into sum");
        int sum = myScanner.nextInt();
        printSubsetSums(myArr, sum);
    }
}

Input1 to the program

Enter 5 numbers into array
1 2 3 4 5
Enter a number into sum
8

Output1 by the program

1 3 4
1 2 5
3 5

Input2 to the program

Enter 5 numbers into array
1 2 3 4 5
Enter a number into sum
20

Output2 by the program

There is no subset possible for the sum = 20

I hope this helps.


问:
Best way to architect test development in Python so that tests can be run either with a mock or without a mock?
I'm starting a fresh python project and I want to write unit and integration tests with mocking and stubbing. However, I would like to run these tests during the build-pipeline against actual services by spawning these dependent services in a docker container. What is the best way to architect my project so that I can easily enable and disable mocking so that:

tests are run with mocks in local branches

tests are run with actual services (with mocks disabled) in CI build pipeline

I'm using python3 and pytest for my purposes.

答:
I asked this question on "Software Quality Assurance & Testing" Stack Exchange page and received an answer that works.This can be achieved by inheriting two different test classes from one abstract test class and calling one or the other depending on the environment the test is run on.

More details in this answer:
https://sqa.stackexchange.com/a/44745/45222


问:
Select if number range contains number in PostgreSQL
I need to be able to find a row based on a number range, saved as a text field. For example, the field tuesday looks like 540-1020. I want to retrieve this row if I search for 900. So far I have,

```<code>SELECT string_to_array(tuesday, '-')
FROM coverage
WHERE 900 IN string_to_array(tuesday, '-')
</code>```

Where string_to_array(tuesday, '-') prints out like {540,1020}. How can I convert it into a selectable integer range?

答:
Use a range.

```<code>SELECT string_to_array(tuesday, '-')
FROM coverage
WHERE 900 <@ int4range(split_part(tuesday, '-', 1)::int4, split_part(tuesday, '-', 2)::int4, '[]');
</code>```

That last parameter [] signifies an inclusive range where '100-900' would match. You could also do an exclusive upper range like [) (note the right paren) where '100-900' would not match because the upper number is excluded from the set of matching numbers.

For better query speed as your table gets larger, you can add a GIST functional index.

```<code>CREATE INDEX tuesday_range_idx ON coverage
  USING GIST (int4range(split_part(tuesday, '-', 1)::int4, split_part(tuesday, '-', 2)::int4, '[]'));
</code>```

This is exposing some weaknesses in your data model. By having each day as a column, you'd have to create a separate functional index for each column. You're also having to parse text into an array every time you run this. Typically you'd want the data in the table to match how you access it, not its serialized form.

Instead of

```<code>CREATE TABLE coverage (
  id serial PRIMARY KEY,
  year smallint,     -- tracking by week
  week_num smallint, -- for example
  sunday varchar,
  monday varchar,
  tuesday varchar,
  wednesday varchar,
  thursday varchar,
  friday varchar,
  saturday varchar
);
</code>```

why not something like

```<code>CREATE TABLE coverage (
  id serial PRIMARY KEY,
  day date NOT NULL UNIQUE,
  daily_data int4range NOT NULL
);

INSERT INTO coverage (day, daily_data)
VALUES ('2020-06-02', '[540,1020]');
</code>```

Then your search looks like

```<code>SELECT daily_data
FROM coverage
WHERE extract(DOW FROM day) = 2 -- Tuesday (Sunday is 0, Saturday is 6)
  AND 900 <@ daily_data;
</code>```

You can make indexes for the daily data ranges, by date (already a unique index in my example), functional indexes for the day of the week, month, year, etc. Much more flexible.

Or if you absolutely want an array back from your SELECT

```<code>SELECT ARRAY[lower(daily_data), upper(daily_data)]
FROM coverage
WHERE extract(DOW FROM day) = 2 -- Tuesday (Sunday is 0, Saturday is 6)
  AND 900 <@ daily_data;
</code>```

Body:
I need to be able to find a row based on a number range, saved as a text field. For example, the field tuesday looks like 540-1020. I want to retrieve this row if I search for 900. So far I have,

SELECT string_to_array(tuesday, '-')
FROM coverage
WHERE 900 IN string_to_array(tuesday, '-')

Where string_to_array(tuesday, '-') prints out like {540,1020}. How can I convert it into a selectable integer range?

Body:
Use a range.

SELECT string_to_array(tuesday, '-')
FROM coverage
WHERE 900 <@ int4range(split_part(tuesday, '-', 1)::int4, split_part(tuesday, '-', 2)::int4, '[]');

That last parameter [] signifies an inclusive range where '100-900' would match. You could also do an exclusive upper range like [) (note the right paren) where '100-900' would not match because the upper number is excluded from the set of matching numbers.

For better query speed as your table gets larger, you can add a GIST functional index.

CREATE INDEX tuesday_range_idx ON coverage
  USING GIST (int4range(split_part(tuesday, '-', 1)::int4, split_part(tuesday, '-', 2)::int4, '[]'));

This is exposing some weaknesses in your data model. By having each day as a column, you'd have to create a separate functional index for each column. You're also having to parse text into an array every time you run this. Typically you'd want the data in the table to match how you access it, not its serialized form.

Instead of

CREATE TABLE coverage (
  id serial PRIMARY KEY,
  year smallint,     -- tracking by week
  week_num smallint, -- for example
  sunday varchar,
  monday varchar,
  tuesday varchar,
  wednesday varchar,
  thursday varchar,
  friday varchar,
  saturday varchar
);

why not something like

CREATE TABLE coverage (
  id serial PRIMARY KEY,
  day date NOT NULL UNIQUE,
  daily_data int4range NOT NULL
);

INSERT INTO coverage (day, daily_data)
VALUES ('2020-06-02', '[540,1020]');

Then your search looks like

SELECT daily_data
FROM coverage
WHERE extract(DOW FROM day) = 2 -- Tuesday (Sunday is 0, Saturday is 6)
  AND 900 <@ daily_data;

You can make indexes for the daily data ranges, by date (already a unique index in my example), functional indexes for the day of the week, month, year, etc. Much more flexible.

Or if you absolutely want an array back from your SELECT

SELECT ARRAY[lower(daily_data), upper(daily_data)]
FROM coverage
WHERE extract(DOW FROM day) = 2 -- Tuesday (Sunday is 0, Saturday is 6)
  AND 900 <@ daily_data;


问:
PHP randomly assign people to a team
I'm currently building up a little game, where users need to be randomly assigned to teams.

What I got is a table in the database, where the logged in users are listed. Also, each user has a column for the team.

Now in PHP, I got all users stored in a variable, like the following (output of var_export)

```<code>array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), )
</code>```

Now I got two teams, Team Red and Team Blue. My goal is, that every person has randomly been assigned to one of the two teams, however, both teams should have a similar amount of team members (or if an odd number of users is logged in, one team can have one more player).

When assigned, I would then write the information to the database. However, I'd like to always be able to shuffle the teams and then have new teams.

The number of logged in users can vary between 2 and 50 persons.

So far, I thought about multiple ways of doing it, like randomly picking a number between 1 and sizeof(array of users) and then assigning him a team, however, I couldn't get it to work...

Also I this Stackoverflow post, however, using this code, my team Red always had player 1 and 3 or 1 and 4 and my team Blue always had player 2 and 3 or 2 and 4. It never happened, that player 1 was in team red. However, as mentioned, the mix should be completely random.

Can anybody help me out with this or has an idea, how I could manage to do that?

答:
I see there is an accepted answer, but I figured I would post my answer as well as I started to work on this last night and figured it out this morning...

Check it out on the online parser 3v4l: https://3v4l.org/O8hOh

Use colors to style the table: https://3v4l.org/ZUl5p

Takes array and iterates through using foreach() then uses rand() to create a new array $checks and then checks if value !in_array() && !array_key_exists() is present in that new array, if it is not, then we iterate the counter and push the new value and the gamers name into the new array. We wrap this all in while loop that checks if counter is equal to count($arr) --> number of gamers, dynamically pulled from arrays count().

We use a second conditional to make sure the new array count($check) === count($arr), both are the same number, move forward with pushing the team into the original array where  key=NULL or team=NULL. foreach() loop to construct $gamers array. Push original values back into new array, then conditional to check if divisible by two as the $checks array will always randomly assign the number of players a new number each time invoked, if($check[$value['name']] % 2 == 0) assign team 2 -->   $gamers[$key]['team'] = 2;.
or $gamers[$key]['team'] = 'blue';, else{ $gamers[$key]['team'] = 1 } or else{ $gamers[$key]['team'] = 'Red' };

The old array that originally held the players that had NULL values for the key team now holds the newly assigned team/s.

Basic code with explanations in code comments:

$arr = array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), );
// count the number of player in the array and assign to variable
$numOfPlayers = count($arr);

// initiate an empty array to hold the values of the players random unique numbers
$check = array();

  $i = 0; // use a counter to evaluate whether number of players set in array is met
  while($i < count($arr)){ // iterate through foreach loop until we have met the number of players using while loop
    // iterate through each time the while loop fires to get the $value
    foreach($arr as $key => $value){
      // create a random number between 0 and the number of players present in array
      // to check and pass into new array if is not set yet
      $random = rand(1,$numOfPlayers);
      // conditional that check if the random number is in the new array, if not we push that as a value into the new array
      // we also check if the persons name is set as a key, if not, we push that as a key into the new aray
      if(!in_array($random, $check) && !array_key_exists($value['name'], $check)){
        // set the new key/value pairs and iterate the counter for the while loop
        $check[$value['name']] = $random;
        $i++;
      }
    }
  }
  // Now see if the two arrays $check and $arr are equal in count
  if(count($check) === count($arr)){
    // now assign teams using modulus
    foreach($arr as $key => $value){
      // construct the old array with original values
      $gamers[$key] = $value;
      // if value is divisible by 2, assign to specific team change operator here
      // if you want to swap what team get the odd numbered players
      if($check[$value['name']] % 2 == 0){
        $gamers[$key]['team'] = 2;
      // else if not divisible by two assign to other team
      }else{
        $gamers[$key]['team'] = 1;
      }
    }
  }
```

<p><strong>As a function:</strong></p>

<pre class="lang-php prettyprint-override"><code>function constTeams($arr){
  $numOfPlayers = count($arr);

  $check = array();

  $i = 0;
  while($i < count($arr)){
    foreach($arr as $key => $value){
      $random = rand(1,$numOfPlayers);
      if(!in_array($random, $check) && !array_key_exists($value['name'], $check)){
        $check[$value['name']] = $random;
        $i++;
      }
    }
  }
  if(count($check) === count($arr)){
    foreach($arr as $key => $value){
      $gamers[$key] = $value;
      if($check[$value['name']] % 2 == 0){
        $gamers[$key]['team'] = 'Blue';
      }else{
        $gamers[$key]['team'] = 'Red';
      }
    }
  }
  return $gamers;
}

</code>```

An output of var_dump(constTeams($arr)); using the function above which will change each time invoked:

```<code>array(4) {
  [0]=>
  array(3) {
    ["ID"]=>
    string(1) "3"
    ["name"]=>
    string(4) "olaf"
    ["team"]=>
    string(3) "Red"
  }
  [1]=>
  array(3) {
    ["ID"]=>
    string(1) "4"
    ["name"]=>
    string(5) "Peter"
    ["team"]=>
    string(4) "Blue"
  }
  [2]=>
  array(3) {
    ["ID"]=>
    string(1) "5"
    ["name"]=>
    string(5) "chris"
    ["team"]=>
    string(4) "Blue"
  }
  [3]=>
  array(3) {
    ["ID"]=>
    string(1) "6"
    ["name"]=>
    string(8) "günther"
    ["team"]=>
    string(3) "Red"
  }
}

</code>```

Use with array of odd numbered players:

$players = array (
  0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ),
  1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ),
  2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ),
  3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ),
  4 => array ( 'ID' => '7', 'name' => 'John', 'team' => NULL, ),
  5 => array ( 'ID' => '8', 'name' => 'Jack', 'team' => NULL, ),
  6 => array ( 'ID' => '9', 'name' => 'Bob', 'team' => NULL, ),
  7 => array ( 'ID' => '10', 'name' => 'Jake', 'team' => NULL, ),
  8 => array ( 'ID' => '11', 'name' => 'Bill', 'team' => NULL, )
) ;

$output = '

    ';
  foreach(constTeams($players) as $key => $value){
      $output .= '

        '.$value['name'].'
        Team: '.$value['team'].'

';
  }
  $output .= '

';

```

OUTPUT: Randomly changes each time function is invoked.
NOTE: odd numbered players will be determined by the operator in the modulus equation conditional, change that to change which team gets the overpowered number of players. == or != --> here: if($check[$value['name']] % 2 == 0)

Title: PHP randomly assign people to a team

Body:
I'm currently building up a little game, where users need to be randomly assigned to teams.

What I got is a table in the database, where the logged in users are listed. Also, each user has a column for the team.

Now in PHP, I got all users stored in a variable, like the following (output of var_export)

array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), )

Now I got two teams, Team Red and Team Blue. My goal is, that every person has randomly been assigned to one of the two teams, however, both teams should have a similar amount of team members (or if an odd number of users is logged in, one team can have one more player).

When assigned, I would then write the information to the database. However, I'd like to always be able to shuffle the teams and then have new teams.

The number of logged in users can vary between 2 and 50 persons.

So far, I thought about multiple ways of doing it, like randomly picking a number between 1 and sizeof(array of users) and then assigning him a team, however, I couldn't get it to work...

Also I this Stackoverflow post, however, using this code, my team Red always had player 1 and 3 or 1 and 4 and my team Blue always had player 2 and 3 or 2 and 4. It never happened, that player 1 was in team red. However, as mentioned, the mix should be completely random.

Can anybody help me out with this or has an idea, how I could manage to do that?

Body:
I see there is an accepted answer, but I figured I would post my answer as well as I started to work on this last night and figured it out this morning...

Check it out on the online parser 3v4l: https://3v4l.org/O8hOh

Use colors to style the table: https://3v4l.org/ZUl5p

Takes array and iterates through using foreach() then uses rand() to create a new array $checks and then checks if value !in_array() && !array_key_exists() is present in that new array, if it is not, then we iterate the counter and push the new value and the gamers name into the new array. We wrap this all in while loop that checks if counter is equal to count($arr) --> number of gamers, dynamically pulled from arrays count().

We use a second conditional to make sure the new array count($check) === count($arr), both are the same number, move forward with pushing the team into the original array where  key=NULL or team=NULL. foreach() loop to construct $gamers array. Push original values back into new array, then conditional to check if divisible by two as the $checks array will always randomly assign the number of players a new number each time invoked, if($check[$value['name']] % 2 == 0) assign team 2 -->   $gamers[$key]['team'] = 2;.
or $gamers[$key]['team'] = 'blue';, else{ $gamers[$key]['team'] = 1 } or else{ $gamers[$key]['team'] = 'Red' };

The old array that originally held the players that had NULL values for the key team now holds the newly assigned team/s.

Basic code with explanations in code comments:

$arr = array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), );
// count the number of player in the array and assign to variable
$numOfPlayers = count($arr);

// initiate an empty array to hold the values of the players random unique numbers
$check = array();

  $i = 0; // use a counter to evaluate whether number of players set in array is met
  while($i < count($arr)){ // iterate through foreach loop until we have met the number of players using while loop
    // iterate through each time the while loop fires to get the $value
    foreach($arr as $key => $value){
      // create a random number between 0 and the number of players present in array
      // to check and pass into new array if is not set yet
      $random = rand(1,$numOfPlayers);
      // conditional that check if the random number is in the new array, if not we push that as a value into the new array
      // we also check if the persons name is set as a key, if not, we push that as a key into the new aray
      if(!in_array($random, $check) && !array_key_exists($value['name'], $check)){
        // set the new key/value pairs and iterate the counter for the while loop
        $check[$value['name']] = $random;
        $i++;
      }
    }
  }
  // Now see if the two arrays $check and $arr are equal in count
  if(count($check) === count($arr)){
    // now assign teams using modulus
    foreach($arr as $key => $value){
      // construct the old array with original values
      $gamers[$key] = $value;
      // if value is divisible by 2, assign to specific team change operator here
      // if you want to swap what team get the odd numbered players
      if($check[$value['name']] % 2 == 0){
        $gamers[$key]['team'] = 2;
      // else if not divisible by two assign to other team
      }else{
        $gamers[$key]['team'] = 1;
      }
    }
  }

As a function:

function constTeams($arr){
  $numOfPlayers = count($arr);

  $check = array();

  $i = 0;
  while($i < count($arr)){
    foreach($arr as $key => $value){
      $random = rand(1,$numOfPlayers);
      if(!in_array($random, $check) && !array_key_exists($value['name'], $check)){
        $check[$value['name']] = $random;
        $i++;
      }
    }
  }
  if(count($check) === count($arr)){
    foreach($arr as $key => $value){
      $gamers[$key] = $value;
      if($check[$value['name']] % 2 == 0){
        $gamers[$key]['team'] = 'Blue';
      }else{
        $gamers[$key]['team'] = 'Red';
      }
    }
  }
  return $gamers;
}

An output of var_dump(constTeams($arr)); using the function above which will change each time invoked:

array(4) {
  [0]=>
  array(3) {
    ["ID"]=>
    string(1) "3"
    ["name"]=>
    string(4) "olaf"
    ["team"]=>
    string(3) "Red"
  }
  [1]=>
  array(3) {
    ["ID"]=>
    string(1) "4"
    ["name"]=>
    string(5) "Peter"
    ["team"]=>
    string(4) "Blue"
  }
  [2]=>
  array(3) {
    ["ID"]=>
    string(1) "5"
    ["name"]=>
    string(5) "chris"
    ["team"]=>
    string(4) "Blue"
  }
  [3]=>
  array(3) {
    ["ID"]=>
    string(1) "6"
    ["name"]=>
    string(8) "günther"
    ["team"]=>
    string(3) "Red"
  }
}

Use with array of odd numbered players:

$players = array (
  0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ),
  1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ),
  2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ),
  3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ),
  4 => array ( 'ID' => '7', 'name' => 'John', 'team' => NULL, ),
  5 => array ( 'ID' => '8', 'name' => 'Jack', 'team' => NULL, ),
  6 => array ( 'ID' => '9', 'name' => 'Bob', 'team' => NULL, ),
  7 => array ( 'ID' => '10', 'name' => 'Jake', 'team' => NULL, ),
  8 => array ( 'ID' => '11', 'name' => 'Bill', 'team' => NULL, )
) ;

$output = '
  <table>
    ';
  foreach(constTeams($players) as $key => $value){
      $output .= '
      <tr border="1">
        <td>'.$value['name'].'</td>
        <td>Team: '.$value['team'].'</td>
      </tr>';
  }
  $output .= '
  </table>';

OUTPUT: Randomly changes each time function is invoked.
NOTE: odd numbered players will be determined by the operator in the modulus equation conditional, change that to change which team gets the overpowered number of players. == or != --> here: if($check[$value['name']] % 2 == 0)


问:
Is there a way in c# to expand a call to multiple implementations of an interface implicitly?
Let's say I have two classes that both implement interface Test

```<code>public interface Test
{
    void Write(string value);
}

public class Data1 : Test
{
    public void Write(string value) { Console.WriteLine(value); }
}
public class Data2 : Test
{
    public void Write(string value) { Console.WriteLine(value); }
}
</code>```

Is there any way to use the interface to call multiple implementations of it?

For example, with the above code I want to do the following:

```<code>public class Wrapper
{
    private Data1 data1;
    private Data2 data2;

    // i'm aware this isn't code but this is the best way I had of describing it
    // basically my goal is to call both implementations with a single call
    public CallMethod(Test.Method, Parameters[])
    {
        data1.Method(Parameters);
        data2.Method(Parameters);
    }
}
</code>```

Its possible I'm going about this the wrong way but the whole goal of this is that I am in the process of migrating to a new database. I have two classes that both implement the same interface that write their data to their own database. I want to call both of those at the same time without having to explicitly write a wrapper method for each method. Eventually I will rip the old data class out and want to have as little code churn as possible.

答: There is no built-in way how to do that. You have to have custom wrapper class/struct.</p>

Body:
Let's say I have two classes that both implement interface Test

public interface Test
{
    void Write(string value);
}

public class Data1 : Test
{
    public void Write(string value) { Console.WriteLine(value); }
}
public class Data2 : Test
{
    public void Write(string value) { Console.WriteLine(value); }
}

Is there any way to use the interface to call multiple implementations of it?

For example, with the above code I want to do the following:

public class Wrapper
{
    private Data1 data1;
    private Data2 data2;

    // i'm aware this isn't code but this is the best way I had of describing it
    // basically my goal is to call both implementations with a single call
    public CallMethod(Test.Method, Parameters[])
    {
        data1.Method(Parameters);
        data2.Method(Parameters);
    }
}

Its possible I'm going about this the wrong way but the whole goal of this is that I am in the process of migrating to a new database. I have two classes that both implement the same interface that write their data to their own database. I want to call both of those at the same time without having to explicitly write a wrapper method for each method. Eventually I will rip the old data class out and want to have as little code churn as possible.


问:
How to remove response headers when sending a json response in php?
I am making an ajax request to a php page e.g page1.php. In page1.php I have a header("Location:page2.php?password=1234") code which redirects to page2.php with the password as a GET parameter. page2.php gives a json response.
The problem is that when I do inspect element and check the resources in Safari browser, I am able to see the location page2.php?password=1234" in the response header part.
This is a security issue. Please suggest how can I remove the response headers when sending the json response? I am using PHP 5.2.6.

答:
Rather than redirecting to the second page, you could query it from the first page, and display its output.

Assuming your setup supports it, the easiest way is probably to include the following in page1.php:

```<code>readfile('http://yoursite.org/page2.php?password=1234');
</code>```

Body:
Rather than redirecting to the second page, you could query it from the first page, and display its output.

Assuming your setup supports it, the easiest way is probably to include the following in page1.php:

readfile('http://yoursite.org/page2.php?password=1234');


问:
Why does old value not passed to vue component?
why does old value not passed to vue component?

passed old value here

<autocomplete-region-component :query="old('regionName')"></autocomplete-region-component>```
</div>
</div>
</p>

<p>my code from vue component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <input
            type="text"
            autocomplete="off"
            v-model="query"
            v-on:keyup="autoComplete"
            class="form-control js-region-name"
            name="regionName"
            value=""
        >
        <input
            type="hidden"
            class="form-control js-region-id"
            name="regionId"
            value="enteredRegion">
        <div class="panel-footer" v-if="results.length">
            <ul class="list-group select-region">
                <li class="list-group-item list-region" v-for="result in results" v-on:click="selectRegion(result)">
                    {{ result.name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                results: [],
                query: '',
            }
        },
        methods: {
            autoComplete() {
                this.results = [];
                if(this.query.length > 2){
                    axios.get('/api/regions',{params: {_limit: 2, query: this.query}}).then(response => {
                        this.results = response.data;
                    });
                }
            },
            selectRegion(result) {
                let inputWithRegionName = document.querySelector('.js-region-name');
                let inputWithRegionId = document.querySelector('.js-region-id');
                let listRegions = document.querySelector('.panel-footer');

                inputWithRegionName.value = result.name;
                inputWithRegionId.value = result.id;
                listRegions.hidden = true;
            }
        }
    }
</script></code>```

console not have mistakes

Please help with a detailed answer since I am a beginner and really need your help. thanks

UPDATE

答:
You have to define a prop and set the data to that prop

When you pass data in a component tag via the v-bind shorthand : these data are known as props and have to be defined as such

Vue disallows mutating props passed from the parent in the child, therefor you should make a local copy of that prop in the reactive data object

```<code>props: {
    queryProp: {
        required: false,
        type: String
    }
},
data() {
    return {
        results: [],
        query: this.queryProp
    };
},
</code>```

Assuming a Blade view like so

    <form action="/" method="post">
        @csrf
        <input type="text" name="regionName">

        <button type="submit">Submit</button>
    </form>
    <autocomplete-region-component :query-prop="{{ json_encode(old('regionName')) }}"></autocomplete-region-component>

```

<p>And routes like so</p>

<pre class="lang-php prettyprint-override"><code><?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::view('/', 'welcome');
Route::post('/', fn (Request $request) => $request->validate(['regionName' => 'integer']));
</code>```

This is what you would get if invalid data is posted

Body:
why does old value not passed to vue component?

passed old value here

<autocomplete-region-component :query="old('regionName')"></autocomplete-region-component>

my code from vue component

<template>

        <input
            type="text"
            autocomplete="off"
            v-model="query"
            v-on:keyup="autoComplete"
            class="form-control js-region-name"
            name="regionName"
            value=""
        >
        <input
            type="hidden"
            class="form-control js-region-id"
            name="regionId"
            value="enteredRegion">

                    {{ result.name }}

</template>

console not have mistakes

Please help with a detailed answer since I am a beginner and really need your help. thanks

UPDATE

Body:
You have to define a prop and set the data to that prop

When you pass data in a component tag via the v-bind shorthand : these data are known as props and have to be defined as such

Vue disallows mutating props passed from the parent in the child, therefor you should make a local copy of that prop in the reactive data object

props: {
    queryProp: {
        required: false,
        type: String
    }
},
data() {
    return {
        results: [],
        query: this.queryProp
    };
},

Assuming a Blade view like so

<div id="app">
    <form action="/" method="post">
        @csrf
        <input type="text" name="regionName"> <br>
        <button type="submit">Submit</button>
    </form>
    <autocomplete-region-component :query-prop="{{ json_encode(old('regionName')) }}"></autocomplete-region-component>
</div>

<script src="/js/app.js"></script>

And routes like so

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::view('/', 'welcome');
Route::post('/', fn (Request $request) => $request->validate(['regionName' => 'integer']));

This is what you would get if invalid data is posted


问:
Why local storage is changing every entry in task list
The local storage should only hold state for the task where the completed button has been pressed. Currently when I refresh the page all the tasks are marked as completed.</p>

```<code><template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>
</div>
</template>

<script>
export default {

props: 'itemId', required: true,
data() {
    return {
        index: 'this.itemId',
        status: ''
    }
},
methods: {
on_order_button_click() {
  this.status = !this.status;
  localStorage.setItem('index', this.status);
}

},
mounted() {

this.status = localStorage.getItem('index') === "true";
},
computed: {
buttonText() {
  return this.status === true ? "Completed" : "Complete";
},
 order_button_style() {
  return this.status === true
    ? "btn btn-danger"
    : "btn btn-primary";
}

}

};
</script>
</code>```

答:
In your calls to set localstorage, you are setting the item with a key of string 'index', not the index data property of your component. With what you have now, all components are reading from the same localstorage key.

For example, change:

mounted() {
    this.status = localStorage.getItem('index') === "true";
},
```

<p>To:</p>

```mounted() {
    this.status = localStorage.getItem(this.index) === "true";
},
```

<p>Also, I don't think the way you are setting a data property equal to a passed property works. I've never seen that before. I think you are just setting your index data property equal to the string literal <code>'this.itemId'</code>.</p>

<p>I've rewritten your component trying to clean what errors I think there are. Let me know if this works.</p>

<pre class="lang-js prettyprint-override"><code><template>
    <button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
        {{ buttonText }}
    </button>
</template>

<script>
export default {
    props: {
        itemId: {
            type: String,
            required: true,
        }
    },
    data() {
        return {
            status: false,
        }
    },
    methods: {
        on_order_button_click() {
            this.status = !this.status;
            localStorage.setItem(this.itemId, this.status);
        }
    },
    mounted() {
        this.status = localStorage.getItem(this.itemId) === "true";
    },
    computed: {
        buttonText() {
            return this.status === true ? "Completed" : "Complete";
        },
        order_button_style() {
            return this.status === true ?
                "btn btn-danger" :
                "btn btn-primary";
        }

    }

};
</script>

</code>```

Body:
The local storage should only hold state for the task where the completed button has been pressed. Currently when I refresh the page all the tasks are marked as completed.

<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>

</template>

Body:
In your calls to set localstorage, you are setting the item with a key of string 'index', not the index data property of your component. With what you have now, all components are reading from the same localstorage key.

For example, change:

mounted() {
    this.status = localStorage.getItem('index') === "true";
},

To:

mounted() {
    this.status = localStorage.getItem(this.index) === "true";
},

Also, I don't think the way you are setting a data property equal to a passed property works. I've never seen that before. I think you are just setting your index data property equal to the string literal 'this.itemId'.

I've rewritten your component trying to clean what errors I think there are. Let me know if this works.

<template>
    <button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
        {{ buttonText }}
    </button>
</template>

<script>
export default {
    props: {
        itemId: {
            type: String,
            required: true,
        }
    },
    data() {
        return {
            status: false,
        }
    },
    methods: {
        on_order_button_click() {
            this.status = !this.status;
            localStorage.setItem(this.itemId, this.status);
        }
    },
    mounted() {
        this.status = localStorage.getItem(this.itemId) === "true";
    },
    computed: {
        buttonText() {
            return this.status === true ? "Completed" : "Complete";
        },
        order_button_style() {
            return this.status === true ?
                "btn btn-danger" :
                "btn btn-primary";
        }

    }

};
</script>


问:
Loop through Key value pairs in Typescript
How to get the values of key value pairs defined in an interface in typescript -

```<code>interface Person {
    [Id: string]: PersonConfig
}

interface PersonConfig {
    name: string,
    age: number
}

const people: Person[] = [
    {
      "p1": {
          name: "abcd",
          age: 20
      }
    },
    {
      "p2": {
          name: "efgh",
          age: 78
      }
    }
];

Object.entries(people).forEach(([key, value]) => {
  console.log(value);
});
</code>```

I get the result as -

```<code>{ p1: { name: 'abcd', age: 20 } }
{ p2: { name: 'efgh', age: 78 } }
</code>```

Now, I want the values of key and values separately. I do not see a way other than providing key values by myself (console.log(value["p1"])).

Expecting the output as :

```<code>console.log(value.Id + "-" + value.PersonConfig);
</code>```

答:
You don't need to use Object.entries in an array. It is used for objects. Since your people is an array you can use normal forEach like below.

```<code>people.forEach(person => {
  Object.entries(person).forEach(([key, value]) => {
    console.log(key, value);
  });
});
</code>```

Body:
How to get the values of key value pairs defined in an interface in typescript -

interface Person {
    [Id: string]: PersonConfig
}

interface PersonConfig {
    name: string,
    age: number
}

const people: Person[] = [
    {
      "p1": {
          name: "abcd",
          age: 20
      }
    },
    {
      "p2": {
          name: "efgh",
          age: 78
      }
    }
];

Object.entries(people).forEach(([key, value]) => {
  console.log(value);
});

I get the result as -

{ p1: { name: 'abcd', age: 20 } }
{ p2: { name: 'efgh', age: 78 } }

Now, I want the values of key and values separately. I do not see a way other than providing key values by myself (console.log(value["p1"])).

Expecting the output as :

console.log(value.Id + "-" + value.PersonConfig);

Body:
You don't need to use Object.entries in an array. It is used for objects. Since your people is an array you can use normal forEach like below.

people.forEach(person => {
  Object.entries(person).forEach(([key, value]) => {
    console.log(key, value);
  });
});


问:
How do I convert this string into json with javascript?
How do I parse string into json with javascript?

"[{'Name': \"O'BRIEN DEIRDRE\", 'Text': 'Hello'}]"

I need to change all single quote to double quote, but I need to keep the single quote of O'BRIEN

答:
Maybe this can fix your problem: https://regexr.com/55t8o

Edit:
If the link is deprecated the regex expression should be '([a-zA-Z]*)' and replace it with "$1"

I also agree with Taplar who commented that it would probably be better if you found out why it's using ' instead of " and not use regex. Hope this helps


问:
Cosine similarity over tf idf output in spark dataframe (scala)
I am using Spark Scala to calculate cosine similarity between the Dataframe rows.

Dataframe format is below:

```<code>root
 |-- id: long (nullable = true)
 |-- features: vector (nullable = true)
</code>```

Sample of the dataframe is below:

```<code>+---+--------------------+
| id|            features|
+---+--------------------+
| 65|(10000,[48,70,87,...|
|191|(10000,[1,73,77,1...|
+---+--------------------+
</code>```

Code that gives me the result is below:

```<code>val df = spark.read.json("articles_line.json")
val tokenizer = new Tokenizer().setInputCol("desc").setOutputCol("words")
val wordsDF = tokenizer.transform(df)

def flattenWords = udf( (s: Seq[Seq[String]]) => s.flatMap(identity) )
val groupedDF = wordsDF.groupBy("id").
  agg(flattenWords(collect_list("words")).as("grouped_words"))
val hashingTF = new HashingTF().
  setInputCol("grouped_words").setOutputCol("rawFeatures").setNumFeatures(10000)
val featurizedData = hashingTF.transform(groupedDF)
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
val idfModel = idf.fit(featurizedData)
val rescaledData = idfModel.transform(featurizedData)
val asDense = udf((v: Vector) => v.toDense) //transform to dense matrix
val newDf = rescaledData.select('id, 'features)
    .withColumn("dense_features", asDense($"features")
</code>```

Final dataframe looks like

```<code>+-----+--------------------+--------------------+
|   id|            features|      dense_features|
+-----+--------------------+--------------------+
|21209|(10000,[128,288,2...|[0.0,0.0,0.0,0.0,...|
|21223|(10000,[8,18,32,4...|[0.0,0.0,0.0,0.0,...|
+-----+--------------------+--------------------+
</code>```

I don't understand how to process "dense_features" to calculate cosine similarity. This article didn't work for me. Appreciate any help.

Example of one row of dense_features. For simplicity the length is cuted.

```<code>[[0.0,0.0,0.0,0.0,7.08,0.0,0.0,0.0,0.0,2.24,0.0,0.0,0.0,0.0,0.0,,9.59]]
</code>```

答:
This worked for me fine.
Full code</p>

```<code>import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer}
import org.apache.spark.ml.linalg.Vector
import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.linalg.distributed._
import org.apache.spark.ml.linalg.{SparseVector, Vector}
import org.apache.spark.sql.types._
import org.apache.spark.ml.feature._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions.Window

val df = spark.read.json("/user/dmitry.korniltsev/lab02/data/DO_record_per_line.json")
val cleaned_df = df
    .withColumn("desc", regexp_replace('desc, "[^\\w\\sа-яА-ЯЁё]", ""))
    .withColumn("desc", lower(trim(regexp_replace('desc, "\\s+", " "))))
    .where(length('desc) > 0)

val tokenizer = new Tokenizer().setInputCol("desc").setOutputCol("words")
val wordsDF = tokenizer.transform(cleaned_df)
def flattenWords = udf( (s: Seq[Seq[String]]) => s.flatMap(identity) )
val hashingTF = new HashingTF()
    .setInputCol("words")
    .setOutputCol("rawFeatures")
    .setNumFeatures(20000)
val featurizedData = hashingTF.transform(wordsDF)
val idf = new IDF()
    .setInputCol("rawFeatures")
    .setOutputCol("features")
val idfModel = idf.fit(featurizedData)
val rescaledData = idfModel.transform(featurizedData)
val asDense = udf((v: Vector) => v.toDense)
val newDf = rescaledData
    .withColumn("dense_features", asDense($"features"))

val cosSimilarity = udf { (x: Vector, y: Vector) =>
    val v1 = x.toArray
    val v2 = y.toArray
    val l1 = scala.math.sqrt(v1.map(x => x*x).sum)
    val l2 = scala.math.sqrt(v2.map(x => x*x).sum)
    val scalar = v1.zip(v2).map(p => p._1*p._2).sum
    scalar/(l1*l2)
    }

val id_list = Seq(23325, 15072, 24506, 3879, 1067, 17019)
val filtered_df = newDf
    .filter(col("id").isin(id_list: _*))
    .select('id.alias("id_frd"), 'dense_features.alias("dense_frd"), 'lang.alias("lang_frd"))

val joinedDf = newDf.join(broadcast(filtered_df), 'id =!= 'id_frd && 'lang === 'lang_frd)
    .withColumn("cosine_sim", cosSimilarity(col("dense_frd"), col("dense_features")))

val filtered = joinedDf
    .filter(col("lang")==="en")
    .withColumn("cosine_sim", when(col("cosine_sim").isNaN, 0).otherwise(col("cosine_sim")))
    .withColumn("rank", row_number().over(
            Window.partitionBy(col("id_frd")).orderBy(col("cosine_sim").desc)))
    .filter(col("rank")between(2,11))
</code>```

Body:
I am using Spark Scala to calculate cosine similarity between the Dataframe rows.

Dataframe format is below:

root
 |-- id: long (nullable = true)
 |-- features: vector (nullable = true)

Sample of the dataframe is below:

+---+--------------------+
| id|            features|
+---+--------------------+
| 65|(10000,[48,70,87,...|
|191|(10000,[1,73,77,1...|
+---+--------------------+

Code that gives me the result is below:

val df = spark.read.json("articles_line.json")
val tokenizer = new Tokenizer().setInputCol("desc").setOutputCol("words")
val wordsDF = tokenizer.transform(df)

def flattenWords = udf( (s: Seq[Seq[String]]) => s.flatMap(identity) )
val groupedDF = wordsDF.groupBy("id").
  agg(flattenWords(collect_list("words")).as("grouped_words"))
val hashingTF = new HashingTF().
  setInputCol("grouped_words").setOutputCol("rawFeatures").setNumFeatures(10000)
val featurizedData = hashingTF.transform(groupedDF)
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
val idfModel = idf.fit(featurizedData)
val rescaledData = idfModel.transform(featurizedData)
val asDense = udf((v: Vector) => v.toDense) //transform to dense matrix
val newDf = rescaledData.select('id, 'features)
    .withColumn("dense_features", asDense($"features")

Final dataframe looks like

+-----+--------------------+--------------------+
|   id|            features|      dense_features|
+-----+--------------------+--------------------+
|21209|(10000,[128,288,2...|[0.0,0.0,0.0,0.0,...|
|21223|(10000,[8,18,32,4...|[0.0,0.0,0.0,0.0,...|
+-----+--------------------+--------------------+

I don't understand how to process "dense_features" to calculate cosine similarity. This article didn't work for me. Appreciate any help.

Example of one row of dense_features. For simplicity the length is cuted.

[[0.0,0.0,0.0,0.0,7.08,0.0,0.0,0.0,0.0,2.24,0.0,0.0,0.0,0.0,0.0,,9.59]]

Body:
This worked for me fine.
Full code

import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer}
import org.apache.spark.ml.linalg.Vector
import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.linalg.distributed._
import org.apache.spark.ml.linalg.{SparseVector, Vector}
import org.apache.spark.sql.types._
import org.apache.spark.ml.feature._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions.Window

val df = spark.read.json("/user/dmitry.korniltsev/lab02/data/DO_record_per_line.json")
val cleaned_df = df
    .withColumn("desc", regexp_replace('desc, "[^\\w\\sа-яА-ЯЁё]", ""))
    .withColumn("desc", lower(trim(regexp_replace('desc, "\\s+", " "))))
    .where(length('desc) > 0)

val tokenizer = new Tokenizer().setInputCol("desc").setOutputCol("words")
val wordsDF = tokenizer.transform(cleaned_df)
def flattenWords = udf( (s: Seq[Seq[String]]) => s.flatMap(identity) )
val hashingTF = new HashingTF()
    .setInputCol("words")
    .setOutputCol("rawFeatures")
    .setNumFeatures(20000)
val featurizedData = hashingTF.transform(wordsDF)
val idf = new IDF()
    .setInputCol("rawFeatures")
    .setOutputCol("features")
val idfModel = idf.fit(featurizedData)
val rescaledData = idfModel.transform(featurizedData)
val asDense = udf((v: Vector) => v.toDense)
val newDf = rescaledData
    .withColumn("dense_features", asDense($"features"))

val cosSimilarity = udf { (x: Vector, y: Vector) =>
    val v1 = x.toArray
    val v2 = y.toArray
    val l1 = scala.math.sqrt(v1.map(x => x*x).sum)
    val l2 = scala.math.sqrt(v2.map(x => x*x).sum)
    val scalar = v1.zip(v2).map(p => p._1*p._2).sum
    scalar/(l1*l2)
    }

val id_list = Seq(23325, 15072, 24506, 3879, 1067, 17019)
val filtered_df = newDf
    .filter(col("id").isin(id_list: _*))
    .select('id.alias("id_frd"), 'dense_features.alias("dense_frd"), 'lang.alias("lang_frd"))

val joinedDf = newDf.join(broadcast(filtered_df), 'id =!= 'id_frd && 'lang === 'lang_frd)
    .withColumn("cosine_sim", cosSimilarity(col("dense_frd"), col("dense_features")))

val filtered = joinedDf
    .filter(col("lang")==="en")
    .withColumn("cosine_sim", when(col("cosine_sim").isNaN, 0).otherwise(col("cosine_sim")))
    .withColumn("rank", row_number().over(
            Window.partitionBy(col("id_frd")).orderBy(col("cosine_sim").desc)))
    .filter(col("rank")between(2,11))