问:
How to terminate an EMR Cluster from Lambda when all Steps are COMPLETE?
I am trying to figure out how I can terminate an EMR cluster successfully once all the steps submitted to it are 'COMPLETED'|'CANCELLED'|'FAILED'|'INTERRUPTED'. There are three Lambda functions.

Lambda 1: Does some work and creates EMR. Triggers Lambda 2 by passing steps and cluster ID through event.

Lambda 2: Submits the steps received from Lambda 1 to the cluster ID received from the same.

Lambda 3: Submits a final step and then should send a request for termination when all steps are 'COMPLETED'|'CANCELLED'|'FAILED'|'INTERRUPTED'.

I've done till Lambda 3's step submission, but unable to do the rest.

I have successfully created EMR through:

```<code>conn = boto3.client("emr")
cluster_id = conn.run_job_flow()
</code>```

submitted steps through:

```<code>conn = boto3.client("emr")
action = conn.add_job_flow_steps(JobFlowId=cluster_id, Steps=event["steps"])
</code>```

Now how can this termination be triggered only on the given condition? I saw the boto3 API doc which has client.terminate_job_flows(), but this function doesn't wait for the steps to finish or fail and directly hits the termination process.

Is there a way to change KeepJobFlowAliveWhenNoSteps from TRUE to FALSE when all my steps are done? Then I think it should automatically turn off the cluster. But going by the API docs, didn't find any option to change this parameter once the run_job_flow() is called.

Hope I was able to convey the issue I faced correctly. Any help?

Note: Using Python 3.8 in AWS Lambda. Each steps are Spark jobs.

答:
I agree with your research. The optimal situation would be to set KeepJobFlowAliveWhenNoSteps to FALSE to have the cluster self-terminate.

I do notice that the RunJobFlow documentation says:

If the KeepJobFlowAliveWhenNoSteps parameter is set to TRUE, the cluster transitions to the WAITING state rather than shutting down after the steps have completed.

Therefore, the Lambda function could check whether the cluster is in the WAITING state and, if so, shutdown the cluster. However, this would take repeated checking.

