问:
Use of full-text search + GIN in a view (Django 1.11 )
I need some help with building proper query in a django view for full-text search using GIN index. I have quite a big database (~400k lines) and need to do a full-text search on 3 fields from it. Tried to use django docs search and this is code BEFORE GIN. It works, but takes 6+ seconds to search over all fields. Next I tried to implement a GIN index to speed up my search. There are a lot of questions already how to build it. But my question is - how does the view query change when using a GIN index for search? What fields should I search?

Before GIN:

models.py

class Product(TimeStampedModel):
    product_id = models.AutoField(primary_key=True)
    shop = models.ForeignKey("Shop", to_field="shop_name")
    brand = models.ForeignKey("Brand", to_field="brand_name")
    title = models.TextField(blank=False, null=False)
    description = models.TextField(blank=True, null=True)
```
<p><em>views.py</em><br></p>
<pre class="lang-py prettyprint-override"><code>
def get_cosmetic(request):
    if request.method == "GET":
        pass
    else:
        search_words = request.POST.get("search")
        search_vectors = (
            SearchVector("title", weight="B")
            + SearchVector("description", weight="C")
            + SearchVector("brand__brand_name", weight="A")
        )

        products = (
            Product.objects.annotate(
                search=search_vectors, rank=SearchRank(search_vectors, search)
            )
            .filter(search=search_words)
            .order_by("-rank")
        )

        return render(request, "example.html", {"products": products})
</code>```

After GIN:

models.py

class ProductManager(models.Manager):
    def with_documents(self):
        vector = (
            pg_search.SearchVector("brand__brand_name", weight="A")
            + pg_search.SearchVector("title", weight="A")
            + pg_search.SearchVector("description", weight="C")
        )
        return self.get_queryset().annotate(document=vector)

class Product(TimeStampedModel):
    product_id = models.AutoField(primary_key=True)
    shop = models.ForeignKey("Shop", to_field="shop_name")
    brand = models.ForeignKey("Brand", to_field="brand_name")
    title = models.TextField(blank=False, null=False)
    description = models.TextField(blank=True, null=True)

    search_vector = pg_search.SearchVectorField(null=True)

    objects = ProductManager()

    class Meta:
        indexes = [
            indexes.GinIndex(
                fields=["search_vector"],
                name="title_index",
            ),
        ]

    # update search_vector every time the entry updates
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if (
            "update_fields" not in kwargs
            or "search_vector" not in kwargs["update_fields"]
        ):
            instance = (
                self._meta.default_manager
                .with_documents().get(pk=self.pk)
            )
            instance.search_vector = instance.document
            instance.save(update_fields=["search_vector"])
```
<p><em>views.py</em><br></p>
<pre class="lang-py prettyprint-override"><code>def get_cosmetic(request):
    if request.method == "GET":
        pass

    else:
        search_words = request.POST.get('search')
        products = ?????????
        return render(request, 'example.html', {"products": products})
</code>```

答:
Answering my own question:

products = (
    Product.objects.annotate(rank=SearchRank(F("search_vector"), search_words))
    .filter(search_vector=search_words)
    .order_by("-rank")
)
```
<p><br>This means you should search your index field - in my case <code>search_vector</code> field.<br>
Also I have changed my code a bit in ProductManager() class, so now I can just use<br></p>
```products = Product.objects.with_documents(search_words)
```

Where with_documents() is a custom function of custom ProductManager(). The recipe of this change is here (page 29).

What does all this code do:

creates search_vector with scores to fields, field with bigger score - gets higher place in result sorting.

creates GIN index for full-text search via ORM Django

updates GIN index every time the instance of model is changed

What this code dosn't do:

It doesn't sort by relevance of substring which is queried. Possible solution.

Hope this will help somebody with a bit complicated full-text search in Django.

Body:
I need some help with building proper query in a django view for full-text search using GIN index. I have quite a big database (~400k lines) and need to do a full-text search on 3 fields from it. Tried to use django docs search and this is code BEFORE GIN. It works, but takes 6+ seconds to search over all fields. Next I tried to implement a GIN index to speed up my search. There are a lot of questions already how to build it. But my question is - how does the view query change when using a GIN index for search? What fields should I search?

Before GIN:

models.py

class Product(TimeStampedModel):
    product_id = models.AutoField(primary_key=True)
    shop = models.ForeignKey("Shop", to_field="shop_name")
    brand = models.ForeignKey("Brand", to_field="brand_name")
    title = models.TextField(blank=False, null=False)
    description = models.TextField(blank=True, null=True)

views.py

def get_cosmetic(request):
    if request.method == "GET":
        pass
    else:
        search_words = request.POST.get("search")
        search_vectors = (
            SearchVector("title", weight="B")
            + SearchVector("description", weight="C")
            + SearchVector("brand__brand_name", weight="A")
        )

        products = (
            Product.objects.annotate(
                search=search_vectors, rank=SearchRank(search_vectors, search)
            )
            .filter(search=search_words)
            .order_by("-rank")
        )

        return render(request, "example.html", {"products": products})

After GIN:

models.py

class ProductManager(models.Manager):
    def with_documents(self):
        vector = (
            pg_search.SearchVector("brand__brand_name", weight="A")
            + pg_search.SearchVector("title", weight="A")
            + pg_search.SearchVector("description", weight="C")
        )
        return self.get_queryset().annotate(document=vector)

class Product(TimeStampedModel):
    product_id = models.AutoField(primary_key=True)
    shop = models.ForeignKey("Shop", to_field="shop_name")
    brand = models.ForeignKey("Brand", to_field="brand_name")
    title = models.TextField(blank=False, null=False)
    description = models.TextField(blank=True, null=True)

    search_vector = pg_search.SearchVectorField(null=True)

    objects = ProductManager()

    class Meta:
        indexes = [
            indexes.GinIndex(
                fields=["search_vector"],
                name="title_index",
            ),
        ]

    # update search_vector every time the entry updates
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if (
            "update_fields" not in kwargs
            or "search_vector" not in kwargs["update_fields"]
        ):
            instance = (
                self._meta.default_manager
                .with_documents().get(pk=self.pk)
            )
            instance.search_vector = instance.document
            instance.save(update_fields=["search_vector"])

views.py

def get_cosmetic(request):
    if request.method == "GET":
        pass

    else:
        search_words = request.POST.get('search')
        products = ?????????
        return render(request, 'example.html', {"products": products})

Body:
Answering my own question:

products = (
    Product.objects.annotate(rank=SearchRank(F("search_vector"), search_words))
    .filter(search_vector=search_words)
    .order_by("-rank")
)

This means you should search your index field - in my case search_vector field.

Also I have changed my code a bit in ProductManager() class, so now I can just use

products = Product.objects.with_documents(search_words)

Where with_documents() is a custom function of custom ProductManager(). The recipe of this change is here (page 29).

What does all this code do:

creates search_vector with scores to fields, field with bigger score - gets higher place in result sorting.

creates GIN index for full-text search via ORM Django

updates GIN index every time the instance of model is changed

What this code dosn't do:

It doesn't sort by relevance of substring which is queried. Possible solution.

Hope this will help somebody with a bit complicated full-text search in Django.


来源: stackexchange

问:
err == errSecAuthFailed works fine on simulator but fails on device
I try to use

```<code>err == errSecAuthFailed
</code>```

like here link

This works fine on simulator but fails on ios Device.. does someone know why??
As you can see on the link Apple also uses this. When I try this on device I get

```<code>Use of undeclared identifier 'errSecAuthFailed'
</code>```

THX!

答: Try adding #import <Security/SecBase.h> on top of the file where the error occurs.

ContentLicense: CC BY-SA 3.0

Body:
I try to use

err == errSecAuthFailed

like here link

This works fine on simulator but fails on ios Device.. does someone know why??
As you can see on the link Apple also uses this. When I try this on device I get

Use of undeclared identifier 'errSecAuthFailed'

THX!


问:
ORDER BY in statement before UNION ALL
I have this query :

```<code>SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona I')  AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
         OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)

UNION ALL

SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona II') AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND NOT ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
             OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
ORDER BY
    NAZIV
</code>```

This query orders by 'NAZIV' whole statement after union all.

But i want both query to order by 'NAZIV' before UNION ALL

答:
Add another column so you can get the order you want:</p>

```<code>SELECT DISTINCT
    '1' AS ZONA,
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona I')  AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
        OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
UNION ALL
SELECT DISTINCT
    '2',
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona II') AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND NOT ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
         OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