It might be possible to submit a final step that calls the EMR API to shutdown the cluster. This means that the cluster is effectively calling for its own termination as a final step. (I haven't tried this concept, but it would be a clean way of performing the shutdown without having to repeatedly check the status.)

There is also a similar discussion about shutting down idle clusters on this Question: How to terminate AWS EMR Cluster automatically after some time

Body:
I am trying to figure out how I can terminate an EMR cluster successfully once all the steps submitted to it are 'COMPLETED'|'CANCELLED'|'FAILED'|'INTERRUPTED'. There are three Lambda functions.

Lambda 1: Does some work and creates EMR. Triggers Lambda 2 by passing steps and cluster ID through event.

Lambda 2: Submits the steps received from Lambda 1 to the cluster ID received from the same.

Lambda 3: Submits a final step and then should send a request for termination when all steps are 'COMPLETED'|'CANCELLED'|'FAILED'|'INTERRUPTED'.

I've done till Lambda 3's step submission, but unable to do the rest.

I have successfully created EMR through:

conn = boto3.client("emr")
cluster_id = conn.run_job_flow()

submitted steps through:

conn = boto3.client("emr")
action = conn.add_job_flow_steps(JobFlowId=cluster_id, Steps=event["steps"])

Now how can this termination be triggered only on the given condition? I saw the boto3 API doc which has client.terminate_job_flows(), but this function doesn't wait for the steps to finish or fail and directly hits the termination process.

Is there a way to change KeepJobFlowAliveWhenNoSteps from TRUE to FALSE when all my steps are done? Then I think it should automatically turn off the cluster. But going by the API docs, didn't find any option to change this parameter once the run_job_flow() is called.

Hope I was able to convey the issue I faced correctly. Any help?

Note: Using Python 3.8 in AWS Lambda. Each steps are Spark jobs.


来源: stackexchange

问:
Removing duplicate dictionaries in list of dicts based on value uniqueness for a given key
I have a dictionary:

```<code>dicts = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item2', 'type': 'foo', 'metaId': 'metaId2'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item5', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item6', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item7', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item8', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item9', 'type': 'foo3', 'metaId': 'metaId3'}]
</code>```

I want to loop through the list and create a new list, that contains dictionaries with unique values for key 'type'. I don't care which dictionaries stay, first instance with that key: value  stays, the rest is omitted. So in the end I'd like to see:

```<code>expected = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'}
]
</code>```

Here is what I tried, definitely not what I need as it returns an empty list. I think I struggle with checking for a value in new sublist of dictionaries to make it excluded

```<code>keys_to_keep = set()
expected = []
for d in dicts:
    for key, value in d.items():
        if value not in expected:
            keys_to_keep.add(key)
remove_keys = set(d) - keys_to_keep

for d in dicts:
    for k in remove_keys:
        del d[k]
dicts = expected
print(dicts)
</code>```

答:
The reason you always get an empty list is because you simply do:

```<code>dicts = expected
</code>```

And expected is simply an empty list, which you never did anything to... not sure why you would think expected would ever change.

But you are overcomplicating things. Just keep a set of the unique values, and create a new list of dicts.

```<code>seen = set()
result = []
for d in dicts:
    if d['type'] not in seen:
        result.append(d)
        seen.add(d['type'])
</code>```

This approach keeps the first dictionary encountered with that unique 'type'.

If, for example, you want the last encountered, you could do something like iterate over dicts in revere order, so

```<code>for d in reversed(dicts):
    ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dictionary:

dicts = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item2', 'type': 'foo', 'metaId': 'metaId2'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item5', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item6', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item7', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item8', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item9', 'type': 'foo3', 'metaId': 'metaId3'}]

I want to loop through the list and create a new list, that contains dictionaries with unique values for key 'type'. I don't care which dictionaries stay, first instance with that key: value  stays, the rest is omitted. So in the end I'd like to see:

expected = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'}
]

Here is what I tried, definitely not what I need as it returns an empty list. I think I struggle with checking for a value in new sublist of dictionaries to make it excluded

keys_to_keep = set()
expected = []
for d in dicts:
    for key, value in d.items():
        if value not in expected:
            keys_to_keep.add(key)
remove_keys = set(d) - keys_to_keep

for d in dicts:
    for k in remove_keys:
        del d[k]
dicts = expected
print(dicts)

Body:
The reason you always get an empty list is because you simply do:

dicts = expected

And expected is simply an empty list, which you never did anything to... not sure why you would think expected would ever change.

But you are overcomplicating things. Just keep a set of the unique values, and create a new list of dicts.

seen = set()
result = []
for d in dicts:
    if d['type'] not in seen:
        result.append(d)
        seen.add(d['type'])

This approach keeps the first dictionary encountered with that unique 'type'.

If, for example, you want the last encountered, you could do something like iterate over dicts in revere order, so

for d in reversed(dicts):
    ...


问:
Expand flex container respective to its children with flex grow
I have a container that has fixed width and inside that I have a flexible menu with display: flex

I want the menu-list to grow upto max-width: 420px, and if it reaches max-width it should wrap and display in next line, so I can't use  white-space: nowrap which makes my menu-list scrollable if it exceeds 420px. How can I make the parent menu expand proportionally with menu-list. The red background should expand 420px in the example below.

.container {
  display: block;
  padding: 10px;
  width: 180px;
}

.menu {
  background-color: red;
  display: inline-flex;
}

.menu-list {
  margin: 10px;
  flex: 1 0 auto;
  max-width: 420px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div></code>```

答:
Here is an idea using width: max-content; (that will not work on IE: https://caniuse.com/#feat=mdn-css_properties_width_max-content)

.container {
  padding: 10px;
  margin:5px;
  max-width: 180px;
}
.menu {
  background-color: red;
  display: inline-block;
}
.menu-list {
  margin: 10px;
  width:max-content;
  max-width: 420px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox jumps over the lazy dog brown fox jump s over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox</div>
      <div class="option">2. The quick brown </div>
      <div class="option">3. The quick bro</div>
      <div class="option">4. The qui</div>
    </div>
  </div>
</div></code>```

Another idea using CSS grid.

.container {
  padding: 10px;
  margin:5px;
  max-width: 180px;
}
.menu {
  background-color: red;
  display: inline-grid;
  grid-auto-columns: max-content;
}
.menu-list {
  margin: 10px;
  max-width: 420px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox jumps over the lazy dog brown fox jump s over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox</div>
      <div class="option">2. The quick brown </div>
      <div class="option">3. The quick bro</div>
      <div class="option">4. The qui</div>
    </div>
  </div>
</div></code>```

Body:
I have a container that has fixed width and inside that I have a flexible menu with display: flex

I want the menu-list to grow upto max-width: 420px, and if it reaches max-width it should wrap and display in next line, so I can't use  white-space: nowrap which makes my menu-list scrollable if it exceeds 420px. How can I make the parent menu expand proportionally with menu-list. The red background should expand 420px in the example below.

.container {
  display: block;
  padding: 10px;
  width: 180px;
}

.menu {
  background-color: red;
  display: inline-flex;
}

.menu-list {
  margin: 10px;
  flex: 1 0 auto;
  max-width: 420px;
}

1. The quick brown fox jumps over the lazy dog

2. The quick brown fox jumps over the lazy dog

3. The quick brown fox jumps over the lazy dog

4. The quick brown fox jumps over the lazy dog

Body:
Here is an idea using width: max-content; (that will not work on IE: https://caniuse.com/#feat=mdn-css_properties_width_max-content)

.container {
  padding: 10px;
  margin:5px;
  max-width: 180px;
}
.menu {
  background-color: red;
  display: inline-block;
}
.menu-list {
  margin: 10px;
  width:max-content;
  max-width: 420px;
}

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox jumps over the lazy dog brown fox jump s over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox</div>
      <div class="option">2. The quick brown </div>
      <div class="option">3. The quick bro</div>
      <div class="option">4. The qui</div>
    </div>
  </div>
</div>

Another idea using CSS grid.

.container {
  padding: 10px;
  margin:5px;
  max-width: 180px;
}
.menu {
  background-color: red;
  display: inline-grid;
  grid-auto-columns: max-content;
}
.menu-list {
  margin: 10px;
  max-width: 420px;
}

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox jumps over the lazy dog brown fox jump s over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick  brown fox</div>
      <div class="option">2. The quick brown </div>
      <div class="option">3. The quick bro</div>
      <div class="option">4. The qui</div>
    </div>
  </div>
</div>


问:
What does CG_INLINE do?
I was poking around the definitions for things like CGPoint for hints on how to create my own functions but I don't know the purpose of CG_INLINE. What is happening behind the scenes here?

```<code>CG_INLINE CGPoint
CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

CG_INLINE CGSize
CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}
</code>```

答:
Inline functions are compiled into the call site, rather than being compiled as a single block of function code and call instructions issued when the function is used. With care, this provides a little more speed and greater numbers of cache hits. However, the history of inline in C and C++ is rocky, so this macro effectively provides a compiler independent static inline behaviour. Looking at the definition:

```<code>#if !defined(CG_INLINE)
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#  define CG_INLINE static inline
# elif defined(__MWERKS__) || defined(__cplusplus)
#  define CG_INLINE static inline
# elif defined(__GNUC__)
#  define CG_INLINE static __inline__
# else
#  define CG_INLINE static
# endif
#endif /* !defined(CG_INLINE) */
</code>```

So...

For compilers providing __STDC_VERSION__ of an appropriate version (in this case >= C99), this means static inline (as C99 allows this natively)

Similarly for Metrowerks Codewarrior or C++ compilers, which support inline natively.

For GCCs not supporting C99, it resolves to static __inline__. The use of __inline__ is the GCC specific inline specifier for previous C standards where inline is unsupported : http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Alternate-Keywords.html.

If all of these fail, it doesn't bother with inline - it's just static.

Why bother with all of these definitions? Because Apple, in their history, have been through a fair few compilers. In the days of yore, the Codewarrior C compiler was the tool of choice for users. Since OS X, Apple have been using Objective C and C++ via an (originally modifier) GCC. Recently, they're transitioning to clang. This macro covers all the cases (and, given how new Core Graphics is, I suspect is a modified version of an older macro).

However, many compilers will ignore inline annotations these days, as their optimisers are better than the hints provided by the programmer. In your own code, don't bother with it (in native form, or via this macro) unless you're really sure you need it (and have proven it useful via profiling). Of course, you may still want static - the above advice covers the inline behaviour.

ContentLicense: CC BY-SA 3.0

Title: What does CG_INLINE do?

Body:
I was poking around the definitions for things like CGPoint for hints on how to create my own functions but I don't know the purpose of CG_INLINE. What is happening behind the scenes here?

CG_INLINE CGPoint
CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

CG_INLINE CGSize
CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}

Body:
Inline functions are compiled into the call site, rather than being compiled as a single block of function code and call instructions issued when the function is used. With care, this provides a little more speed and greater numbers of cache hits. However, the history of inline in C and C++ is rocky, so this macro effectively provides a compiler independent static inline behaviour. Looking at the definition:

#if !defined(CG_INLINE)
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#  define CG_INLINE static inline
# elif defined(__MWERKS__) || defined(__cplusplus)
#  define CG_INLINE static inline
# elif defined(__GNUC__)
#  define CG_INLINE static __inline__
# else
#  define CG_INLINE static
# endif
#endif /* !defined(CG_INLINE) */

So...

For compilers providing __STDC_VERSION__ of an appropriate version (in this case >= C99), this means static inline (as C99 allows this natively)

Similarly for Metrowerks Codewarrior or C++ compilers, which support inline natively.

For GCCs not supporting C99, it resolves to static __inline__. The use of __inline__ is the GCC specific inline specifier for previous C standards where inline is unsupported : http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Alternate-Keywords.html.

If all of these fail, it doesn't bother with inline - it's just static.

Why bother with all of these definitions? Because Apple, in their history, have been through a fair few compilers. In the days of yore, the Codewarrior C compiler was the tool of choice for users. Since OS X, Apple have been using Objective C and C++ via an (originally modifier) GCC. Recently, they're transitioning to clang. This macro covers all the cases (and, given how new Core Graphics is, I suspect is a modified version of an older macro).

However, many compilers will ignore inline annotations these days, as their optimisers are better than the hints provided by the programmer. In your own code, don't bother with it (in native form, or via this macro) unless you're really sure you need it (and have proven it useful via profiling). Of course, you may still want static - the above advice covers the inline behaviour.


问:
How to save a user’s image and display it
I have a user profile model.

```<code>class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(User,default='default.jpg', upload_to='profile_pics',) #default avatar user /download avatar user
    avatar = models.CharField(max_length=300, null=True, blank=True) #field for storing url from a social network

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)
</code>```

It has two fields for the image.

1- regular default avatar (input image) it can be set by the user and after downloading it will be saved in the media / profile_pics folder.

2 field (input avatar) - to store the avatar url from outside (social network). I also have two authorizations, regular and social (python-social-auth). When authorizing a call through social networks, I use the function to get the url of the user address:

```<code>def get_avatar(backend, response, user=None, *args, **kwargs):

    if backend.name == 'vk-oauth2':
        url = response.get('photo', )
    if url:
        user.profile.avatar = url
        user.profile.save()
</code>```

I get a link of this kind (url variable):

https://sun9-12.userapi.com/c852132/v852132234/118b6c/aB0GoDEWzaw.jpg

and save this url user.profile.avatar.

In the template, I output:

```<code><img  src="{{user.profile.image.url }}"> - #default avatar user/download avatar user
<img  src="{{user.profile.avatar}}"> - #social avatar (url) user

</code>```

How do I make sure that when authorizing through social authorization, the image from the url is downloaded and saved in a folder as for imagefield (profile.image)? That is, during the atvorization through social networks, the picture was downloaded by url, and it was saved as if this field were image and I was able to access it through user. profile.image.url, not a separate user.profile.avatar field?

I would be grateful for any help.

答:
You could download the image via urllib.request:

```<code>import urllib.request
import mimetypes

    def save_image(user):
        url = user.profile.avatar
        filename = user.id + mimettypes.guess_extension(urllib.request.urlopen(url).headers['content-type'])
        path = os.path.join(settings.MEDIA_ROOT, filename)

        urllib.request.urlretrieve(url, path)

        user.image = path
        user.save()
</code>```

depending on your storage location, you might change the path, but this should be a sketch of a possible solution.

EDIT: As you are using an ImageField, this should also work:

```<code>import urllib.request

    def save_image(user):
        url = user.profile.avatar
        file = urllib.request.urlopen(url).read()

        user.image = file
        user.save()
</code>```

Body:
I have a user profile model.

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(User,default='default.jpg', upload_to='profile_pics',) #default avatar user /download avatar user
    avatar = models.CharField(max_length=300, null=True, blank=True) #field for storing url from a social network

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

It has two fields for the image.

1- regular default avatar (input image) it can be set by the user and after downloading it will be saved in the media / profile_pics folder.

2 field (input avatar) - to store the avatar url from outside (social network). I also have two authorizations, regular and social (python-social-auth). When authorizing a call through social networks, I use the function to get the url of the user address:

def get_avatar(backend, response, user=None, *args, **kwargs):

    if backend.name == 'vk-oauth2':
        url = response.get('photo', )
    if url:
        user.profile.avatar = url
        user.profile.save()

I get a link of this kind (url variable):

https://sun9-12.userapi.com/c852132/v852132234/118b6c/aB0GoDEWzaw.jpg

and save this url user.profile.avatar.

In the template, I output:

 - #default avatar user/download avatar user
 - #social avatar (url) user

How do I make sure that when authorizing through social authorization, the image from the url is downloaded and saved in a folder as for imagefield (profile.image)? That is, during the atvorization through social networks, the picture was downloaded by url, and it was saved as if this field were image and I was able to access it through user. profile.image.url, not a separate user.profile.avatar field?

I would be grateful for any help.

Body:
You could download the image via urllib.request:

import urllib.request
import mimetypes

    def save_image(user):
        url = user.profile.avatar
        filename = user.id + mimettypes.guess_extension(urllib.request.urlopen(url).headers['content-type'])
        path = os.path.join(settings.MEDIA_ROOT, filename)

        urllib.request.urlretrieve(url, path)

        user.image = path
        user.save()

depending on your storage location, you might change the path, but this should be a sketch of a possible solution.

EDIT: As you are using an ImageField, this should also work:

import urllib.request

    def save_image(user):
        url = user.profile.avatar
        file = urllib.request.urlopen(url).read()

        user.image = file
        user.save()


问:
Drawing a line in the direction a player is moving
For debugging purposes I am trying to draw 2 debug lines. One in the direction that the character is facing and one in the direction that the character is moving.

I have the following function that is called in the update method.

```<code>    void DrawDirectionLines()
    {
        var wishDir = transform.position + transform.forward;
        var movementDir = Quaternion.LookRotation(rb.velocity).eulerAngles;

        Debug.DrawLine(transform.position, transform.position + transform.forward * 5, Color.red);
        Debug.DrawLine(transform.position, transform.position + movementDir * 5, Color.blue);
    }
</code>```

The red direction debug line works perfectly however the blue line representing the actual movement direction of the player seems to always misbehave and never points in the direction the player is moving in.

Does anybody know how I can fix this?

答:
The problem is because your movemendDir is a Vector3 with the euler angles, and not a direction vector.

The good news is that rb.velocity is the direction you only need. The documentation says: Unity velocity also has the speed in X, Y, and Z defining the direction.

But if you use that velocity vector the lenght of the line will depends on the velocity. The solution is normalize that vector.

You need to replace:

```<code>var movementDir = Quaternion.LookRotation(rb.velocity).eulerAngles;
</code>```

to:

```<code>var movementDir = rb.velocity.normalized;
</code>```

Body:
For debugging purposes I am trying to draw 2 debug lines. One in the direction that the character is facing and one in the direction that the character is moving.

I have the following function that is called in the update method.

    void DrawDirectionLines()
    {
        var wishDir = transform.position + transform.forward;
        var movementDir = Quaternion.LookRotation(rb.velocity).eulerAngles;

        Debug.DrawLine(transform.position, transform.position + transform.forward * 5, Color.red);
        Debug.DrawLine(transform.position, transform.position + movementDir * 5, Color.blue);
    }

The red direction debug line works perfectly however the blue line representing the actual movement direction of the player seems to always misbehave and never points in the direction the player is moving in.

Does anybody know how I can fix this?

Body:
The problem is because your movemendDir is a Vector3 with the euler angles, and not a direction vector.

The good news is that rb.velocity is the direction you only need. The documentation says: Unity velocity also has the speed in X, Y, and Z defining the direction.

But if you use that velocity vector the lenght of the line will depends on the velocity. The solution is normalize that vector.

You need to replace:

var movementDir = Quaternion.LookRotation(rb.velocity).eulerAngles;

to:

var movementDir = rb.velocity.normalized;


问:
'IndexError: string index out of range' when index is shorter than the max index in the string. Python
So, first of all some context. As a small fun project I'm working on a small compiler that reads text files and is kind of like a fake programming language. Anyways, the same bug has popped up twice. Once for my 'if' statement and once for my 'math' statement in the language (it's read in python3 by the way). The bug is IndexError: String Index out of range even though the index is less that len(string)-1. Here is my code for the if statement:

```<code>    elif (code[0] + code[1]) == 'if':
        # sta is the index
        sta = 7
        i = 0
        varname = ''
        while i == 0:
            if code[sta] == '=':
                i = 0
            else:
                varname = varname + code[sta]
                sta += 1
        sign = code[sta]
        sta += 2
        i = 0
        condition = ''
        while i == 0:
            if code[sta] == ':':
                i = 0
            else:
                condition = condition + code[sta]
                sta += 1
        sta += 2
        if ints[varname] == int(condition):
            codeif = code[sta:(len(code) - 1)]
            readCode(codeif)
</code>```

And the line that is causing the error is:

```<code>if code[sta] == '=':
</code>```

The code I'm passing through is exactly 15 indexs long
Anyway I could use some help. Thank you in advance!

答:
The problem is that your = is at index 4, assuming your input of:

```<code>      012345678901234567890
code="if x= 9: chr *Hello!;"
</code>```

But if sta starts at 7, and only increments, it will never find the =. Eventually sta reaches 21, which is > the max index of 20. So your claim that even though the index is less that len(string)-1. appears to not hold here.

As other commenters pointed out, there does not appear to be a way to exit that loop, as i starts at 0, is never modified other than to be set again to 0, and the loop only exits if i != 0. Just work on the logic a bit and you should be off and running again.

Happy coding!

Body:
So, first of all some context. As a small fun project I'm working on a small compiler that reads text files and is kind of like a fake programming language. Anyways, the same bug has popped up twice. Once for my 'if' statement and once for my 'math' statement in the language (it's read in python3 by the way). The bug is IndexError: String Index out of range even though the index is less that len(string)-1. Here is my code for the if statement:

    elif (code[0] + code[1]) == 'if':
        # sta is the index
        sta = 7
        i = 0
        varname = ''
        while i == 0:
            if code[sta] == '=':
                i = 0
            else:
                varname = varname + code[sta]
                sta += 1
        sign = code[sta]
        sta += 2
        i = 0
        condition = ''
        while i == 0:
            if code[sta] == ':':
                i = 0
            else:
                condition = condition + code[sta]
                sta += 1
        sta += 2
        if ints[varname] == int(condition):
            codeif = code[sta:(len(code) - 1)]
            readCode(codeif)

And the line that is causing the error is:

if code[sta] == '=':

The code I'm passing through is exactly 15 indexs long
Anyway I could use some help. Thank you in advance!

Body:
The problem is that your = is at index 4, assuming your input of:

      012345678901234567890
code="if x= 9: chr *Hello!;"

But if sta starts at 7, and only increments, it will never find the =. Eventually sta reaches 21, which is > the max index of 20. So your claim that even though the index is less that len(string)-1. appears to not hold here.

As other commenters pointed out, there does not appear to be a way to exit that loop, as i starts at 0, is never modified other than to be set again to 0, and the loop only exits if i != 0. Just work on the logic a bit and you should be off and running again.

Happy coding!


问:
how to publish msg to rabbitmq server with self signed certificate with python pika?
```<code>parameters = pika.URLParameters('amqps://<user>:<pass>@<host>/<vhost>')
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
</code>```

I am getting: ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

I know the server has a self signed certificate. What steps am I missing?

答:
<pre class="lang-py prettyprint-override"><code>    ssl_enabled = settings["rabbitmq"].get("ssl", False)

    rabbitmq_user = settings["rabbitmq"]["user"]
    rabbitmq_password = settings["rabbitmq"]["password"]
    rabbitmq_server = settings["rabbitmq"]["server"]
    rabbitmq_vhost = settings["rabbitmq"]["vhost"]
    rabbitmq_exchange = settings["rabbitmq"]["exchange"]
    rabbitmq_queue = settings["rabbitmq"]["queue"]

    if ssl_enabled:
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        context.verify_mode = ssl.CERT_REQUIRED
        context.load_verify_locations(settings["rabbitmq"].get("ca_bundle", '/etc/pki/tls/certs/ca-bundle.crt'))
        ssl_options = pika.SSLOptions(context)
        port = settings["rabbitmq"].get("port", 5671)
    else:
        ssl_options = None
        port = settings["rabbitmq"].get("port", 5672)

    credentials = pika.credentials.PlainCredentials(
        username=rabbitmq_user, password=rabbitmq_password
    )
    connection_params = pika.ConnectionParameters(
        host=rabbitmq_server,
        ssl_options=ssl_options,
        port=port,
        credentials=credentials,
        virtual_host=rabbitmq_vhost,
        heartbeat=600,
        blocked_connection_timeout=300,
    )
    rabbit = pika.BlockingConnection(connection_params)
    channel = rabbit.channel()

    channel.exchange_declare(
        exchange=rabbitmq_exchange, exchange_type="direct", durable=True
    )
    channel.queue_declare(queue=rabbitmq_queue, durable=True)
    channel.queue_bind(
        exchange=rabbitmq_exchange, queue=rabbitmq_queue, routing_key=rabbitmq_queue
    )

    queue_properties = pika.BasicProperties(delivery_mode=2)
</code>```

Body:
parameters = pika.URLParameters('amqps://<user>:<pass>@<host>/<vhost>')
connection = pika.BlockingConnection(parameters)
channel = connection.channel()

I am getting: ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

I know the server has a self signed certificate. What steps am I missing?


问:
UIPinchGestureRecognizer not responding
I have a universal binary application and currently working on the iPad version of the application. The iPad is using a uitabbarcontroller and on the second tab I have 6 images and when adding a UIPinchGesture it is not responding. I have userInteractionEnabled=YES; I tried adding the image view programmatically and then adding the gesture recognizer and still nothing seems to work.

I tried setting the delegate to the view controller and implementing one of the delegate methods and didn't get any responses. Below is the code sample of what I am doing:

```<code>UIImageView *img2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img2-large.png"]];
img2.frame = CGRectMake(20, 20, 100, 100);
[img2 setUserInteractionEnabled:YES];
img2.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:img2];

UIPinchGestureRecognizer *img2Pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(img2Pinch:)];
[img2 addGestureRecognizer:img2Pinch];
[img2Pinch release];

- (void)img2Pinch:(UIPinchGestureRecognizer *)sender {
      NSLog(@"HERE");
}
</code>```

I'm sure it's something silly that I'm missing. I've used this stuff before but can't for the life of me figure out what is going wrong.

答:
What view are you placing it into?
Is it a scroll view?

Also img2.multipleTouchEnabled = YES, multi touch is not enabled by default, a pinch requires multiple fingers.

(img2Pinch is correctly released)

Title: UIPinchGestureRecognizer not responding

Body:
I have a universal binary application and currently working on the iPad version of the application. The iPad is using a uitabbarcontroller and on the second tab I have 6 images and when adding a UIPinchGesture it is not responding. I have userInteractionEnabled=YES; I tried adding the image view programmatically and then adding the gesture recognizer and still nothing seems to work.

I tried setting the delegate to the view controller and implementing one of the delegate methods and didn't get any responses. Below is the code sample of what I am doing:

UIImageView *img2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img2-large.png"]];
img2.frame = CGRectMake(20, 20, 100, 100);
[img2 setUserInteractionEnabled:YES];
img2.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:img2];

UIPinchGestureRecognizer *img2Pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(img2Pinch:)];
[img2 addGestureRecognizer:img2Pinch];
[img2Pinch release];

- (void)img2Pinch:(UIPinchGestureRecognizer *)sender {
      NSLog(@"HERE");
}

I'm sure it's something silly that I'm missing. I've used this stuff before but can't for the life of me figure out what is going wrong.


问:
static_cast seems to work when it can't possibly work
In the following code I use static_cast on a void*, which points to an A object.

A and B are not related in any way. I understand the compiler cannot raise an error against this. But what I don't understand is, how come this actually seems to work when run...? I would expect a segfault or an error of some kind.

```<code>#include <iostream>