ORDER BY
    ZONA, NAZIV
</code>```

Title: ORDER BY in statement before UNION ALL

Body:
I have this query :

SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona I')  AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
         OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)

UNION ALL

SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona II') AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND NOT ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
             OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
ORDER BY
    NAZIV

This query orders by 'NAZIV' whole statement after union all.

But i want both query to order by 'NAZIV' before UNION ALL

Body:
Add another column so you can get the order you want:

SELECT DISTINCT
    '1' AS ZONA,
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona I')  AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
        OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
UNION ALL
SELECT DISTINCT
    '2',
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona II') AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND NOT ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
         OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
ORDER BY
    ZONA, NAZIV


问:
X-Okta-XsrfToken and JS Widget
I've noticed that when JS component makes calls to authorise (/api/v1/authn) its got an empty header in the request called 'X-Okta-XsrfToken'.

Should that be set or is it defunct?

答:
It's a bug - X-Okta-XsrfToken isn't needed in the /authn requests. I've filed this issue for the team to fix:
https://github.com/okta/okta-signin-widget/issues/359</p>

ContentLicense: CC BY-SA 4.0

Title: X-Okta-XsrfToken and JS Widget


问:
SIGBUS when trying to increment a std::map iterator
I am debugging a big C++98 application and I am obtaining a SIBGUS error when a method tries to increment a std::map::iterator.

By putiing traces, I have discovered that the method in question removes elements from the mentioned map (indireclty, by calling other methods that call other methods and so on...), so I suspect that the problem is to been iterating over the map while deleting its elements.

I have been searching the proper way to iterate over a std::map and delete items safelly, and I have found this:

```<code>for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    ++it;
  }
}
</code>```

Code quoted from How to remove from a map while iterating it?

I have some questions about this:

Is it actually necessary to distinguis between deleting elements or not, taking into account that the iterator is going to be increased in any case?

Is the following code snippet equivalent to the above one, in terms of safety?

```<code>for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it);
  }
  it++;
}
</code>```

The method that is producing the SIGBUS follows the following pattern:

```<code>std::map<..., ...>::iterator it = myMap.begin(); // myMap is an instance attribute and can be accessed by any class method.

while(it != myMap.end() {
  if(somethingHappens())
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete 'myMap' elements.
  it++; // The error occurs here
}
</code>```

Since the deletion is performed by other method/s, I cannot distinguis if an element has been deleted or not (unless I return a boolean value or similar). Is this potentially unsafe?

答:
Is the following code snippet equivalent to the above one, in terms of safety?

No, of course not, you cannot increase it after you passed it to map.erase() as that iterator is invalidated by that call. Difference is:

```<code> map.erase(it++);
</code>```

is logically equivalent to:

```<code>iterator tmp = it;
++it;
map.erase( tmp );
</code>```

So in this case tmp is invalidated, but it is still valid.

Considering this code:

```<code>while(it != myMap.end() {
  if(somethingHappens())
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete 'myMap' elements.
  it++; // The error occurs here
}
</code>```

I think only viable way would be this:

```<code>while(it != myMap.end() {
  if(somethingHappens()) {
    key_type key = it->first();
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete          'myMap' elements.
    it = myMap.upper_bound( key );
  } else
     it++;
}
</code>```

Body:
I am debugging a big C++98 application and I am obtaining a SIBGUS error when a method tries to increment a std::map::iterator.

By putiing traces, I have discovered that the method in question removes elements from the mentioned map (indireclty, by calling other methods that call other methods and so on...), so I suspect that the problem is to been iterating over the map while deleting its elements.

I have been searching the proper way to iterate over a std::map and delete items safelly, and I have found this:

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    ++it;
  }
}

Code quoted from How to remove from a map while iterating it?

I have some questions about this:

Is it actually necessary to distinguis between deleting elements or not, taking into account that the iterator is going to be increased in any case?

Is the following code snippet equivalent to the above one, in terms of safety?

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it);
  }
  it++;
}

The method that is producing the SIGBUS follows the following pattern:

std::map<..., ...>::iterator it = myMap.begin(); // myMap is an instance attribute and can be accessed by any class method.

while(it != myMap.end() {
  if(somethingHappens())
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete 'myMap' elements.
  it++; // The error occurs here
}

Since the deletion is performed by other method/s, I cannot distinguis if an element has been deleted or not (unless I return a boolean value or similar). Is this potentially unsafe?

Body:
Is the following code snippet equivalent to the above one, in terms of safety?

No, of course not, you cannot increase it after you passed it to map.erase() as that iterator is invalidated by that call. Difference is:

 map.erase(it++);

is logically equivalent to:

iterator tmp = it;
++it;
map.erase( tmp );

So in this case tmp is invalidated, but it is still valid.

Considering this code:

while(it != myMap.end() {
  if(somethingHappens())
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete 'myMap' elements.
  it++; // The error occurs here
}

I think only viable way would be this:

while(it != myMap.end() {
  if(somethingHappens()) {
    key_type key = it->first();
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete          'myMap' elements.
    it = myMap.upper_bound( key );
  } else
     it++;
}


问:
Lower WebGL Render Resolution, and Increase FPS
I am having a problem with rendering 2d sprites to a GL canvas. When my browser is on a lower resolution monitor it renders at a higher FPS than if it's rendering in a higher resolution monitor.

Mac Retina Display: 2880x1800 = ~20 FPS

External Monitor: 1920x1080 = ~60 FPS

WebGL is rendering at a faster FPS on my 1080 resolution monitor than it is on the Mac retina display.

What is the best practice to force WebGL to render at a lower resolution? I have tried looking for sources to help answer this but can't find anything online.

I've tried lowering the resolution as follows:

```<code>var ratio = 1
var width = $(window).width();
var height = $(window).height();
if (window.screen.height * window.devicePixelRatio > 1080) {
   ratio = 1080/(window.screen.height * window.devicePixelRatio);
}
width = width*ratio;
height = height*ratio;
gl.canvas.width = width;
gl.canvas.height = height;
</code>```

And then setting my viewport like this:

```<code>gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
</code>```

Update to code

```<code>var width = $(window).width();
var height = $(window).height();
if (window.screen.height * window.devicePixelRatio > 1080) {
   glTools.ratio = 1080/(window.screen.height * window.devicePixelRatio);
} else {
   glTools.ratio = 1;
}
width = Math.round(width*glTools.ratio);
height = Math.round(height*glTools.ratio);
glTools.gl.canvas.width = width;
glTools.gl.canvas.height = height;
glTools.gl.viewport(0, 0, width, height);
</code>```

Performance Update
Although the answer to this question is correct. I just wanted to point another culprit to my FPS in my video game. Having timers in my code and performing non-hardware accelerated css animations in my game managed to block the thread and therefore cause the render to be scheduled for later.
You can see that the game renders at 60FPS at Obsidio

答:
Per MDN's WebGL best practices:

Rendering to a canvas can be done at a different resolution than the
  style sheet will eventually force the canvas to appear at. If
  struggling with performance you should consider rendering to a low
  resolution WebGL context and using CSS to upscale its canvas to the
  size you intend.

WebGL will render based on your canvas' width and height attributes.  A canvas that looks like this: <canvas width="256" height="256"> will render at 256x256.  However, you can then scale up your drawing by styling your canvas with CSS: canvas {width: 512px;height: 512px;} will display your rendered image at an upscaled 512x512.

Run the snippet below and you'll see the output:

[Canvas internal rendering] W: 256 | H: 256
[Actual canvas size] W: 512 | H: 512
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const canvas = document.querySelector("canvas"),
  ctx = canvas.getContext("webgl"),
  {
    width,
    height
  } = canvas.getBoundingClientRect();

console.log(`[Canvas internal rendering] W: ${ctx.drawingBufferWidth} | H: ${ctx.drawingBufferHeight}`);
console.log(`[Actual canvas size] W: ${width} | H: ${height}`);</code>```

canvas {
  width: 512px;
  height: 512px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas width="256" height="256"></code>```

After looking at your code, the reason your game seems to "zoom in", is because you are tying your viewport to your rendering size.  Don't couple these.  Your viewport settings should definitely mirror your aspect ratio, but should be independent of your drawing size.  WebGL will default it to your canvas size, but since you want to upscale, try setting it to the upscaled canvas size and see if you still get a zoom.  From my above example, the code would look like:

```<code>ctx.viewport(0, 0, width, height);
</code>```

Where width and height come from the computed element's size.

Upscaling Example:

Here is a demo showing the differing rending resolutions of the same shape.  You will see aliasing in the first image, but the second image should be clear.

const vertSource = `
attribute vec3 a_position;
void main(void) {
    gl_Position = vec4((a_position * 2.0) - 1.0, 1.0);
}`;

const fragSource = `
void main(void) {
    gl_FragColor = vec4(1.0);
}`;

const verts = [
  0.1, 0.1, 0,
  0.9, 0.1, 0,
  0.5, 0.9, 0
];

function setupCanvas(canvas) {
  const gl = canvas.getContext("webgl");

  const {
    width,
    height
  } = canvas.getBoundingClientRect();

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.enable(gl.DEPTH_TEST);
  gl.viewport(0.0, 0.0, gl.drawingBufferWidth, gl.drawingBufferHeight);

  console.log(`[Canvas internal rendering] W: ${gl.drawingBufferWidth} | H: ${gl.drawingBufferHeight}`);
  console.log(`[Actual canvas size] W: ${width} | H: ${height}`);

  const b = gl.createBuffer(),
    p = gl.createProgram(),
    v = gl.createShader(gl.VERTEX_SHADER),
    f = gl.createShader(gl.FRAGMENT_SHADER);

  gl.bindBuffer(gl.ARRAY_BUFFER, b);
  gl.shaderSource(v, vertSource);
  gl.compileShader(v);
  gl.shaderSource(f, fragSource);
  gl.compileShader(f);
  gl.attachShader(p, v);
  gl.attachShader(p, f);
  gl.linkProgram(p);
  gl.useProgram(p);

  const a = gl.getAttribLocation(p, "a_position");
  gl.vertexAttribPointer(a, 3, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(a);

  function draw() {
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.DYNAMIC_DRAW);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, verts.length / 3);
  }
  draw();
}

Array.from(document.querySelectorAll("canvas"))
  .forEach(setupCanvas);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  width: 512px;
  height: 512px;
}</code>```

<canvas width="256" height="256"></canvas>
<canvas width="512" height="512"></canvas>```

Body:
I am having a problem with rendering 2d sprites to a GL canvas. When my browser is on a lower resolution monitor it renders at a higher FPS than if it's rendering in a higher resolution monitor.

Mac Retina Display: 2880x1800 = ~20 FPS

External Monitor: 1920x1080 = ~60 FPS

WebGL is rendering at a faster FPS on my 1080 resolution monitor than it is on the Mac retina display.

What is the best practice to force WebGL to render at a lower resolution? I have tried looking for sources to help answer this but can't find anything online.

I've tried lowering the resolution as follows:

var ratio = 1
var width = $(window).width();
var height = $(window).height();
if (window.screen.height * window.devicePixelRatio > 1080) {
   ratio = 1080/(window.screen.height * window.devicePixelRatio);
}
width = width*ratio;
height = height*ratio;
gl.canvas.width = width;
gl.canvas.height = height;

And then setting my viewport like this:

gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);

Update to code

var width = $(window).width();
var height = $(window).height();
if (window.screen.height * window.devicePixelRatio > 1080) {
   glTools.ratio = 1080/(window.screen.height * window.devicePixelRatio);
} else {
   glTools.ratio = 1;
}
width = Math.round(width*glTools.ratio);
height = Math.round(height*glTools.ratio);
glTools.gl.canvas.width = width;
glTools.gl.canvas.height = height;
glTools.gl.viewport(0, 0, width, height);

Performance Update
Although the answer to this question is correct. I just wanted to point another culprit to my FPS in my video game. Having timers in my code and performing non-hardware accelerated css animations in my game managed to block the thread and therefore cause the render to be scheduled for later.
You can see that the game renders at 60FPS at Obsidio

Body:
Per MDN's WebGL best practices:

Rendering to a canvas can be done at a different resolution than the
  style sheet will eventually force the canvas to appear at. If
  struggling with performance you should consider rendering to a low
  resolution WebGL context and using CSS to upscale its canvas to the
  size you intend.

WebGL will render based on your canvas' width and height attributes.  A canvas that looks like this: <canvas width="256" height="256"> will render at 256x256.  However, you can then scale up your drawing by styling your canvas with CSS: canvas {width: 512px;height: 512px;} will display your rendered image at an upscaled 512x512.

Run the snippet below and you'll see the output:

[Canvas internal rendering] W: 256 | H: 256
[Actual canvas size] W: 512 | H: 512

const canvas = document.querySelector("canvas"),
  ctx = canvas.getContext("webgl"),
  {
    width,
    height
  } = canvas.getBoundingClientRect();

console.log(`[Canvas internal rendering] W: ${ctx.drawingBufferWidth} | H: ${ctx.drawingBufferHeight}`);
console.log(`[Actual canvas size] W: ${width} | H: ${height}`);

canvas {
  width: 512px;
  height: 512px;
}

<canvas width="256" height="256">

After looking at your code, the reason your game seems to "zoom in", is because you are tying your viewport to your rendering size.  Don't couple these.  Your viewport settings should definitely mirror your aspect ratio, but should be independent of your drawing size.  WebGL will default it to your canvas size, but since you want to upscale, try setting it to the upscaled canvas size and see if you still get a zoom.  From my above example, the code would look like:

ctx.viewport(0, 0, width, height);

Where width and height come from the computed element's size.

Upscaling Example:

Here is a demo showing the differing rending resolutions of the same shape.  You will see aliasing in the first image, but the second image should be clear.

const vertSource = `
attribute vec3 a_position;
void main(void) {
    gl_Position = vec4((a_position * 2.0) - 1.0, 1.0);
}`;

const fragSource = `
void main(void) {
    gl_FragColor = vec4(1.0);
}`;

const verts = [
  0.1, 0.1, 0,
  0.9, 0.1, 0,
  0.5, 0.9, 0
];

function setupCanvas(canvas) {
  const gl = canvas.getContext("webgl");

  const {
    width,
    height
  } = canvas.getBoundingClientRect();

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.enable(gl.DEPTH_TEST);
  gl.viewport(0.0, 0.0, gl.drawingBufferWidth, gl.drawingBufferHeight);

  console.log(`[Canvas internal rendering] W: ${gl.drawingBufferWidth} | H: ${gl.drawingBufferHeight}`);
  console.log(`[Actual canvas size] W: ${width} | H: ${height}`);

  const b = gl.createBuffer(),
    p = gl.createProgram(),
    v = gl.createShader(gl.VERTEX_SHADER),
    f = gl.createShader(gl.FRAGMENT_SHADER);

  gl.bindBuffer(gl.ARRAY_BUFFER, b);
  gl.shaderSource(v, vertSource);
  gl.compileShader(v);
  gl.shaderSource(f, fragSource);
  gl.compileShader(f);
  gl.attachShader(p, v);
  gl.attachShader(p, f);
  gl.linkProgram(p);
  gl.useProgram(p);

  const a = gl.getAttribLocation(p, "a_position");
  gl.vertexAttribPointer(a, 3, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(a);

  function draw() {
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.DYNAMIC_DRAW);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, verts.length / 3);
  }
  draw();
}

Array.from(document.querySelectorAll("canvas"))
  .forEach(setupCanvas);

canvas {
  width: 512px;
  height: 512px;
}

<canvas width="256" height="256"></canvas>
<canvas width="512" height="512"></canvas>


问:
C# reading XML values using LINQ to XML
I have created a function that reads a third party XML document to get the conversion rate of Euros to GBP on any given date, however my linq query is returning a null value.

XML:

```<code><therate xmlns="http://somecurrencysite.com">
    <terms>someValue</terms>
    <from>EUR</from>
    <amount>1.0</amount>
    <timestamp>2001-05-01T06:00:00Z</timestamp>
    <to>
        <rate>
            <currency>GBP</currency>
            <dayrate>0.619887217</dayrate>
        </rate>
    </to>
</therate>
</code>```

C#:

```<code>var uri = "http://somecurrencysite.com?date=" + date.ToString("yyyy-MM-dd") + "&to=GBP";

decimal rate;

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential("userName", "passWord");

    try
    {
        var source = new MemoryStream(client.DownloadData(uri));
        var xRdr = new XmlTextReader(source);
        rate = XDocument.Load(xRdr)
            .Descendants("rate")
            .Select(e => (decimal)e.Element("dayrate"))
            .FirstOrDefault();
    }
    catch (Exception ex)
    {
        Err.ErrMsg(ex);
        throw;
    }
}

return rate;
</code>```

Please could someone help me figure out what I'm missing here,

Cheers.

答:
You have to allow for the XML Namespace Horror:</p>

```<code>XNamespace ns = "http://somecurrencysite.com";

var rate = XDocument.Load(xRdr)
    .Descendants(ns + "to")
    .Descendants(ns + "rate")
    .Descendants(ns + "dayrate")
    .Select(dr => Convert.ToDecimal(dr.Value))
    .FirstOrDefault()
    ;
</code>```

Title: C# reading XML values using LINQ to XML

Body:
I have created a function that reads a third party XML document to get the conversion rate of Euros to GBP on any given date, however my linq query is returning a null value.

XML:

<therate xmlns="http://somecurrencysite.com">
    <terms>someValue</terms>
    <from>EUR</from>
    <amount>1.0</amount>
    <timestamp>2001-05-01T06:00:00Z</timestamp>
    <to>
        <rate>
            <currency>GBP</currency>
            <dayrate>0.619887217</dayrate>
        </rate>
    </to>
</therate>

C#:

var uri = "http://somecurrencysite.com?date=" + date.ToString("yyyy-MM-dd") + "&to=GBP";

decimal rate;

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential("userName", "passWord");

    try
    {
        var source = new MemoryStream(client.DownloadData(uri));
        var xRdr = new XmlTextReader(source);
        rate = XDocument.Load(xRdr)
            .Descendants("rate")
            .Select(e => (decimal)e.Element("dayrate"))
            .FirstOrDefault();
    }
    catch (Exception ex)
    {
        Err.ErrMsg(ex);
        throw;
    }
}

return rate;

Please could someone help me figure out what I'm missing here,

Cheers.

Body:
You have to allow for the XML Namespace Horror:

XNamespace ns = "http://somecurrencysite.com";

var rate = XDocument.Load(xRdr)
    .Descendants(ns + "to")
    .Descendants(ns + "rate")
    .Descendants(ns + "dayrate")
    .Select(dr => Convert.ToDecimal(dr.Value))
    .FirstOrDefault()
    ;


问:
Error: Property 'pipe' does not exist on type 'Observable<any>'
I'm copy pasting one of the examples from here:

https://material.angular.io/components/autocomplete/overview

HTML:

```<code><form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>
</code>```

TS:

```<code>import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';

/**
 * @title Filter autocomplete
 */
@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css']
})
export class AutocompleteFilterExample {

  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
  ];

  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(val => this.filter(val))
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().indexOf(val.toLowerCase()) === 0);
  }

}
</code>```

CSS:

```<code>.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}
</code>```

But I get this error:

Failed to compile: Property 'pipe' does not exist on type 'Observable'.

Any idea why?

答:
Based on your comments above it seems like you are just trying to subscribe to the value changes that occur on that FormControl. Try this:

this.filteredOptions = this.myControl.valueChanges
    .subscribe(_Changes => {
        console.log(_Changes);
    }
```