using namespace std;

class A {
    public:
    void f() const {
        cout << "f" << endl;
    }
};

class B {
    public:
    void q() {
        cout << "q" << endl;
    }
};

int main(int argc, char** argv) {
    A a;
    void* p = &a;

    static_cast<B*>(p)->q(); // Prints "q"!

    return 0;
}
</code>```

What is the mechanism behind this?

答:
The code causes undefined behaviour (because it dereferences a B * which does not point to a B object), which means anything can happen. You should not expect any particular subset of consequences.

To find out what your compiler did, you could inspect the assembly. My guess would be that the compiler generated assembly which would be correct if there were a B object there: call the function B::q() with implicit argument p.

Body:
In the following code I use static_cast on a void*, which points to an A object.

A and B are not related in any way. I understand the compiler cannot raise an error against this. But what I don't understand is, how come this actually seems to work when run...? I would expect a segfault or an error of some kind.

#include <iostream>

using namespace std;

class A {
    public:
    void f() const {
        cout << "f" << endl;
    }
};

class B {
    public:
    void q() {
        cout << "q" << endl;
    }
};

int main(int argc, char** argv) {
    A a;
    void* p = &a;

    static_cast(p)->q(); // Prints "q"!

    return 0;
}

What is the mechanism behind this?


问:
Delete vs Delete[] in a custom operator in C++ (different than common delete vs delete[] questions)
I define a class called MyNewDeleteAllocator and define custom new and delete operators for the class. This code has no bugs whatsoever and works perfectly fine. However, I have a question about line 29 of my code. It seems that changing "delete[]" to "delete" does not change anything in my code results.

I am aware of the difference between delete (single object when allocated by "new") and delete[] (array of objects allocated by "new[]").

I was wondering why interchanging delete and delete[] here on line 29 did not affect my results.

```<code>#include <new>
#include <iostream>

using namespace std;

//Allocator class
class MyNewDeleteAllocator {
public:
    MyNewDeleteAllocator() {}
    ~MyNewDeleteAllocator() {}
    static void* operator new (size_t size);
    static void operator delete (void* p);
};

void* MyNewDeleteAllocator::operator new (size_t size) {
    void* p;
    p = malloc(size);
    if (p == NULL) {
        //Throw bad_alloc.
        std::bad_alloc exception;
        throw exception;
    }
    cout << "MyNewDeleteAllocator::operator new called with size_t " << size << endl;
    return p;
}

void MyNewDeleteAllocator::operator delete (void* p) {
    cout << "MyNewDeleteAllocator::operator delete called. " << endl;
    delete[] p; //THIS IS LINE 29
}

int main()
{
    MyNewDeleteAllocator* p = new MyNewDeleteAllocator; //Create MyNewDeleteAllocator object.

    delete p; //Delete MyNewDeleteAllocator object.

    return 0;
}
</code>```

答:
First of all, this is not an allocator, or your name convention is wrong. In C++, an allocator allocates memory for a given type, not for raw bytes. More on that - https://en.cppreference.com/w/cpp/memory/allocator

Second, don't mix malloc()/delete and new/free(). malloc() should be used with free(), new with delete, not the other way around. More on that - https://stackoverflow.com/a/20488420/12979560

So, all you need to do is to replace malloc() with new. Also, when you use new, C++ will throw std::bad_alloc in case if it can't allocate the requested memory.

Body:
I define a class called MyNewDeleteAllocator and define custom new and delete operators for the class. This code has no bugs whatsoever and works perfectly fine. However, I have a question about line 29 of my code. It seems that changing "delete[]" to "delete" does not change anything in my code results.

I am aware of the difference between delete (single object when allocated by "new") and delete[] (array of objects allocated by "new[]").

I was wondering why interchanging delete and delete[] here on line 29 did not affect my results.

#include <new>
#include <iostream>

using namespace std;

//Allocator class
class MyNewDeleteAllocator {
public:
    MyNewDeleteAllocator() {}
    ~MyNewDeleteAllocator() {}
    static void* operator new (size_t size);
    static void operator delete (void* p);
};

void* MyNewDeleteAllocator::operator new (size_t size) {
    void* p;
    p = malloc(size);
    if (p == NULL) {
        //Throw bad_alloc.
        std::bad_alloc exception;
        throw exception;
    }
    cout << "MyNewDeleteAllocator::operator new called with size_t " << size << endl;
    return p;
}

void MyNewDeleteAllocator::operator delete (void* p) {
    cout << "MyNewDeleteAllocator::operator delete called. " << endl;
    delete[] p; //THIS IS LINE 29
}

int main()
{
    MyNewDeleteAllocator* p = new MyNewDeleteAllocator; //Create MyNewDeleteAllocator object.

    delete p; //Delete MyNewDeleteAllocator object.

    return 0;
}


问:
Error making ScrollView autoscroll horizontally in react native
I am trying to make an image slider that autoscrolls horizontally with react native scrollview, it returns error can't find error _scrollView. Who knows a fix or a better to go about it.
Right I have to manually move between the images.I tried adding a ref to the scrollView, but the ref seems to be giving error.</p>

```<code>import React, { Component } from 'react'
import { Animated, View, StyleSheet, Image, Dimensions, ScrollView } from 'react-native'