Not exactly sure what your intent is here, but this should at least start spitting the change values out at you.

Body:
I'm copy pasting one of the examples from here:

https://material.angular.io/components/autocomplete/overview

HTML:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

TS:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';

/**
 * @title Filter autocomplete
 */
@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css']
})
export class AutocompleteFilterExample {

  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
  ];

  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(val => this.filter(val))
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().indexOf(val.toLowerCase()) === 0);
  }

}

CSS:

.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}

But I get this error:

Failed to compile: Property 'pipe' does not exist on type 'Observable'.

Any idea why?

Body:
Based on your comments above it seems like you are just trying to subscribe to the value changes that occur on that FormControl. Try this:

this.filteredOptions = this.myControl.valueChanges
    .subscribe(_Changes => {
        console.log(_Changes);
    }

Not exactly sure what your intent is here, but this should at least start spitting the change values out at you.


问:
Django - importing dynamically
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

```<code>from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
</code>```

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

```<code>globals()[form]()
</code>```

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

```<code>theModule = __import__("app1.forms.App1ProfileForm")
</code>```

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

```<code> theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()
</code>```

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

答:
I figured it out.  Here's how to do it:

```<code>    theModule = __import__(module_name+".forms") # for some reason need the .forms part
    theClass = getattr(theModule,'forms')
    theForm = getattr(theClass,form_name)
</code>```

then to initialize:

```<code>theForm() or theForm(request.POST)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Django - importing dynamically

Body:
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

globals()[form]()

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

theModule = __import__("app1.forms.App1ProfileForm")

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

 theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

Body:
I figured it out.  Here's how to do it:

    theModule = __import__(module_name+".forms") # for some reason need the .forms part
    theClass = getattr(theModule,'forms')
    theForm = getattr(theClass,form_name)

then to initialize:

theForm() or theForm(request.POST)


问:
I want to plot line with 3 colors on MATLAB
I have 3 variables, x, y, z.
I want to plot line with 3 colors, red at h=0, green at h=1, blue at h=2.</p>

```<code>x = [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14];
y = [0 1 2 1 3 4 7 9 8 6 5 3 2 1 0];
h = [0 0 0 0 0 1 1 1 1 1 2 2 2 2 2];
color = [1 0 0 ; 0 1 0 ; 0 0 1];
</code>```

答:
Try this:</p>

```<code>x = [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14];
y = [0 1 2 1 3 4 7 9 8 6 5 3 2 1 0];
h = [0 0 0 0 0 1 1 1 1 1 2 2 2 2 2];
color = [1 0 0 ; 0 1 0 ; 0 0 1];

greens = h<1;
reds = h>=1;
blues = h>=2;

greenLine = y;
redLine = y;
blueLine = y;

greenLine(~greens) = NaN;

redLine(~reds) = NaN

blueLine(~blues) = NaN

plot(x,greenLine,'g',x,redLine,'r',x,blueLine,'b');
</code>```

Body:
I have 3 variables, x, y, z.
I want to plot line with 3 colors, red at h=0, green at h=1, blue at h=2.

x = [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14];
y = [0 1 2 1 3 4 7 9 8 6 5 3 2 1 0];
h = [0 0 0 0 0 1 1 1 1 1 2 2 2 2 2];
color = [1 0 0 ; 0 1 0 ; 0 0 1];

Body:
Try this:

x = [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14];
y = [0 1 2 1 3 4 7 9 8 6 5 3 2 1 0];
h = [0 0 0 0 0 1 1 1 1 1 2 2 2 2 2];
color = [1 0 0 ; 0 1 0 ; 0 0 1];

greens = h<1;
reds = h>=1;
blues = h>=2;

greenLine = y;
redLine = y;
blueLine = y;

greenLine(~greens) = NaN;

redLine(~reds) = NaN

blueLine(~blues) = NaN

plot(x,greenLine,'g',x,redLine,'r',x,blueLine,'b');


问:
Scheduled deletion of objects in IBM Cloud Object Storage using Node SDK
Is it possible to do scheduled deletion using the Node SDK ?

I can't find a function or parameter in the SDK that would let me do it.

If it's not possible with the SDK as-is, any pointers for a workaround (e.g. how to manually craft an HTTP request in Node that would serve the same purpose - can I use the Node SDK to prepare a template request or token?) would be really useful.

答:
Not within the SDK itself - COS doesn't support object expiry or lifecycle policies yet.

To schedule operations within your application logic, might want to check out the later (link) or node-cron (link) packages.


问:
ReactJS: How to fix numerical rows values length with toFixed(2)
I am printing the data fetched from an API into a table, and I am facing some difficulties to fix the rows numerical values to decimals. If the rows data within the API consists of numerical values, i.e. 10.0, 333, 8 or 100, etc. to render it in the end with decimal values -> 10.00, 333.00, 100.00.

The function that I am familiar with .toFixed(2), doesn't function in the same way in React, as I used to code it in javaScript. I think I am misleading the ES6 standard, but I am not sure.
Here is how it's look like, if I avoid using .toFixed(2).

Here is my code sample with rows.toFixed(2), but it's doesn't function well:

```<code>class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (
            <div id="container" className="container">
                <h1>Final Table with React JS</h1>
                <table className="datagrid">
                    <thead>
                        <tr> {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( <th>{column}</th> )
                            }
                            )
                        }
                        </tr>
                    </thead>
                    <tbody> {
                        this.state.rows.toFixed(2).map( row => (
                            <tr>{row.toFixed(2).map( cell => (
                                <td>{cell}</td>
                            ) )}
                            </tr>
                        ) )
                    }
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
</code>```

You are welcome to contribute directly to my Repo: Fetching API data into a table

Here is how looks like my example, when the .toFixed has been used:

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function with rows[].length.toFixed(2) either.

Any suggestions will be appreciated!

答:
Greetings to @Okazari for the suggestion. Here is the technically correct answer, but not logically:

```<code>this.state.rows.map( row => (
<tr>{row.map( cell => (
<td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
) )}
</tr>
) )
</code>```

It's not logical, because the age row values are printed as well as decimal, only the price values should be decimals. Further suggestions will be appreciated!

Body:
I am printing the data fetched from an API into a table, and I am facing some difficulties to fix the rows numerical values to decimals. If the rows data within the API consists of numerical values, i.e. 10.0, 333, 8 or 100, etc. to render it in the end with decimal values -> 10.00, 333.00, 100.00.

The function that I am familiar with .toFixed(2), doesn't function in the same way in React, as I used to code it in javaScript. I think I am misleading the ES6 standard, but I am not sure.
Here is how it's look like, if I avoid using .toFixed(2).

Here is my code sample with rows.toFixed(2), but it's doesn't function well:

class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (

Final Table with React JS

 {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( {column}	 )
                            }
                            )
                        }

 {
                        this.state.rows.toFixed(2).map( row => (

{row.toFixed(2).map( cell => (
                                {cell}
                            ) )}

                        ) )
                    }

        )
    }
}

ReactDOM.render(
<App />
, document.querySelector( 'body' ) );

You are welcome to contribute directly to my Repo: Fetching API data into a table

Here is how looks like my example, when the .toFixed has been used:

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function with rows[].length.toFixed(2) either.

Any suggestions will be appreciated!

Body:
Greetings to @Okazari for the suggestion. Here is the technically correct answer, but not logically:

this.state.rows.map( row => (
<tr>{row.map( cell => (
<td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
) )}
</tr>
) )

It's not logical, because the age row values are printed as well as decimal, only the price values should be decimals. Further suggestions will be appreciated!


问:
Why does logging backgroundTimeRemaining show a wrong/big number even though app was moved to background?
I'm logging my UIApplication.shared.backgroundTimeRemaining but the number is huge. It's almost 200 digits.

This is how I'm logging it.

```<code> os_log("Lat: %f | Long:  %f | RemainingTime: %f ", log: log, type: .default, location.coordinate.latitude, location.coordinate.longitude, UIApplication.shared.backgroundTimeRemaining)
</code>```

I thought there is something wrong with the format of my logging so I also tried placing a breakpoint and printing it but still the number that it logs is the same huge number. I also looked into this question which has a fair explanation, that is if your app is in foreground then the time would be that huge. But I still see this number even if there has been 5 minutes since I've moved the app to background.

A sample number I get for my remainingTime is:

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

Entire code:

```<code>import UIKit
import CoreLocation
import os.log
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate{

    lazy var locationManager : CLLocationManager = {
        var manager = CLLocationManager()
        manager.delegate = self

        manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        manager.distanceFilter = 1
        manager.pausesLocationUpdatesAutomatically = true
        manager.allowsBackgroundLocationUpdates = true
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()
        return manager
    }()

    var lastLocation : CLLocation?

    var mapView : MKMapView?

    let log = OSLog(subsystem: "XYZ.LocationAppSubSystem", category: "dumbo")

    override func viewDidLoad() {
        super.viewDidLoad()

        if locationManager.location != nil{

        }else {

            DispatchQueue.main.async {
                self.locationManager.startUpdatingLocation()
            }

        }
        os_log("view was Loaded", log: log, type: .error)

        mapView = MKMapView(frame: UIScreen.main.bounds)
        mapView?.showsUserLocation = true
        view.addSubview(mapView!)

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let location = locations.last else {
            return
        }
        lastLocation = location
        //        let date = Date().description(with: Locale.current)

        os_log("Lat: %{public}f | Long:  %{private}f | RemainingTime: %{public}f ", log: log, type: .default, location.coordinate.latitude, location.coordinate.longitude, UIApplication.shared.backgroundTimeRemaining)

    }

    func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
        os_log("locationManager was paused", log: log)

        let location = lastLocation

        os_log("Lat: %{public}f | Long:  %{private}f | RemainingTime: %{public}f ", log: log, type: .default, (location?.coordinate.latitude)!, (location?.coordinate.longitude)!, UIApplication.shared.backgroundTimeRemaining)

    }

    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        os_log("Region was exited", log: log)
    }

    func createRegion(location: CLLocation) {

        let radius = 3.0

        let region = CLCircularRegion(center: location.coordinate, radius: radius, identifier: "didPauseLocationUpdates")
        region.notifyOnExit = true
        region.notifyOnEntry = false

        locationManager.startMonitoring(for: region)
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        if region?.identifier == "didPauseLocationUpdates"{
            os_log("Main Region was Failed to be created", log: log)
        }else{
            os_log("Other regions were checked ", log: log)
        }
    }

}
</code>```

答:
It is because even though the app is in foreground or even closed, when a didEnterRegion, didExitRegion (apparently didUpdateLocations as well) event occurs, the app gets 10 seconds. In those 10 seconds, the backgroundTimeRemaining value will show the same as in foreground. However, if you register for a background task, the backgroundTimeRemaining will show the real background time remaining after those 10 seconds have passed.

In iOS, regions associated with your app are tracked at all times, including when the app isn’t running. If a region boundary is crossed while an app isn’t running, that app is relaunched into the background to handle the event. Similarly, if the app is suspended when the event occurs, it’s woken up and given a short amount of time (around 10 seconds) to handle the event. When necessary, an app can request more background execution time using the beginBackgroundTaskWithExpirationHandler: method of the UIApplication class.

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/RegionMonitoring/RegionMonitoring.html

Body:
I'm logging my UIApplication.shared.backgroundTimeRemaining but the number is huge. It's almost 200 digits.

This is how I'm logging it.

 os_log("Lat: %f | Long:  %f | RemainingTime: %f ", log: log, type: .default, location.coordinate.latitude, location.coordinate.longitude, UIApplication.shared.backgroundTimeRemaining)

I thought there is something wrong with the format of my logging so I also tried placing a breakpoint and printing it but still the number that it logs is the same huge number. I also looked into this question which has a fair explanation, that is if your app is in foreground then the time would be that huge. But I still see this number even if there has been 5 minutes since I've moved the app to background.

A sample number I get for my remainingTime is:

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

Entire code:

import UIKit
import CoreLocation
import os.log
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate{

    lazy var locationManager : CLLocationManager = {
        var manager = CLLocationManager()
        manager.delegate = self

        manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        manager.distanceFilter = 1
        manager.pausesLocationUpdatesAutomatically = true
        manager.allowsBackgroundLocationUpdates = true
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()
        return manager
    }()

    var lastLocation : CLLocation?

    var mapView : MKMapView?

    let log = OSLog(subsystem: "XYZ.LocationAppSubSystem", category: "dumbo")

    override func viewDidLoad() {
        super.viewDidLoad()

        if locationManager.location != nil{

        }else {

            DispatchQueue.main.async {
                self.locationManager.startUpdatingLocation()
            }

        }
        os_log("view was Loaded", log: log, type: .error)

        mapView = MKMapView(frame: UIScreen.main.bounds)
        mapView?.showsUserLocation = true
        view.addSubview(mapView!)

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let location = locations.last else {
            return
        }
        lastLocation = location
        //        let date = Date().description(with: Locale.current)

        os_log("Lat: %{public}f | Long:  %{private}f | RemainingTime: %{public}f ", log: log, type: .default, location.coordinate.latitude, location.coordinate.longitude, UIApplication.shared.backgroundTimeRemaining)

    }

    func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
        os_log("locationManager was paused", log: log)

        let location = lastLocation

        os_log("Lat: %{public}f | Long:  %{private}f | RemainingTime: %{public}f ", log: log, type: .default, (location?.coordinate.latitude)!, (location?.coordinate.longitude)!, UIApplication.shared.backgroundTimeRemaining)

    }

    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        os_log("Region was exited", log: log)
    }

    func createRegion(location: CLLocation) {

        let radius = 3.0

        let region = CLCircularRegion(center: location.coordinate, radius: radius, identifier: "didPauseLocationUpdates")
        region.notifyOnExit = true
        region.notifyOnEntry = false

        locationManager.startMonitoring(for: region)
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        if region?.identifier == "didPauseLocationUpdates"{
            os_log("Main Region was Failed to be created", log: log)
        }else{
            os_log("Other regions were checked ", log: log)
        }
    }

}


问:
SQL exclude on multiple criteria
This is my first post and I am new to SQL.

I have some data where the ID number begins with "0 thru 9", "C", "F", "E" and "H". My issue is I need to exclude all the ID numbers that begin with any of the letter values and also equal a particular word in another column, such as "Apple". However, I need to keep all the letter value ID's that contain for instance "Orange".

Data:

```<code>12345 Apple
56789 Apple
14569 Orange
14569 Apple
C2456 Apple
C2456 Orange
F1234 Apple
F1234 Orange
</code>```

Needed data:

```<code>12345 Apple
56789 Apple
14569 Orange
14569 Apple
C2456 Orange
F1234 Orange
</code>```

How would I do this in my where clause?

答:
How about...</p>

```<code>select *
from YourTable
where (left(lower(ID),1) like '%[a-z]%' and Column2 = 'Orange')
OR (left(ID,1) like '%[0-9]%')
</code>```

Title: SQL exclude on multiple criteria

Body:
This is my first post and I am new to SQL.

I have some data where the ID number begins with "0 thru 9", "C", "F", "E" and "H". My issue is I need to exclude all the ID numbers that begin with any of the letter values and also equal a particular word in another column, such as "Apple". However, I need to keep all the letter value ID's that contain for instance "Orange".

Data:

12345 Apple
56789 Apple
14569 Orange
14569 Apple
C2456 Apple
C2456 Orange
F1234 Apple
F1234 Orange

Needed data:

12345 Apple
56789 Apple
14569 Orange
14569 Apple
C2456 Orange
F1234 Orange

How would I do this in my where clause?

Body:
How about...

select *
from YourTable
where (left(lower(ID),1) like '%[a-z]%' and Column2 = 'Orange')
OR (left(ID,1) like '%[0-9]%')


问:
What to choose to store just one integer? Sqlite? or Text file?
I've build a small web-service in PHP. I want to control the number of calls to a specific API method.

I thought at first of using a text file, because it's just an integer. But after taking a good look at SQLite it seemed much more convenient.
So the code is just: get the "counter" from SQLite and increment it when that method is called, then store it back on SQLite db.

Is this a right way of doing it? Would it be simpler and more scalable to just use a file or... maybe something else?

Thanks in advance.

答: Put it in a real database both a textfile, and a SQLite DB will have locking issues where if the file(s) is currently open and a new request to open it happens the second request will error out.  Use a real DB like MySQL, MSSQL, or whatever is available.</p>

OwnerDisplayName: rogeriopvl

OwnerDisplayName: Unkwntech


问:
Calculate evenly distributed points along a curve
I'm using this equation to calculate a series of points along a quadratic curve:

```<code>// Returns a point on a quadratic bezier curve with Robert Penner's optimization of the standard equation
result.x = sx + t * (2 * (1 - t) * (cx - sx) + t * (ex - sx));
result.y = sy + t * (2 * (1 - t) * (cy - sy) + t * (ey - sy));
</code>```

Sadly the points are unevenly distributed, as you can see in the dashed-line rendering below. The points are denser in the middle of the curve, and are further spaced apart near the edges. How can I calculate a evenly distributed set of points along a quadratic bezier curve?

Please note that I'm using this for rendering a dashed line, so a slow solution in MATLAB or something will not do. I need a fast solution that will fit inside a renderer. This is not for research or a one-off calculation!

Edit: I'm not asking how to accomplish the above. The above is MY RENDERING! I already know how to estimate the length of a bezier, calculate the number of points, etc, etc. What I need is a better bezier point interpolation algorithm since the one I have calculates points unevenly distributed along the curve!

答:
This approach uses the THREE.js library, which is not in the OP's question, but may be useful if only to look at how they approach it:</p>

```<code>  var curve = new THREE.QuadraticBezierCurve(
    new THREE.Vector2( -10, 0 ),
    new THREE.Vector2( 20, 15 ),
    new THREE.Vector2( 10, 0 )
);

  var points = curve.getSpacedPoints(numPoints);
</code>```

Body:
I'm using this equation to calculate a series of points along a quadratic curve:

// Returns a point on a quadratic bezier curve with Robert Penner's optimization of the standard equation
result.x = sx + t * (2 * (1 - t) * (cx - sx) + t * (ex - sx));
result.y = sy + t * (2 * (1 - t) * (cy - sy) + t * (ey - sy));

Sadly the points are unevenly distributed, as you can see in the dashed-line rendering below. The points are denser in the middle of the curve, and are further spaced apart near the edges. How can I calculate a evenly distributed set of points along a quadratic bezier curve?

Please note that I'm using this for rendering a dashed line, so a slow solution in MATLAB or something will not do. I need a fast solution that will fit inside a renderer. This is not for research or a one-off calculation!

Edit: I'm not asking how to accomplish the above. The above is MY RENDERING! I already know how to estimate the length of a bezier, calculate the number of points, etc, etc. What I need is a better bezier point interpolation algorithm since the one I have calculates points unevenly distributed along the curve!

Body:
This approach uses the THREE.js library, which is not in the OP's question, but may be useful if only to look at how they approach it:

  var curve = new THREE.QuadraticBezierCurve(
    new THREE.Vector2( -10, 0 ),
    new THREE.Vector2( 20, 15 ),
    new THREE.Vector2( 10, 0 )
);

  var points = curve.getSpacedPoints(numPoints);


问:
PHP Fatal error: Unknown: Failed opening required | public duplicate in index.php link
My project use Zend 3 framework and php7.2. When I build web on Ubuntu 17.04, this web isn’t working.

```<code>> php -S 0.0.0.0:8080 -t public public/index.php
[Thu Dec  7 23:25:59 2017] PHP Warning:  Unknown: failed to open stream: No such file or directory in Unknown on line 0
[Thu Dec  7 23:25:59 2017] PHP Fatal error:  Unknown: Failed opening required '/home/isling/workspace/sp/shopping/public/public/index.php' (include_path='.:/usr/share/php') in Unknown on line 0
</code>```

'.../public/public/index.php' -> public is duplicated ???

答:
The -t argument specifies the document root, it is assumed that's where the indicated file is. So you just need this:

```<code>php -S 0.0.0.0:8080 -t public index.php
</code>```

I usually put this in my composer.json:

```<code>"scripts": {
    "serve": "php -S 0.0.0.0:8080 -t public/ index.php"
}
</code>```

Then I can just do composer serve to get a development server.

[EDIT 2018-04-27] This behavior has changed around version 7.2.3 or so. The filename parameter now appears to be relative to the current directory and not relative to the doc root directory specfied via -t, so you'd now use something like: php -S 0.0.0.0:8080 -t public/ public/index.php

Body:
My project use Zend 3 framework and php7.2. When I build web on Ubuntu 17.04, this web isn’t working.

> php -S 0.0.0.0:8080 -t public public/index.php
[Thu Dec  7 23:25:59 2017] PHP Warning:  Unknown: failed to open stream: No such file or directory in Unknown on line 0
[Thu Dec  7 23:25:59 2017] PHP Fatal error:  Unknown: Failed opening required '/home/isling/workspace/sp/shopping/public/public/index.php' (include_path='.:/usr/share/php') in Unknown on line 0

'.../public/public/index.php' -> public is duplicated ???

Body:
The -t argument specifies the document root, it is assumed that's where the indicated file is. So you just need this:

php -S 0.0.0.0:8080 -t public index.php

I usually put this in my composer.json:

"scripts": {
    "serve": "php -S 0.0.0.0:8080 -t public/ index.php"
}

Then I can just do composer serve to get a development server.

[EDIT 2018-04-27] This behavior has changed around version 7.2.3 or so. The filename parameter now appears to be relative to the current directory and not relative to the doc root directory specfied via -t, so you'd now use something like: php -S 0.0.0.0:8080 -t public/ public/index.php


问:
How to ignore exceptions on delete if database id not exists anymore?
I'd like to ignore any exceptions that occur during a delete action in spring CrudRepository.

```<code>@Tranactional
public void remove(Long id) {
    try {
        if (id != null) dao.delete(id); //CrudRepository
    } catch (Exception e) {
        //ignore any exceptions, it's not critical delete
    }
}
</code>```

Problem: when I run this, I'm still getting the following exception (eg if the id to be deleted does not exist anymore in database - means it may have been deleted concurrently). How could I ignore it?

```<code>org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526) ~[spring-orm-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:485) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]
</code>```

答:
Even if you catch the exception, the transaction manager will mark the transaction as rollbackonly, so when you commit at the end of the method you will have an TransactionSystemException exception.

The first reflex is to mark the method @Transactional(noRollbackFor=EmptyResultDataAccessException.class) but this does not solve the problem because if you take a look in SimpleJpaRepository class wil see that delete method is marked as transactional, so when the exception is thrown, this @Transactional marks your transaction as rollback only.

In my opinion, the solution is to call findOne method and then if entity exists call delete method (call delete method by entity and not by ID) :

```<code>@Tranactional
public void remove(Long id) {
    if (id != null) {
     YouEntity entity= dao.findOne(id);
     if (nonNull(entity)) {
        dao.delete(entity);
     }
    }
 }