const deviceWidth = Dimensions.get('window').width
const deviceHeight = Dimensions.get('window').height

const FIXED_BAR_WIDTH = 280
const BAR_SPACE = 10

const images = [
    require("../../assets/images/banner_1.jpg"),
    require("../../assets/images/banner2.jpg")
]

export default class ImgSlider extends Component {

    _scrollView = React.createRef();

    componentDidMount() {
        const numOfBackground = 2;
        let scrollValue = 0, scrolled = 0;
        setInterval(function () {
            scrolled++;
            if(scrolled < numOfBackground)
                scrollValue = scrollValue + deviceWidth;
            else{
                scrollValue = 0;
                scrolled = 0
            }
            _scrollView.scrollTo({ x: scrollValue, animated: false })
        }, 3000);
    }
  numItems = images.length
  itemWidth = (FIXED_BAR_WIDTH / this.numItems) - ((this.numItems - 1) * BAR_SPACE)
  animVal = new Animated.Value(0)

  render() {
    let imageArray = []
    let barArray = []
    images.forEach((image, i) => {
      console.log(image, i)
      const thisImage = (
        <Image
          key={`image${i}`}
          source={image}
          style={{ width: deviceWidth, height: 300 }}
        />
      )
      imageArray.push(thisImage)

      const scrollBarVal = this.animVal.interpolate({
        inputRange: [deviceWidth * (i - 1), deviceWidth * (i + 1)],
        outputRange: [-this.itemWidth, this.itemWidth],
        extrapolate: 'clamp',
      })

      const thisBar = (
        <View
          key={`bar${i}`}
          style={[
            styles.track,
            {
              width: this.itemWidth,
              marginLeft: i === 0 ? 0 : BAR_SPACE,
            },
          ]}
        >
          <Animated.View

            style={[
              styles.bar,
              {
                width: this.itemWidth,
                transform: [
                  { translateX: scrollBarVal },
                ],
              },
            ]}
          />
        </View>
      )
      barArray.push(thisBar)
    })

    return (
      <View
        style={styles.container}
        flex={1}
      >
        <ScrollView
          horizontal
          ref={this._scrollView}
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={10}
          pagingEnabled
        //   ref={(scrollView) => { _scrollView = scrollView }}
          onScroll={
            Animated.event(
              [{ nativeEvent: { contentOffset: { x: this.animVal } } }]
            )
          }
        >

          {imageArray}

        </ScrollView>
        <View
          style={styles.barContainer}
        >
          {barArray}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  barContainer: {
    position: 'absolute',
    zIndex: 2,
    top: 290,
    flexDirection: 'row',
  },
  track: {
    backgroundColor: '#ccc',
    overflow: 'hidden',
    height: 2,
  },
  bar: {
    backgroundColor: '#BB1E18',
    height: 2,
    position: 'absolute',
    left: 0,
    top: 0,
  },
})
</code>```

答: this._scrollView does not have the function scrollTo try console logging whats init and see whats going on in there.

Body:
I am trying to make an image slider that autoscrolls horizontally with react native scrollview, it returns error can't find error _scrollView. Who knows a fix or a better to go about it.
Right I have to manually move between the images.I tried adding a ref to the scrollView, but the ref seems to be giving error.

import React, { Component } from 'react'
import { Animated, View, StyleSheet, Image, Dimensions, ScrollView } from 'react-native'

const deviceWidth = Dimensions.get('window').width
const deviceHeight = Dimensions.get('window').height

const FIXED_BAR_WIDTH = 280
const BAR_SPACE = 10

const images = [
    require("../../assets/images/banner_1.jpg"),
    require("../../assets/images/banner2.jpg")
]

export default class ImgSlider extends Component {

    _scrollView = React.createRef();

    componentDidMount() {
        const numOfBackground = 2;
        let scrollValue = 0, scrolled = 0;
        setInterval(function () {
            scrolled++;
            if(scrolled < numOfBackground)
                scrollValue = scrollValue + deviceWidth;
            else{
                scrollValue = 0;
                scrolled = 0
            }
            _scrollView.scrollTo({ x: scrollValue, animated: false })
        }, 3000);
    }
  numItems = images.length
  itemWidth = (FIXED_BAR_WIDTH / this.numItems) - ((this.numItems - 1) * BAR_SPACE)
  animVal = new Animated.Value(0)

  render() {
    let imageArray = []
    let barArray = []
    images.forEach((image, i) => {
      console.log(image, i)
      const thisImage = (
        <Image
          key={`image${i}`}
          source={image}
          style={{ width: deviceWidth, height: 300 }}
        />
      )
      imageArray.push(thisImage)

      const scrollBarVal = this.animVal.interpolate({
        inputRange: [deviceWidth * (i - 1), deviceWidth * (i + 1)],
        outputRange: [-this.itemWidth, this.itemWidth],
        extrapolate: 'clamp',
      })

      const thisBar = (
        <View
          key={`bar${i}`}
          style={[
            styles.track,
            {
              width: this.itemWidth,
              marginLeft: i === 0 ? 0 : BAR_SPACE,
            },
          ]}
        >
          <Animated.View

            style={[
              styles.bar,
              {
                width: this.itemWidth,
                transform: [
                  { translateX: scrollBarVal },
                ],
              },
            ]}
          />
        </View>
      )
      barArray.push(thisBar)
    })

    return (
      <View
        style={styles.container}
        flex={1}
      >
        <ScrollView
          horizontal
          ref={this._scrollView}
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={10}
          pagingEnabled
        //   ref={(scrollView) => { _scrollView = scrollView }}
          onScroll={
            Animated.event(
              [{ nativeEvent: { contentOffset: { x: this.animVal } } }]
            )
          }
        >

          {imageArray}

        </ScrollView>
        <View
          style={styles.barContainer}
        >
          {barArray}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  barContainer: {
    position: 'absolute',
    zIndex: 2,
    top: 290,
    flexDirection: 'row',
  },
  track: {
    backgroundColor: '#ccc',
    overflow: 'hidden',
    height: 2,
  },
  bar: {
    backgroundColor: '#BB1E18',
    height: 2,
    position: 'absolute',
    left: 0,
    top: 0,
  },
})


问:
how to access to ids of selected names in manytomany relationship django
how to access all ids of Languages through Programmer

```<code>class Language(models.Model):
    name = models.CharField(max_length=20)

class Programmer(models.Model):
    name = models.CharField(max_length=30)
    langs = models.ManyToManyField(Language,through='Level')

class Level(models.Model):
    language = models.ForeignKey(Language)
    programmer = models.ForeignKEy(Programmer)
    level = models.CharField(max_length=10)
</code>```

i tried this ways but no one worked

in Programmer instance : instance.level_set.language_id , instance.level.all.language_id , instance.level.all.language.id and also tried this instance.level_set.language.id
all said Programmer has no attribute ,language , language_id etc
thanks for any advice

答:
Some useful things:

To get all language id's as an iterable:

instance.langs.values_list('id', flat=True)
# <QuerySet [1, 5]>
```

<ul>
<li>Level and language id as a list of 2-tuples:</li>
</ul>

<pre class="lang-py prettyprint-override"><code>instance.level_set.values_list('language__id', 'level')
# <QuerySet [(1, 'advanced'), (5, 'beginner')]>
</code>```

Body:
how to access all ids of Languages through Programmer

class Language(models.Model):
    name = models.CharField(max_length=20)

class Programmer(models.Model):
    name = models.CharField(max_length=30)
    langs = models.ManyToManyField(Language,through='Level')

class Level(models.Model):
    language = models.ForeignKey(Language)
    programmer = models.ForeignKEy(Programmer)
    level = models.CharField(max_length=10)

i tried this ways but no one worked

in Programmer instance : instance.level_set.language_id , instance.level.all.language_id , instance.level.all.language.id and also tried this instance.level_set.language.id
all said Programmer has no attribute ,language , language_id etc
thanks for any advice

Body:
Some useful things:

To get all language id's as an iterable:

instance.langs.values_list('id', flat=True)
# <QuerySet [1, 5]>

Level and language id as a list of 2-tuples:

instance.level_set.values_list('language__id', 'level')
# <QuerySet [(1, 'advanced'), (5, 'beginner')]>


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

Here is my HTML file:

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

my DetailsComponent component:

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

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

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

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

and my model.js file:

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

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

Could anybody help?

答:
If a Movie has its reviews, you can calculate the AVG as soon as you get it. For example:

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

  if (this.movieData.reviews != null && this.movieData.reviews.length > 0) {
    let sum = 0;
    this.movieData.reviews.forEach(review => sum += review.stars);
    this.avg = sum/this.movieData.reviews.length;
  } else {
    this.avg = 0; # Or whatever you want to show if there are no reviews for the movie
  }
});
}
</code>```

The code above checks if the movie has at least 1 review in order to calculate the avg, otherwise it sets avg to 0.

Then in the template you just show it with

```<code>{{avg}}
</code>```

As @jeprubio mentioned, I'd delete the Input() and getMovie(idx) as they are not being used.

Lastly, keep in mind that you are not initializing avg, and if getOneMovie() fails for any reason, you'll never get to set it to a number (leading to errors in the template).

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

Here is my HTML file:

        Reviewer
        Stars
        Reviews
        Action

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

Average rating:  {{avgRating}}

my DetailsComponent component:

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

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

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

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

and my model.js file:

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

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

Could anybody help?

Body:
If a Movie has its reviews, you can calculate the AVG as soon as you get it. For example:

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

  if (this.movieData.reviews != null && this.movieData.reviews.length > 0) {
    let sum = 0;
    this.movieData.reviews.forEach(review => sum += review.stars);
    this.avg = sum/this.movieData.reviews.length;
  } else {
    this.avg = 0; # Or whatever you want to show if there are no reviews for the movie
  }
});
}

The code above checks if the movie has at least 1 review in order to calculate the avg, otherwise it sets avg to 0.

Then in the template you just show it with

{{avg}}

As @jeprubio mentioned, I'd delete the Input() and getMovie(idx) as they are not being used.

Lastly, keep in mind that you are not initializing avg, and if getOneMovie() fails for any reason, you'll never get to set it to a number (leading to errors in the template).


问:
How to save and load Markdown with React?
I'm new to React. I have an assignment building a Markdown Editor with Blockstack ID integrated.

I'm trying to save the content into a JSON file then load it again in the editor, but it seems like it can't load that JSON file back to the editor.

Here's some code:

```<code>import MDEditor from '@uiw/react-md-editor';

    <MDEditor
       onChange={e=>this.updateMarkdown(e)}
       value={this.state.markdown}
    />

             <button
              onClick={e => this.saveNewText(e)}>
              Submit Changes
             </button>

</code>```

```<code>  updateMarkdown(editor, data, value) {
    this.setState({ markdown: value})
  }

  saveNewText() {
    const { userSession } = this.props
    let currentDocument = this.state.currentDocument
    let newDocument = {
      md: this.state.markdown,
      created_at: Date.now()
    }

    const options = { encrypt: true }
    userSession.putFile('Document.json', JSON.stringify(newDocument), options)
      .then(() => {
        this.setState({
          currentDocument:newDocument
        })
      })
   }

  loadNewText() {
      const { userSession } = this.props
      const options = { decrypt: true }
      userSession.getFile('Document.json', options)
      .then((file) => {
          var docFile = JSON.parse(file || '[]');
          this.setState({
            currentDocument:docFile,
            markdown:docFile.md
          });
      })
    }

  componentWillMount() {
    const { userSession } = this.props
    this.setState({
      person: new Person(userSession.loadUserData().profile),
      username: userSession.loadUserData().username
    });
    this.loadNewText();
</code>```

答:
The react-blockstack package provides a useFile hook for React to persist content in the Blockstack Gaia storage:

const [document, setDocument] = useFile('Document.json')
```

This replaces most of your code except transformation between text and JSON.

Body:
I'm new to React. I have an assignment building a Markdown Editor with Blockstack ID integrated.

I'm trying to save the content into a JSON file then load it again in the editor, but it seems like it can't load that JSON file back to the editor.

Here's some code:

import MDEditor from '@uiw/react-md-editor';

    <MDEditor
       onChange={e=>this.updateMarkdown(e)}
       value={this.state.markdown}
    />

             <button
              onClick={e => this.saveNewText(e)}>
              Submit Changes
             </button>

  updateMarkdown(editor, data, value) {
    this.setState({ markdown: value})
  }

  saveNewText() {
    const { userSession } = this.props
    let currentDocument = this.state.currentDocument
    let newDocument = {
      md: this.state.markdown,
      created_at: Date.now()
    }

    const options = { encrypt: true }
    userSession.putFile('Document.json', JSON.stringify(newDocument), options)
      .then(() => {
        this.setState({
          currentDocument:newDocument
        })
      })
   }

  loadNewText() {
      const { userSession } = this.props
      const options = { decrypt: true }
      userSession.getFile('Document.json', options)
      .then((file) => {
          var docFile = JSON.parse(file || '[]');
          this.setState({
            currentDocument:docFile,
            markdown:docFile.md
          });
      })
    }

  componentWillMount() {
    const { userSession } = this.props
    this.setState({
      person: new Person(userSession.loadUserData().profile),
      username: userSession.loadUserData().username
    });
    this.loadNewText();

Body:
The react-blockstack package provides a useFile hook for React to persist content in the Blockstack Gaia storage:

const [document, setDocument] = useFile('Document.json')

This replaces most of your code except transformation between text and JSON.


问:
Requesting assist with postgresql query
Hey everyone. Here is my situation... I need to craft a sql query against a postgresql server that will return all records created within the past 5 minutes, rounded down to the lowest minute. So if cron kicks the query off at 12:05:25.000, it needs to query all records created since 12:00:00.000. So I guess I really have two issues.

Here is the current query:

```<code>select * from callhistory where created>date_trunc('minute', timestamp (current_timestamp-interval '5' minute));
</code>```

It doesn't return anything. Also, the format of the created field is "2011-05-18 18:11:32.024."

Any help would be appreciated.

答:
Here is a sample test I did against a PostgreSQL 8.3 server. You did not mention the version you are running.

```<code>select current_timestamp, to_char((current_timestamp - '5 minutes'::interval), 'yyyy-mm-dd HH:mi:00')::timestamp;
</code>```

The interval deducts the 5 minutes and to_char() method rounds down to the closest minute. If this is what you are looking for, then the query should look as follows:

```<code>select * from callhistory where created > to_char((current_timestamp - '5 minutes'::interval), 'yyyy-mm-dd HH:mi:00')::timestamp
</code>```

Title: Requesting assist with postgresql query

Body:
Hey everyone. Here is my situation... I need to craft a sql query against a postgresql server that will return all records created within the past 5 minutes, rounded down to the lowest minute. So if cron kicks the query off at 12:05:25.000, it needs to query all records created since 12:00:00.000. So I guess I really have two issues.

Here is the current query:

select * from callhistory where created>date_trunc('minute', timestamp (current_timestamp-interval '5' minute));

It doesn't return anything. Also, the format of the created field is "2011-05-18 18:11:32.024."

Any help would be appreciated.

Body:
Here is a sample test I did against a PostgreSQL 8.3 server. You did not mention the version you are running.

select current_timestamp, to_char((current_timestamp - '5 minutes'::interval), 'yyyy-mm-dd HH:mi:00')::timestamp;

The interval deducts the 5 minutes and to_char() method rounds down to the closest minute. If this is what you are looking for, then the query should look as follows:

select * from callhistory where created > to_char((current_timestamp - '5 minutes'::interval), 'yyyy-mm-dd HH:mi:00')::timestamp


问:
force src on @font-face using SASS
I have some custom fonts in my project and reference them by using @font-face.
But when the SASS is compiled the src gets all wrong, pointing to the original folder. I want it to point to the current folder where the CSS file is.

SASS:

```<code>@font-face {
    font-family: Default;
    src: url("Poppins-Medium.ttf");
}

@font-face {
    font-family: Regular;
    src: url("Poppips-Regular.ttf");
}

@font-face {
    font-family: SemiBold;
    src: url("Poppins-SemiBold.ttf");
}

@font-face {
    font-family: Bold;
    src: url("Poppins-Black.ttf");
}
</code>```

Compiled SASS:

```<code>@font-face {
  font-family: Default;
  src: url("../../STYLE/Layout/Poppins-Medium.ttf"); }

@font-face {
  font-family: Regular;
  src: url("../../STYLE/Layout/Poppips-Regular.ttf"); }