</code>```

Body:
I'd like to ignore any exceptions that occur during a delete action in spring CrudRepository.

@Tranactional
public void remove(Long id) {
    try {
        if (id != null) dao.delete(id); //CrudRepository
    } catch (Exception e) {
        //ignore any exceptions, it's not critical delete
    }
}

Problem: when I run this, I'm still getting the following exception (eg if the id to be deleted does not exist anymore in database - means it may have been deleted concurrently). How could I ignore it?

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526) ~[spring-orm-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:485) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]

Body:
Even if you catch the exception, the transaction manager will mark the transaction as rollbackonly, so when you commit at the end of the method you will have an TransactionSystemException exception.

The first reflex is to mark the method @Transactional(noRollbackFor=EmptyResultDataAccessException.class) but this does not solve the problem because if you take a look in SimpleJpaRepository class wil see that delete method is marked as transactional, so when the exception is thrown, this @Transactional marks your transaction as rollback only.

In my opinion, the solution is to call findOne method and then if entity exists call delete method (call delete method by entity and not by ID) :

@Tranactional
public void remove(Long id) {
    if (id != null) {
     YouEntity entity= dao.findOne(id);
     if (nonNull(entity)) {
        dao.delete(entity);
     }
    }
 }


问:
Python Function Arguments: NameError argumant is not defined
I am new to Python. I want to call a function that detect null value in a excel table and passing "Fail" to a variable stat.

```<code>def checkBlank(tb):
    book=xlrd.open_workbook(reportFile)
    sheet = book.sheet_by_name(tb)
    s= "Pass"
    for i in range(sheet.nrows):
        row = sheet.row_values(i)
        for cell in row:
            if  cell =='':
                s="Fail"
    return s