@font-face {
  font-family: SemiBold;
  src: url("../../STYLE/Layout/Poppins-SemiBold.ttf"); }

@font-face {
  font-family: Bold;
  src: url("../../STYLE/Layout/Poppins-Black.ttf"); }
</code>```

I want the source to be "Poppins-Black.ttf", since they are in the same folder.

答: I ended up copying the font files to the build folder and reference them from there,</p>

Title: force src on @font-face using SASS

Body:
I have some custom fonts in my project and reference them by using @font-face.
But when the SASS is compiled the src gets all wrong, pointing to the original folder. I want it to point to the current folder where the CSS file is.

SASS:

@font-face {
    font-family: Default;
    src: url("Poppins-Medium.ttf");
}

@font-face {
    font-family: Regular;
    src: url("Poppips-Regular.ttf");
}

@font-face {
    font-family: SemiBold;
    src: url("Poppins-SemiBold.ttf");
}

@font-face {
    font-family: Bold;
    src: url("Poppins-Black.ttf");
}

Compiled SASS:

@font-face {
  font-family: Default;
  src: url("../../STYLE/Layout/Poppins-Medium.ttf"); }

@font-face {
  font-family: Regular;
  src: url("../../STYLE/Layout/Poppips-Regular.ttf"); }

@font-face {
  font-family: SemiBold;
  src: url("../../STYLE/Layout/Poppins-SemiBold.ttf"); }

@font-face {
  font-family: Bold;
  src: url("../../STYLE/Layout/Poppins-Black.ttf"); }

I want the source to be "Poppins-Black.ttf", since they are in the same folder.


问:
Reading in ASCII file with uncommon formatting in Python
I've never worked with importing data from an ASCII file and I've noticed that different ASCII files have different formats so trying to find a general solution that works for any format has proven challenging for me.

I have a .dat (ASCII) file that I need to read in and extract the variables (see snippet of txt at bottom of question). Below is code from different attempts (separated by ###) of me trying to figure out how to read in the data.

```<code>f_41 = open(fileRS41, 'r')
data_41 = f_41.read()
for line in data_41:
    print(repr(line))
data_41.close()

############################

f = open(fileRS41, 'r')

# Read and ignore header lines
header1 = f.readline()
header2 = f.readline()
header3 = f.readline()

# Loop over lines and extract variables of interest
for line in f:
    line = line.strip()
    columns = line.split()
    name = columns[1] # Not sure what the different numbers do but this was code from another solution
    j = float(columns[1]) # ERROR: string can't be converted to float
    print(name, j)
f.close()

############################
from astropy.io import ascii
data = ascii.read(f_41, guess=False)
print(data)
############################
x = np.genfromtxt(f_41, dtype=None)
</code>```

Another option would be to convert this into a CSV file first and then use Pandas to work with it. However, when I do convert, the variable names get imported as a column stacked on top of each other versus one variable name per its respective column.

```<code># convert ASCII to CSV
f = open(file, 'r')
lines = f.readlines()

with open("FILEOUT.csv", 'w') as csvfile:
    writer = csv.writer(csvfile)
    for l in lines:
        asdf = l.split()
        writer.writerow(asdf)
print("out?")
</code>```

.dat file relevant sample:

```<code>Generated by Rfunction:  Get.mw41.edt.func2
============> Radisonde_info:
RS_type:        RS41-SGP
RS_config:      -32768
RS_serialnum:   R3340183
RS_freq:        403
RS__windtype:   ccGPS
=============> Station_info:
Station:        HUBV_RS41SGP
Latitude:       39.0563
Longitude:      -76.8755
Altitude:       52.3
SW version:     MW41 2.15.0
Start time:     2020-01-23 06:46:41
=============> Variables & units - Vaisala EDT
NA_numeric value:  -9999
NA_string:  xx or NA
-----------------------------
      Variable       Unit
          time        sec
            xx         NA
            Ta          K
            RH          %
       v(S->N)        m/s
       u(E->W)        m/s
        Height          m
         press        hPa
            Td          K
            MR       g/Kg
            DD        dgr
            FF        m/s
    Ascend_FLG  (0-N,1-Y)
            xx         NA
            xx         NA
           Lon        dgr
           Lat        dgr
            xx         NA
            xx         NA
            xx         NA
=============> Data:
   0.00  -9999.    268.37    85.00      0.00      0.00         52.3   1023.19    266.24     2.22       0.00      0.00 1  -9999.  -9999.   -76.8755    39.0563  -9999.  -9999.  -9999.
   0.81  -9999.    268.46    83.38      0.46      0.86         54.5   1022.90    266.08     2.19     241.86      0.98 1  -9999.  -9999.   -76.8757    39.0564  -9999.  -9999.  -9999.
</code>```

答:
I found one solution that works but I would like to avoid hard-coding column headers and be able to read them directly from the ASCII file:</p>

```<code># set the directory for data files
fileRS41 = 'filename.dat'

# load text from .dat files
f41 = np.loadtxt(fileRS41, skiprows = 40)

# create column names for variables
c = ['time' , 'xx0', 'temp', 'RH', 'v(S_N)', 'u(E_W)', 'height', 'pressure', 'Td', 'mixingratio', 'DD', 'FF', 'Ascend_FLG', 'xx1', 'xx2', 'lon', 'lat', 'xx3', 'xx4', 'xx5']

# skip columns when reading in file and converting to dataFrame
skip = ['xx0', 'DD', 'FF', 'Ascend_FLG', 'xx1', 'xx2', 'xx3', 'xx4', 'xx5']

# convert to Pandas Dataframe
df_f41 = pd.DataFrame.from_records(f41, exclude=skip, columns = c)

</code>```

Body:
I've never worked with importing data from an ASCII file and I've noticed that different ASCII files have different formats so trying to find a general solution that works for any format has proven challenging for me.

I have a .dat (ASCII) file that I need to read in and extract the variables (see snippet of txt at bottom of question). Below is code from different attempts (separated by ###) of me trying to figure out how to read in the data.

f_41 = open(fileRS41, 'r')
data_41 = f_41.read()
for line in data_41:
    print(repr(line))
data_41.close()

############################

f = open(fileRS41, 'r')

# Read and ignore header lines
header1 = f.readline()
header2 = f.readline()
header3 = f.readline()

# Loop over lines and extract variables of interest
for line in f:
    line = line.strip()
    columns = line.split()
    name = columns[1] # Not sure what the different numbers do but this was code from another solution
    j = float(columns[1]) # ERROR: string can't be converted to float
    print(name, j)
f.close()

############################
from astropy.io import ascii
data = ascii.read(f_41, guess=False)
print(data)
############################
x = np.genfromtxt(f_41, dtype=None)

Another option would be to convert this into a CSV file first and then use Pandas to work with it. However, when I do convert, the variable names get imported as a column stacked on top of each other versus one variable name per its respective column.

# convert ASCII to CSV
f = open(file, 'r')
lines = f.readlines()

with open("FILEOUT.csv", 'w') as csvfile:
    writer = csv.writer(csvfile)
    for l in lines:
        asdf = l.split()
        writer.writerow(asdf)
print("out?")

.dat file relevant sample:

Generated by Rfunction:  Get.mw41.edt.func2
============> Radisonde_info:
RS_type:        RS41-SGP
RS_config:      -32768
RS_serialnum:   R3340183
RS_freq:        403
RS__windtype:   ccGPS
=============> Station_info:
Station:        HUBV_RS41SGP
Latitude:       39.0563
Longitude:      -76.8755
Altitude:       52.3
SW version:     MW41 2.15.0
Start time:     2020-01-23 06:46:41
=============> Variables & units - Vaisala EDT
NA_numeric value:  -9999
NA_string:  xx or NA
-----------------------------
      Variable       Unit
          time        sec
            xx         NA
            Ta          K
            RH          %
       v(S->N)        m/s
       u(E->W)        m/s
        Height          m
         press        hPa
            Td          K
            MR       g/Kg
            DD        dgr
            FF        m/s
    Ascend_FLG  (0-N,1-Y)
            xx         NA
            xx         NA
           Lon        dgr
           Lat        dgr
            xx         NA
            xx         NA
            xx         NA
=============> Data:
   0.00  -9999.    268.37    85.00      0.00      0.00         52.3   1023.19    266.24     2.22       0.00      0.00 1  -9999.  -9999.   -76.8755    39.0563  -9999.  -9999.  -9999.
   0.81  -9999.    268.46    83.38      0.46      0.86         54.5   1022.90    266.08     2.19     241.86      0.98 1  -9999.  -9999.   -76.8757    39.0564  -9999.  -9999.  -9999.

Body:
I found one solution that works but I would like to avoid hard-coding column headers and be able to read them directly from the ASCII file:

# set the directory for data files
fileRS41 = 'filename.dat'

# load text from .dat files
f41 = np.loadtxt(fileRS41, skiprows = 40)

# create column names for variables
c = ['time' , 'xx0', 'temp', 'RH', 'v(S_N)', 'u(E_W)', 'height', 'pressure', 'Td', 'mixingratio', 'DD', 'FF', 'Ascend_FLG', 'xx1', 'xx2', 'lon', 'lat', 'xx3', 'xx4', 'xx5']

# skip columns when reading in file and converting to dataFrame
skip = ['xx0', 'DD', 'FF', 'Ascend_FLG', 'xx1', 'xx2', 'xx3', 'xx4', 'xx5']

# convert to Pandas Dataframe
df_f41 = pd.DataFrame.from_records(f41, exclude=skip, columns = c)


问:
Create Object (in ViewSet class) with Celery Task in Django
Hello I encountered a problem which i am not able to solve by myself. I tried to call function create_with_celery inside create but it didnt work

How should I call create.delay with proper arguments?
I don't know how to properly call create function to make workers create objects

```<code>class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    @app.task(bind=True)
    def create(self, request):
        article = Article.objects.create(link=request.data['link'])
        article.save()
        serializer = ArticleSerializer(article, many=False)

        words = WordList(article.link)
        # take every 90nth word for faster loading only dev approach
        i = 0
        for word in range(0, len(words.list)):

            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,
                                                                   len(words.list), words[word]))

        response = {'message': 'Article created ', 'result': serializer.data}
        return Response(response, status=status.HTTP_200_OK)