print checkBlank('Sheet1')
</code>```

Above code will return "Fail"
but below code will give: NameError: name 'stat' is not defined

```<code>def checkBlank(tb,stat):
    book=xlrd.open_workbook(reportFile)
    sheet = book.sheet_by_name(tb)
    s= "Pass"
    for i in range(sheet.nrows):
        row = sheet.row_values(i)
        for cell in row:
            if  cell =='':
                s="Fail"
print checkBlank('Sheet1', stat)
print stat
</code>```

How can I assign "Fail" to stat if the function find the empty cell?

答:
It appears that you are attemping to pass a variable into a function to be used as the return value. This is not Pythonic and in general will not work. Instead, your function should be returning a value and you should be assigning that value to a new "variable."

```<code>def function(arg):
    if arg:
        return 'Pass'
    else:
        return 'Fail'

status = function(False)
print(status) # 'Fail'
</code>```

In Python, you don't want to try to write a function that calls by reference, because variables don't exist in Python in the same way that they do in C. Instead, what we have are names which are more akin to placeholders and can be used to retrieve objects. This article and many other Stack Overflow answers go into this in more depth.

Body:
I am new to Python. I want to call a function that detect null value in a excel table and passing "Fail" to a variable stat.

def checkBlank(tb):
    book=xlrd.open_workbook(reportFile)
    sheet = book.sheet_by_name(tb)
    s= "Pass"
    for i in range(sheet.nrows):
        row = sheet.row_values(i)
        for cell in row:
            if  cell =='':
                s="Fail"
    return s
print checkBlank('Sheet1')

Above code will return "Fail"
but below code will give: NameError: name 'stat' is not defined

def checkBlank(tb,stat):
    book=xlrd.open_workbook(reportFile)
    sheet = book.sheet_by_name(tb)
    s= "Pass"
    for i in range(sheet.nrows):
        row = sheet.row_values(i)
        for cell in row:
            if  cell =='':
                s="Fail"
print checkBlank('Sheet1', stat)
print stat

How can I assign "Fail" to stat if the function find the empty cell?

Body:
It appears that you are attemping to pass a variable into a function to be used as the return value. This is not Pythonic and in general will not work. Instead, your function should be returning a value and you should be assigning that value to a new "variable."

def function(arg):
    if arg:
        return 'Pass'
    else:
        return 'Fail'

status = function(False)
print(status) # 'Fail'

In Python, you don't want to try to write a function that calls by reference, because variables don't exist in Python in the same way that they do in C. Instead, what we have are names which are more akin to placeholders and can be used to retrieve objects. This article and many other Stack Overflow answers go into this in more depth.


问:
postgresql select max no if date is same
i have a table like:

```<code>  sr_no    or_no     date
  1        1         2017-01-01
  1        2         2017-02-02
  1        3         2017-02-02
  2        1         2017-01-02
  2        2         2017-01-10
</code>```

What i want is if date field for a sr_no is same then record with max or_no should be fetched. Output should be like:

```<code>sr_no     or_no    date
1         1        2017-01-01
1         3        2017-02-02
2         1        2017-01-02
2         2        2017-01-10
</code>```

答:
just distinct on to cut max(or_no) with order:</p>

```<code>with a as (select distinct on (d) * from t order by d,or_no desc)
select * from a order by sr_no,or_no;
 sr_no | or_no |     d
-------+-------+------------
     1 |     1 | 2017-01-01
     1 |     3 | 2017-02-02
     2 |     1 | 2017-01-02
     2 |     2 | 2017-01-10