</code>```

Im trying to do something like this but I get error "Object of type 'Article' is not JSON serializable"

```<code>class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    @app.task(bind=True)
    def create_with_celery(self, article, serializer, words, req):
        i = 0
        for word in range(0, len(words.list)):
            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )

                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,len(words.list), words[word]))

def create(self, request):
    article = Article.objects.create(link=request.data['link'])
    article.save()
    serializer = ArticleSerializer(article, many=False)
    words = WordList(article.link)
    req = request

    self.create_with_celery.delay(article, serializer, words, req)

    response = {'message': 'Article created ', 'result': serializer.data}
    return Response(response, status=status.HTTP_200_OK)
</code>```

答: Take in mind that celery is a good tool to process async data, as I see what you try to do on ArticleViewSet, you could achieve that directly on the save method of the ArticleSerializer.

Body:
Hello I encountered a problem which i am not able to solve by myself. I tried to call function create_with_celery inside create but it didnt work

How should I call create.delay with proper arguments?
I don't know how to properly call create function to make workers create objects

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    @app.task(bind=True)
    def create(self, request):
        article = Article.objects.create(link=request.data['link'])
        article.save()
        serializer = ArticleSerializer(article, many=False)

        words = WordList(article.link)
        # take every 90nth word for faster loading only dev approach
        i = 0
        for word in range(0, len(words.list)):

            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,
                                                                   len(words.list), words[word]))

        response = {'message': 'Article created ', 'result': serializer.data}
        return Response(response, status=status.HTTP_200_OK)

Im trying to do something like this but I get error "Object of type 'Article' is not JSON serializable"

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    @app.task(bind=True)
    def create_with_celery(self, article, serializer, words, req):
        i = 0
        for word in range(0, len(words.list)):
            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )

                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,len(words.list), words[word]))

def create(self, request):
    article = Article.objects.create(link=request.data['link'])
    article.save()
    serializer = ArticleSerializer(article, many=False)
    words = WordList(article.link)
    req = request

    self.create_with_celery.delay(article, serializer, words, req)

    response = {'message': 'Article created ', 'result': serializer.data}
    return Response(response, status=status.HTTP_200_OK)


问:
Is there a way to add CSS to a title element in a SVG file?
I am working on an SVG file that has a number of <path> tags. I also have a <title> tag for each of these <path> tags. I have text inside the <title> tag such that when I hover over the <path> element, it displays the text. However, the text is the default format, bland text with an ugly looking border box etc.

Is there a way where I can use CSS to modify the <title> tag so that it can look better?

This is what I have thus far:

```<code> <title>
      Title Tag!!!
 </title>
 <path d="M696.393,-204.269C703.418,-219.592 708.202,-238.899 697,-252 671.205,-282.169 562.896,-290.806 492.399,-293.194" fill="none" stroke="green" stroke-width="3"></path>
</code>```

答:
Unfortunately this is browser element and you cannot style it.

If that helps you could make custom tooltip by yourself, look for example here.
Making custom tooltip will probably require some amendments in your code though.

Body:
I am working on an SVG file that has a number of <path> tags. I also have a <title> tag for each of these <path> tags. I have text inside the <title> tag such that when I hover over the <path> element, it displays the text. However, the text is the default format, bland text with an ugly looking border box etc.

Is there a way where I can use CSS to modify the <title> tag so that it can look better?

This is what I have thus far:

 <title>
      Title Tag!!!
 </title>
 <path d="M696.393,-204.269C703.418,-219.592 708.202,-238.899 697,-252 671.205,-282.169 562.896,-290.806 492.399,-293.194" fill="none" stroke="green" stroke-width="3"></path>


问:
Android byte[] to image in Camera.onPreviewFrame
When trying to convert the byte[] of Camera.onPreviewFrame to Bitamp using BitmapFactory.decodeByteArray gives me an error SkImageDecoder::Factory returned null

Following is my code:

```<code>public void onPreviewFrame(byte[] data, Camera camera) {
    Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length);
}
</code>```

答:
This has been hard to find! But since API 8, there is a YuvImage class in android.graphics. It's not an Image descendent, so all you can do with it is save it to Jpeg, but you could save it to memory stream and then load into Bitmap Image if that's what you need.</p>

```<code>import android.graphics.YuvImage;

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
    try {
        Camera.Parameters parameters = camera.getParameters();
        Size size = parameters.getPreviewSize();
        YuvImage image = new YuvImage(data, parameters.getPreviewFormat(),
                size.width, size.height, null);
        File file = new File(Environment.getExternalStorageDirectory()
                .getPath() + "/out.jpg");
        FileOutputStream filecon = new FileOutputStream(file);
        image.compressToJpeg(
                new Rect(0, 0, image.getWidth(), image.getHeight()), 90,
                filecon);
    } catch (FileNotFoundException e) {
        Toast toast = Toast
                .makeText(getBaseContext(), e.getMessage(), 1000);
        toast.show();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When trying to convert the byte[] of Camera.onPreviewFrame to Bitamp using BitmapFactory.decodeByteArray gives me an error SkImageDecoder::Factory returned null

Following is my code:

public void onPreviewFrame(byte[] data, Camera camera) {
    Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length);
}

Body:
This has been hard to find! But since API 8, there is a YuvImage class in android.graphics. It's not an Image descendent, so all you can do with it is save it to Jpeg, but you could save it to memory stream and then load into Bitmap Image if that's what you need.

import android.graphics.YuvImage;

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
    try {
        Camera.Parameters parameters = camera.getParameters();
        Size size = parameters.getPreviewSize();
        YuvImage image = new YuvImage(data, parameters.getPreviewFormat(),
                size.width, size.height, null);
        File file = new File(Environment.getExternalStorageDirectory()
                .getPath() + "/out.jpg");
        FileOutputStream filecon = new FileOutputStream(file);
        image.compressToJpeg(
                new Rect(0, 0, image.getWidth(), image.getHeight()), 90,
                filecon);
    } catch (FileNotFoundException e) {
        Toast toast = Toast
                .makeText(getBaseContext(), e.getMessage(), 1000);
        toast.show();
    }
}


问:
How do I use the setStartupBehavior API call?
I am trying to register event handlers when a document first opens up in Excel as it shows in the documentation. However, it tells me that I need to configure my code to include this: Office.addin.setStartupBehavior(Office.StartupBehavior.load); I'm not too sure where I am supposed to use this. I created my project using the yeoman generator for Office.</p>

答:
It depends on whether you want the users to decide whether the add-in runs when the file opens or whether you want to ensure that it does. If you want the user to decide, include this line of code in an event handler for a button or other UI. There's a sample add-in that does this at: Excel shared runtime scenarios.

If you want to ensure that the add-in runs whenever the file opens, then include the line of code in the Office.initialize method or Office.onReady method. The first time the file opens, the add-in will not run immediately and the user will have to manually invoke it. But, after that, the add-in will run whenever that file is opened.