(4 rows)
</code>```

Body:
i have a table like:

  sr_no    or_no     date
  1        1         2017-01-01
  1        2         2017-02-02
  1        3         2017-02-02
  2        1         2017-01-02
  2        2         2017-01-10

What i want is if date field for a sr_no is same then record with max or_no should be fetched. Output should be like:

sr_no     or_no    date
1         1        2017-01-01
1         3        2017-02-02
2         1        2017-01-02
2         2        2017-01-10

Body:
just distinct on to cut max(or_no) with order:

with a as (select distinct on (d) * from t order by d,or_no desc)
select * from a order by sr_no,or_no;
 sr_no | or_no |     d
-------+-------+------------
     1 |     1 | 2017-01-01
     1 |     3 | 2017-02-02
     2 |     1 | 2017-01-02
     2 |     2 | 2017-01-10
(4 rows)


问:
Enter password for git pull in script
I would like to create a script/tool which runs through my repositories and makes git pull. Script asks me a pass from GitLab/Bitbucket/whatever, I enter it and script synchronizes all repos hosted there. The problem I have faced: I have no idea how to enter password automatically.

For example, options like these do not work:

```<code>yes ${STORED_PASSWORD} | git pull
echo ${STORED_PASSWORD} | git pull
</code>```

From googling and reading Stack Overflow, I have understood:

Passing password as a part of url is not safe;

Credentials helper needs to enter password once for each remote repo and it will continue to store passwords after script will finish its work.

I use Windows's git shell, and there is no expect tool. Are there any options or workarounds?

答:
As others have pointed out, using SSH instead of HTTPS makes perfect sense in your use case, as it is less unwieldy and won't have you accidentally reveal your password to other users of your machine.

If you insist on using HTTPS and passing your password, this approach will work:

git pull https://myusername:${STORED_PASSWORD}@mygithost.com/my/repository

Title: Enter password for git pull in script

Body:
I would like to create a script/tool which runs through my repositories and makes git pull. Script asks me a pass from GitLab/Bitbucket/whatever, I enter it and script synchronizes all repos hosted there. The problem I have faced: I have no idea how to enter password automatically.

For example, options like these do not work:

yes ${STORED_PASSWORD} | git pull
echo ${STORED_PASSWORD} | git pull

From googling and reading Stack Overflow, I have understood:

Passing password as a part of url is not safe;

Credentials helper needs to enter password once for each remote repo and it will continue to store passwords after script will finish its work.

I use Windows's git shell, and there is no expect tool. Are there any options or workarounds?


问:
bluetooth socket connect
I am trying to get all data from a bluetooth device (Google Daydream Controller) to react to certain user inputs within an android application. I found a web application (https://github.com/mrdoob/daydream-controller.js) that pretty much reads the data as I would need it. Really I only need the button feedback for the app button.

But I am not able to connect! There is always an error when trying to connect. Other people have experience similar but in different setups.. I have not been able to find a solution

```<code>public class TryAgain extends AppCompatActivity {

    private static final String UUID_SERIAL_PORT_PROFILE = "00001101-0000-1000-8000-00805F9B34FB";

    private static final String TAG = "tag";

    BluetoothAdapter mBluetoothAdapter;
    BluetoothDevice mDevice;
    private BluetoothSocket mSocket = null;
    private BufferedReader mBufferedReader = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_try_again);

        findBT();

        try {
            openDeviceConnection(mDevice);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null)
        {
            System.out.println("No bluetooth adapter available");
        }

        if(!mBluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("Daydream controller"))
                {
                    mDevice = device;
                    break;
                }
            }
        }
        System.out.println("Bluetooth Device Found");
    }

    private void openDeviceConnection(BluetoothDevice device)
            throws IOException {
        InputStream aStream = null;
        InputStreamReader aReader = null;
        try {
            mSocket = device.createRfcommSocketToServiceRecord( getSerialPortUUID() );
            mSocket.connect();
            aStream = mSocket.getInputStream();
            aReader = new InputStreamReader( aStream );
            mBufferedReader = new BufferedReader( aReader );
        } catch ( IOException e ) {
            Log.e( TAG, "Could not connect to device", e );
            close( mBufferedReader );
            close( aReader );
            close( aStream );
            close( mSocket );
            throw e;
        }
    }

    private void close(Closeable aConnectedObject) {
        if ( aConnectedObject == null ) return;
        try {
            aConnectedObject.close();
        } catch ( IOException e ) {
        }
        aConnectedObject = null;
    }

    private UUID getSerialPortUUID() {
        return UUID.fromString( UUID_SERIAL_PORT_PROFILE );
    }
}
</code>```

The first step would be to read the data stream that the device sends and then extract the information to get the clicker information. Of course connecting to the device is essential and that's where I am struggling right now.

Error message:

```<code>java.io.IOException: read failed, socket might closed or timeout, read ret: -1
</code>```

答:
You need to call openDeviceConnection from a background thread like this:

```<code> Thread yourBGThread = new Thread( ){
    @Override
    public void run() {
        try {
            openDeviceConnection(mDevice);
        } catch (IOException  e) {
            e.printStackTrace();
        }
    }

};
yourBGThread.start();
</code>```

Put this code below findBT()

Title: bluetooth socket connect

Body:
I am trying to get all data from a bluetooth device (Google Daydream Controller) to react to certain user inputs within an android application. I found a web application (https://github.com/mrdoob/daydream-controller.js) that pretty much reads the data as I would need it. Really I only need the button feedback for the app button.

But I am not able to connect! There is always an error when trying to connect. Other people have experience similar but in different setups.. I have not been able to find a solution

public class TryAgain extends AppCompatActivity {

    private static final String UUID_SERIAL_PORT_PROFILE = "00001101-0000-1000-8000-00805F9B34FB";

    private static final String TAG = "tag";

    BluetoothAdapter mBluetoothAdapter;
    BluetoothDevice mDevice;
    private BluetoothSocket mSocket = null;
    private BufferedReader mBufferedReader = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_try_again);

        findBT();

        try {
            openDeviceConnection(mDevice);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null)
        {
            System.out.println("No bluetooth adapter available");
        }

        if(!mBluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("Daydream controller"))
                {
                    mDevice = device;
                    break;
                }
            }
        }
        System.out.println("Bluetooth Device Found");
    }

    private void openDeviceConnection(BluetoothDevice device)
            throws IOException {
        InputStream aStream = null;
        InputStreamReader aReader = null;
        try {
            mSocket = device.createRfcommSocketToServiceRecord( getSerialPortUUID() );
            mSocket.connect();
            aStream = mSocket.getInputStream();
            aReader = new InputStreamReader( aStream );
            mBufferedReader = new BufferedReader( aReader );
        } catch ( IOException e ) {
            Log.e( TAG, "Could not connect to device", e );
            close( mBufferedReader );
            close( aReader );
            close( aStream );
            close( mSocket );
            throw e;
        }
    }

    private void close(Closeable aConnectedObject) {
        if ( aConnectedObject == null ) return;
        try {
            aConnectedObject.close();
        } catch ( IOException e ) {
        }
        aConnectedObject = null;
    }

    private UUID getSerialPortUUID() {
        return UUID.fromString( UUID_SERIAL_PORT_PROFILE );
    }
}

The first step would be to read the data stream that the device sends and then extract the information to get the clicker information. Of course connecting to the device is essential and that's where I am struggling right now.

Error message:

java.io.IOException: read failed, socket might closed or timeout, read ret: -1

Body:
You need to call openDeviceConnection from a background thread like this:

 Thread yourBGThread = new Thread( ){
    @Override
    public void run() {
        try {
            openDeviceConnection(mDevice);
        } catch (IOException  e) {
            e.printStackTrace();
        }
    }

};
yourBGThread.start();

Put this code below findBT()


问:
realloc crashes when pointer has an offset
I have below a simplified C program that demonstrates the problem. When I try to call realloc using a pointer, it works fine, but if I try to add an offset to the pointer(i.e. to start from a later element in an array), it fails.

```<code># include <stdio.h>
# include <stdlib.h>

struct arbNum{
    unsigned char* bytes;
    long len;
};

void trim(struct arbNum* num){
    printf("%d,%d,%d,%d\n",num->bytes,num->bytes[0],num->bytes[1],num->len);
    unsigned char* nbytes = realloc(num->bytes,num->len);
    printf("Realloc successful.\n");
    num->bytes = nbytes;
}

int main(void){
    struct arbNum p = {calloc(2,1),2};
    trim(&p);
}
</code>```

As an example, this outputs:

```<code>9247152,0,0,2
Realloc successful.
</code>```

But, from the above code, changing realloc(num->bytes,num->len); to realloc(num->bytes+1,num->len-1); changes the output/behavior to this:

```<code>10361264,0,0,2
</code>```

And then crashes. It may be that I do not understand pointers at all, but my current understanding is that they are essentially addresses at which another value is stored. In this case, why would supplying the pointer+1 not point to the value stored in the address one higher than the pointer, or in other words, what would act as the 1st element of an array pointed to by that pointer. What I'm trying to do is copy an array pointed to by num.bytes starting at the 1st element to a new address in memory, but clearly, it's failing for some reason.

答:
No, you can only realloc() on the actual pointer previously returned by malloc() or family.

Otherwise, it's undefined behavior

Quoting C11, chapter §7.22.3.5

If ptr is a null pointer, the realloc function behaves like the malloc function for the
  specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory
  management function, or if the space has been deallocated by a call to the free or
  realloc function, the behavior is undefined. [....]

So, you're not allowed to use pointer aritmatic go generate a new address, pass that to realloc() and expect to re-allocate partially, that makes no sense.

Body:
I have below a simplified C program that demonstrates the problem. When I try to call realloc using a pointer, it works fine, but if I try to add an offset to the pointer(i.e. to start from a later element in an array), it fails.

# include <stdio.h>
# include <stdlib.h>

struct arbNum{
    unsigned char* bytes;
    long len;
};

void trim(struct arbNum* num){
    printf("%d,%d,%d,%d\n",num->bytes,num->bytes[0],num->bytes[1],num->len);
    unsigned char* nbytes = realloc(num->bytes,num->len);
    printf("Realloc successful.\n");
    num->bytes = nbytes;
}

int main(void){
    struct arbNum p = {calloc(2,1),2};
    trim(&p);
}

As an example, this outputs:

9247152,0,0,2
Realloc successful.

But, from the above code, changing realloc(num->bytes,num->len); to realloc(num->bytes+1,num->len-1); changes the output/behavior to this:

10361264,0,0,2

And then crashes. It may be that I do not understand pointers at all, but my current understanding is that they are essentially addresses at which another value is stored. In this case, why would supplying the pointer+1 not point to the value stored in the address one higher than the pointer, or in other words, what would act as the 1st element of an array pointed to by that pointer. What I'm trying to do is copy an array pointed to by num.bytes starting at the 1st element to a new address in memory, but clearly, it's failing for some reason.