text:
Q: Should I create multiple DTOs for the same entity? (Sorry my English is so bad).
The user entity in my spring boot project has the following basic fields: id, name, email, role, password. Admin can create new employee (including password field), update employee (except for password field), view employee information (except for password field). Employees can edit their information(except for role field). If I create only one DTO, will it be used for all of the above actions? Should I create a DTO for each of those actions?

A:
If I create only one DTO, will it be used for all of the above
actions?

Not unless you write code to make that happen.  You could have a single DTO for any number of actions if you wanted, but Spring does not impose that.  Creating a DTO will not make it be used for all of the actions.

Should I create a DTO for each of those actions?

Generally, no.

A: I would create one DTO per "display" case.
But it is not an obligation.

A: You can use Single DTO for all those operations and exclude that particular field which performing the operation. Like when Employee is editing their information then exclude the input of role property while saving/updating the record.


text:
Q: Preferring HTTPS IRIs on the semantic web TL/DR: Why shouldn't we prefer https: IRIs when defining new vocabularies for the semantic web?
The semantic web is built around the use of IRIs to identify various components, be they resources like a webpage or abstract concepts like ownership.  Every source I've consulted recommends the use of http: IRIs specifically, for example:

*

*Linked Data book (2011),

*UK government Open Data initiative (2010),

*W3C note on Cool URIs (2008), and

*W3C note on best practices for RDF vocabularies (2008).

This surprises me slightly.  The world seems to be moving away from HTTP to HTTPS, yet I know of no vocabulary that uses https: IRIs, and none of the documents quoted above even discuss the question.  I can find discussion on why ftp: or urn: are less good choices, but nothing about https:.
Even though IRIs on the semantic web are primarily identifiers not locators, there's a convention that the IRI is a good place to look for more information about entity, and various authorities recommend 303 redirects to documents like RDF or OWL schemas or other descriptive documents with further information.  If the IRI is an http: one, at least the initial request and redirect may be made over HTTP.  Even if the schema content is in no sense confidential, it still has the following problems:

*

*It is susceptible to a man-in-the-middle attack.  A malicious party could inject deliberately inconsistent schema information that may affect processing decisions made by applications, potentially causing a DoS or otherwise disrupting the user experience.

*ISPs may do a MITM themselves to inject adverts into content.  Really they oughtn't to do this for non-HTML content (well, they shouldn't do it at all, but that's another matter), but that relies on the ISP caring enough to get this right.  This can still happen over HTTPS, as Superfish demonstrated, but it's much harder.

*The request might be tracked by ISPs.  The fact that a user is using an application that consults a particular schema is itself valuable information about the customer that can be sold to advertisers which the US Senate recently voted to make legal.  People are increasingly privacy-conscious and want to minimise this.  Of course the ISP still knows which domain you've visited as the SNI field is not encrypted, but we can still seek to minimise the leak of data.
If the client supports it, HSTS can be used to ensure subsequent accesses go directly over HTTPS, but this does nothing about the initial request that is still made over HTTP.  Attempts at putting similar functionality in DNS have so far come to nothing, I suspect partly due to the slow adoption of DNSSEC.  I'm not aware of any other technical measures that might alleviate the problems discussed above.
These considerations all suggest to me that https: is a better choice than http: when defining a new vocabulary.  Obviously the situation is different if you have an existing vocabulary that already uses http:, but that's not the case I'm interested in here.
However I'm sure I'm not the first person to think of this, so I can only think everyone still uses and recommends http: for a reason.  If so, what are the disadvantages of https:?  And can anyone direct me to a good discussion of this?  So far as I can see the W3C have nothing on the subject which surprises me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript fetch POST Api REST request using formData() I have to send a request to my rest API to send an element which contains an image file.
Here is the code calling the request function :
await uploader(async () => {
        let mime = msg.fichier.split(";")[0].split(":")[1];
        let data = atob(msg.fichier.split(",")[1]);
        let bytes = new Uint8Array(data.length);
        for (let i in data) {
          bytes[i] = data.charCodeAt(i);
        }
        let file = new File(
          [bytes],
          msg.data.titre + "." + mime.split("/")[1],
          { type: mime }
        );
        return await upload_fichier(msg.type_fichier, file, { data: msg.data });

Below is the actual graphql request. My goal is to use api Rest request instead of graphql (i know graphql is better but for some reasons i NEED to use api Rest request) :
async function upload_fichier(type, fichier, variables) {
  const body = new FormData();
  variables[type] = null;
  body.append(
    "operations",
    JSON.stringify({
      query:
        `mutation createElement($data: ElementInput!, $${type}: Upload) {
          createElement(data: $data, ${type}: $${type}) {
            element {
              id
            }
          }
        }`.replace(/\s\s+/g, " "),
      variables: variables,
    })
  );
  body.append("map", JSON.stringify({ "1": [`variables.${type}`] }));
  body.append("1", fichier);

  const storage = await browser.storage.local.get("refresh_token");
  const headers = {};
  if (storage.refresh_token) {
    headers.authorization = "JWT " + storage.refresh_token;
  }

  const res = await fetch(url_graphql, {
    method: "POST",
    headers: headers,
    body: body,
  });
  return await res.json();

Below is the code i tried to write to do what i want :
async function upload_fichier(type, fichier, variables) {
  const body = new FormData();
  var index = [];
  variables[type] = null;
  // On récupère la valeur de chaque propriété de "variables"
  for (var variable in variables.data) {
    index.push(variables.data[variable]);
  }
  // Tableau des valeurs de clés
  const keys = Object.getOwnPropertyNames(variables.data);
  var json_str = {};
  for (let i = 0; i < keys.length; i++) {
    json_str[keys[i]] = index[i];
  }
  json_str["options"] = {isnew: true};
  // alert(JSON.stringify(json_str));
  body.append(
    "operations",
    JSON.stringify(json_str)
  );
  body.append("map", JSON.stringify({ "1": [`variables.${type}`] }));
  body.append("1", fichier);
  for (var value of body.values()) {
    alert(value);
  }
  const storage = await browser.storage.local.get("refresh_token");
  const headers = {};
  if (storage.refresh_token) {
    headers.authorization = "JWT " + storage.refresh_token;
  }
  const res = await fetch(url_api + "/elements/", {
    method: "POST",
    headers: headers,
    body: body,
  });

  return await res.json();

But if my element is well sent, it is empty. No title, no description, no image.
It seems that body value isn't right. So my Api request is just "url_api/elements/", which just create an empty basic element.


text:
Q: How to send a simple data by Ajax jQuery to views.py in Django? I want to send a simple data (a number) from home.html to a function in views.py by using Ajax jQuery. But it seems that the the function is not being called.
home.html:
I get the success response correctly. I see the tagID on the success notification. I want to see that in my views.py
...
function GetInfo(e){
                document.getElementById("test3").innerHTML = e.target.myCustomID;
                var tagID = e.target.myCustomID;

        $.ajax({
            url: 'Ajax1',
            type: "POST",
            data: {
                'tagID': tagID,
                'csrfmiddlewaretoken': '{{ csrf_token }}',
            },
            success: function (data) {
                alert ("Congrats! You sent some data: " + tagID);}
            ,
            error: function() {
                 alert ("Something went wrong");
             }
                })};

views.py:
I want to see that this function is called by the ajax. So if the command print ("AAAAAAAAAAAAA") works, I am happy!
...
@csrf_exempt
def Ajax1(request):
    print ("AAAAAAAAAAAAA")
    if request.is_ajax() and request.POST():
        print("BBBBBBBBBBBBB")
        TagID = request.POST.get('tagID', None)
    else:
        raise Http404

my_app/urls.py
urlpatterns = [
    url(r'', views.home_map, name="home"),
    url(r'^ajax/$', views.Ajax1, name="Ajax")
]

urls.py
urlpatterns = [
    path(r'', include('my_app.urls')),
    path('admin/', admin.site.urls),
    path(r'^ajax/$', Ajax1, name='Ajax')
]

would you please let me know what I am missing? thanks
UPDATE
Based on the kind suggestions, I made some changes. Still this is not working.
**views.py: **
def ajax1(request):
    TagIDD = request.POST['object_type']
    print("AAAAAAAAAAAAAAAAA", TagIDD)
    if request.is_ajax() and request.method == "POST":
        print("BBBBBBBBBBBBB")
        TagID = request.POST.get('tagID')
    else:
        raise Http404
    # TagID = request.POST('tagID')
    print ("Hello")
    print(TagID)

    response = {
        'TagID': TagID
    }
    return HttpResponse(response)

home.html
    function GetInfo(e){
                document.getElementById("test3").innerHTML =
                 e.target.myCustomID;
                const tagID = e.target.myCustomID;

                $.ajax({
                        type: "POST",
                        url: "{{ 'ajax-view/' }}",

                        data: {
                        'csrfmiddlewaretoken': '{{ csrf_token }}',
                        'tagID': tagID
                         },
                        success: function (data) {
                            alert ("Congrats! You sent some data: " +
                                       tagID);}
                        ,
                        error: function() {
                              alert ("Something went wrong");}
                        })
                };

 </script>

my_app\urls.py:
urlpatterns = [
    url(r'', views.home_map, name="home"),
    url('ajax-view/', views.ajax1, name='ajax-test-view')
]

urls.py:
urlpatterns = [
    path(r'', include('wrms01_map.urls')),
    path('admin/', admin.site.urls),
]

Still, it seems that the ajax is not calling the function "ajax1" in views.py. But I can see the success notification. Thanks in advance.

A: You are doing the ajax call wrong. You have to pass the EXACT URL of your endpoint inside the url:''
What you have done is passing a string 'Ajax1' which inside your urls.py is no where to be found. In you urls.py you have 'ajax' as the url pattern and Ajax1 is your view function name.
Also what I observe inside your urls.py you have same patterns for 2 different view methods (this is a bad practise).
For now do this inside your ajax
$.ajax({
            url: "{%url 'Ajax'%}",  //This is the jinja template tag that will automatically fill in the url pattern from your urls.py corresponding to the name of that url pattern
            type: "POST",
            data: {
                'tagID': tagID,
                'csrfmiddlewaretoken': '{{ csrf_token }}',
            },
            success: function (data) {
                alert ("Congrats! You sent some data: " + tagID);}
            ,
            error: function() {
                 alert ("Something went wrong");
             }
  })

A: So, it seems that I had a mistake in urls.py
urls.py:
urlpatterns = [
    path('', views.home_map, name='home.html'),
    path('admin/', admin.site.urls),
    path('ajax-view/', views.ajax1)
    # path('ajax/', ajax1, name='ajax1')
]

home.html:
                    $.ajax({
                        type: "POST",
                        url: '{{ "ajax-view/" }}',

                        data: {
                        'csrfmiddlewaretoken': '{{ csrf_token }}',
                        'tagID': tagID
                         },
                     success: function (data) {
                             alert ("Congrats! You sent some data: "
                                    +tagID)
                    ,
                        error: function() {
                              alert ("Something went wrong");}
                        })
                };


text:
Q: Invertible Elements of a field basic question about field theory
I know that if $p(x)$ is an irreducible polynomial in $\mathbb{Q}$, then $$\frac{\mathbb{Q}[x]}{\langle p(x) \rangle}$$ is a field.
But if $p(x)$ is irreducible over $\mathbb{Z}$, then we have $$\frac{\mathbb{Z}[x]}{\langle p(x) \rangle}$$
Now I am wondering that how these two fields differ?
I am extremely confused because the polynomial $x^3+9x+6$ is irreducible over $\mathbb{Z}[x]$ and $\mathbb{Q}[x]$ so we have the corresponding quotient fields.
If $\theta$ is a root of $p(x)$  then the element $1+\theta$
as an inverse $\frac{\theta^2-\theta+10}{4}$ in $$\frac{\mathbb{Q}[x]}{\langle p(x) \rangle}$$
but it doesn't lie in $$\frac{\mathbb{Z}[x]}{\langle p(x) \rangle}$$
But both of them are fields. So that element must have inverse in both of them
Probably I am missing something but extremely confused.

A: Irreducibles in UFDs generate prime ideals (and not necessarly maximal ideals),  so the quotient in general are integral domains. For your specefic example of $\mathbb{Z}[X]$, maximal ideals have the form $\langle n,p \rangle$, where $n$ is a prime integer and $p$ is a primitive  polynomial that is irreducible mod $p$ (u can easily see that the your ideal is not maximal). So when an ideal of $\mathbb{Z}[X]$ is maximal, the quotient the finite field $\mathbb{Z}/p\mathbb{Z}$.


text:
Q: PHP array merge values from one array into another Sorry I have read so many posts to make sense of this and have finally confused myself!
I have 2 arrays:
Array 1:
Array (

[0] => Array ( [ID] => SI012348 [Date] => 06/01/2016 [Month] => 1 [Tier1] => 2.188875 [Tier2] => [Tier3] => [Tier4] => [Delivery] => 0 )

[1] => Array ( [ID] => SI012351 [Date] => 06/01/2016 [Month] => 1 [Tier1] => 2.139 [Tier2] => 0 [Tier3] => 0 [Tier4] => 0 [Delivery] => 0 )

[2] => Array ( [ID] => SI012387 [Date] => 14/01/2016 [Month] => 1 [Tier1] => 0.201 [Tier2] => 0 [Tier3] => 0 [Tier4] => 0 [Delivery] => 0 )

)

Array 2: (Contains all invoices with Delivery charges)
Array (
[SI000005] => 25
[SI000010] => 15
[SI000054] => 20
[SI000069] => 0
[SI000074] => 20
[SI000076] => 16
)

I need to update Array 1 where SI00000x matches and push the value from Array 2 into the [Delivery] value in Array 1.
I am sure this is straightforward but everything I try either takes an age or crashes!
Please help!

A: You could use this (note the ampersand):
foreach ($arr1 as &$rec) {
    if (isset($arr2[$rec['ID']])) $rec['Delivery'] = $arr2[$rec['ID']];
}

A: Try this (use a reference)
foreach ($array1 as &$a1) {
  if(isset($array1[$a1['ID']])) $a1['Delivery'] = $array1[$a1['ID']];
}

A: foreach ($array1 as &$a1) {
    if (isset($array2[$a1['ID']])) {
        $a1['Delivery'] = $array2[$a1['ID']];
    }
}


text:
Q: Resizing UITextView's WIDTH based on content I am trying to resize a UITextView based on content. I would like to resize the height if it is multiline but when the text is really short I would like to resize the width to the content as well. Currently the height works but the width doesn't. I have tried
UITextView *view = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 130)];
view.text = @"This is a test";
CGSize size = [view.text sizeWithFont:view.font constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, size.width,size.height);
[self.view addSubview:view];

which is the closest I have come. But this doesn't resize the height and is chopping off the last word in the text ('test'). To resize the height I have tried both:
CGSize size = [view sizeThatFits:CGSizeMake(300, MAXFLOAT)];
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, size.width,size.height);

and
[view sizeToFit];
[view layoutIfNeeded];

which both work for height but don't seem to resize width (I don't know why they wouldn't work for width..)


text:
Q: What's the largest box I can make out of a sheet of wood? I'm planning on building a storage box out of sheet wood, and I'd like to know how to cut up my sheet into 6 pieces to form a box with the largest volume possible. Ideally the box should be flush on the outside, but I imagine the problem is a lot easier to solve when not taking that into account.
In the case of a non-flush box  I'd like a solution that takes the width and height of the sheet and gives me the width height and depth of the interior of the resulting box.

A: The answer will depend in part on the aspect ratio of the original sheet of wood, that is, the ratio of length to width.
For two sheets of the same aspect ratio but different sizes, that is,
two similar rectangles, you can take any plan for cutting one sheet and
assembling a box, and scale it up or down to build a similar box with the other sheet. An optimal plan for a box using one sheet translates in this
way into an optimal plan for the other sheet.
If one sheet is $x$ times as wide as the other, its area
will be $x^2$ as great as that of the other sheet, but the volume of the similar box will be $x^3$ as great as that of the other box.
For any sheet of a given aspect ratio,
the volume of the optimal box will be some constant times the
$3/2$ power of the area of the sheet, that is, $V_{\max} = k_{\max} A^{3/2}$,
where $k_{\max}$ is a best-case multiplier
determined by your sheet's aspect ratio.
The question then is how to find $k_{\max}$, given an aspect ratio.
The theoretical best case
The best value of $k_{\max}$ that any sheet of wood could possibly have
would occur in the cases where you are able to cut a thin sheet so as to
build a cube with no wood discarded.
Assuming an extremely thin sheet, a sheet of dimensions either
$w \times 6w$ or $2w \times 3w$ can be cut into six squares of
side $w$, which then enclose a cube of side $w$ and volume $V = w^3$.
The original area of the sheet was $A = 6w^2$, giving us the relation
$\sqrt[3]{\strut V} = \sqrt{\frac16 A}$, so
$$
V = \frac{\sqrt{6}}{36} A^{3/2}
$$
Since a cube is the rectangular box of maximum value for a given surface
area, and since these plans use all the area of the original sheet,
the factor $\sqrt 6/36 \approx 0.06804138174$ is the best possible such factor for any sheet of any aspect ratio.
But you can do this only with the two aspect ratios $1:6$ or $2:3$.
You cannot build a cube without waste from any other sheet of wood,
so for any other sheet you will be forced to use a different pattern
and if you are able to determine the value of $k_{\max}$, you will
find that $k_{\max} < \sqrt 6/36$.
A more practical example
Sheets of wood seem more likely to come with an aspect ratio of $1:2$
rather than $1:6$ or $2:3$; a typical sheet for construction in
seems to be $4$ feet wide by $8$ feet long.
(Even in countries using the metric system, it seems the size may be given in metric but will be $4\ \text{feet}\times8\ \text{feet}$ to within less than $\frac1{10}\%$ in each dimension;
for our purposes, however, only the aspect ratio matters.)
But rather than $4$ feet or $1.2$ meters, let's just say the
width of the sheet of wood is $w$ and its length is $2w$.
A likely plan for a sheet of wood of dimensions $w \times 2w$
(area $A = 2w^2$)
is to cut it lengthwise in half, and then cut three pieces of dimensions
$h \times \frac12 w$, $h \times \frac12 w$, and
$2(w - h) \times \frac12 w$ from each of the two halves.
If $h = \frac34 w$, for example, the resulting box would have dimensions
$\frac34 w \times \frac12 w \times \frac12 w$ and volume
$$
V = \frac{3}{16} w^3 = \frac{3\sqrt 2}{64} A^{3/2}
\approx 0.06629126073 A^{3/2}.
$$
This is almost as good as the theoretical best $k_{max}$ for sheets of
any aspect ratio.
But can we do better? What about other values of $h$?
If we let $h$ be less than $\frac34 w$, after cutting off two pieces
of width $h$ from each half of the sheet, the dimension $2(w-h)$
of the remaining pieces would be greater than $\frac12 w$.
In order to use the four $h \times \frac12 w$ pieces as "sides" of the box,
we would have to cut down the top and bottom to $\frac12 w \times \frac12 w$,
and the resulting box would have volume
$V = \frac14 w^2h < \frac{3}{16} w^3$,
less than when $h = \frac34 w$. So we can reject any $h < \frac34 w$.
If we let $h$ be greater than
$\frac34 w$, the width of the "top" of the box, $2(w-h)$, will be
less than $\frac12 w$. We can still build a box of height $h$ using
the $h \times \frac12 w$ pieces as "sides", but two of the "side"
pieces will be incompletely used.
The box will have dimensions $h \times 2(w-h) \times \frac12 w$.
As a function of $h$, the volume will be
$V = (w - h)wh = w^2 h - w h^2.$
Over the interval $\frac34 w \leq h \leq w $, this function reaches its
maximum value at $h = \frac34 w$.
That is, for any box made according to this pattern, the volume of the box
is maximized at $h = \frac34 w$, with volume
$V = \frac{3\sqrt 2}{64} A^{3/2}.$
Here's another attempt to build a better box from the $w \times 2w$ sheet:
An alternative plan for building a box from the $w \times 2w$ sheet
is to cut it widthwise into pieces of dimensions
$y \times w$, $(w - \frac12 y) \times w$, and $(w - \frac12 y) \times w$,
where $\frac12 w \leq y < w$.
We then cut two $y \times (w - y)$ pieces from the $y \times w$ piece,
discarding the part left over, and cut a $(w - \frac12 y) \times (w -y)$
piece from each of the remaining pieces, leaving a
$(w - \frac12 y) \times y$ piece. The resulting box has dimensions
$y \times (w - y) \times (w - \frac12 y)$, with volume
$V = \frac12 y^3 - \frac32 wy^2 + w^2 y$.
Over the interval $\frac12 w \leq y < w$, however, the volume of the
box is maximized at $y = \frac12 w$, where it turns out that
$$
V = \frac{3}{16} w^3 = \frac{3\sqrt 2}{64} A^{3/2},
$$
the same maximum volume (in fact the same pieces) as in the other plan.
For a $4\ \text{feet}\times8\ \text{feet}$ sheet of plywood this
results in a box of dimensions
$2\ \text{feet}\times2\ \text{feet}\times3\ \text{feet}$
with volume $12\ \text{feet}^3$ or about $0.339802$ cubic meters.
This does not prove there is no better way to build the box
(that is, I am not claiming that $k_{max}$ is $3\sqrt 2/64$ for
a sheet of aspect ratio $1:2$), but I have
not yet found a better way, and the volume achieved is fairly close to the
theoretical maximum volume of any box built from a sheet with the
given area.
The general case
A more general formula would take any aspect ratio, reduce it to a
single number (length divided by width), and then express
$k_{max}$ as a function of that number.
The tricky thing about such a function is that there is no single
"pattern" for cutting the wood that will be best for sheets of all shapes.
(Notice how very differently we cut a $1:6$ sheet and a $2:3$ sheet,
even though they end up with the exact same value of $k_{max}$.)
We have not even begun to look at all the possible aspect ratios
(such as $1:3$, $4:5$, $1:\frac12(1+\sqrt5)$, and so forth);
and even for the $1:2$ sheet we have not yet (at least not in any answer to
this question) gotten a proven value of $k_{max}$, only a
"pretty good" multiplier that is at least close to if not equal to
$k_{max}$ for the aspect ratio $1:2$.

A: This looks like a perfectly acceptable question. A man has a sheet of material (width W and height H). What is the maximmum volume of a closed box he can make?
We can ignore the thickness of the material initially.
A square box unfolded would be 4 units by 3 units in size - but this would produce a large amount of waste. To reduce the waste, simply divide the sheet into 6 equal sized pieces ( all W/2 x H/3 in size ).
Of the six pieces, four can remain this size but the top and bottom can only be the smallest dimension square. If we assume W < H, then the remaining 2 sides are W/2 square.
Our volume therefore would be, the base area times the height, or
(W/2) * (W/2) * H/3.
If this were a 2.4x1.2 sheet of ply, the maximum volume would be:
(.6*.6) * .8 = 0.48 cubic metres. The waste would be 2 strips of 0.6x0.2
While this produces some waste, we can't distribute that waste evenly to the other 4 sides ( altering one dimension on a box results in four sides changing size). In this woodworking exercise, some of the excess would be used to in the top and bottom because the external dimensions would be 0.6 x (0.6 + 2 x thickness).

A: A 4x8 sheet is 32 sq feet.  For a maximum theoretical volume you would picka cube with equal sides all L^2 in area.  6xL^2=32, or L=SQRT(32/6)=2.3 feet.  The resulting volume is L^3, or 12.32 cubic feet.  Of course, you can't cut the 4x8 sheet into 6 equal 2.3 ft squares, so split the sheet the long way, getting pieces as close to 2.3 ft (in this case 2 ft).  This will allow two ends at 2x2, then 4 equal pieces (tops and sides at 2x3).  The resulting volume is then 2x2x3, or 12 cubic feet, which is as close to the maximum you will get with a realistic cutting pattern.

A: For simplicity (and practical purposes) I will just ignore the saw kerf. Generally speaking, if you are making something out lower grade material it will come in 48 x 96" sheets. Cabinetry type sheets often come in 49 x 97 sheets to account for trim cuts of slightly damaged edges and some saw kerf from your other cuts. Either way, if you use lumber to case the edges as described below, the edges of the box don't necessarily have to meet perfectly.
Rip the 4 x 8 sheet of plywood in half to make two $2 \times 8$ pieces. From both of these strips cut two 3 ft pieces and you are left with one piece 2 x 2 from the end. This will give you 4 pieces @ 3 x 2 for the sides, top and bottom and 2 pieces at 2 x 2 for the ends.
If you want to put stuff in the box, I would probably then use some sort of lumber for all of the outside edge (if you want to put things on the box you can move the lumber to the inside of the box). The width of the lumber depends on what you want to put in the box really, 1 x 2 strapping or 1 x 4 lumber would probably work for the majority of stuff. If you have some scrap 2 x 4 lying around you can also make "feet" for the bottom.


text:
Q: passing a generator to field_values in django-autofixture Referring to django-autofixture documentation, I wrote the following code (edited for terseness):
    def random_state_generator(self, states=None):
        import random
        if not states:
            states = "waiting|email|post|einv".split('|')
        while 1:
            yield random.choice(states)

...
   rsg = self.random_state_generator()
   self.create_test_foo(10, values={'state': rsg})

...
    field_values = dict(field_values.items() + values.items())
    foo_fixture = AutoFixture(FooClass, overwrite_defaults=True,
                              generate_fk=generate_fk_values,
                              field_values=field_values)
    bunch_of_stuff = foo_fixture.create(foo_count)

Okay,
now when I have the DB all set up, and I filter myself a list of stuff,
and go
for foo in bunch_of_stuff: print (foo.state)

instead of getting the expected random state string, I get the following output:

generator object random_state_generator at 0x242c640>

which is not what I'd expect based on the documentation, specifically

field_values: A dictionary with field names of model as keys. Values may be static values that are assigned to the field, a Generator instance that generates a value on the fly or a callable which takes no arguments and returns the wanted value.

What am I doing wrong?

A: Okay, the field_values takes a class instance from autofixture.generators, so all I had to do was:
generate the list of states;
from autofixture.generators import ChoicesGenerator
states = "waiting|email|post|einv".split('|')
rsg = ChoicesGenerator(values=states)
self.create_test_foo(10, values={'state': rsg})

the misunderstanding rose from confusing autofixture's generators with generic python generators.

A: In case when u just want some raw data you can use :
def create_doctor():
    if Doctor.objects.all().count() == 0:
        import random
        avail_item = ['Hart', 'Kidney', 'Lungs', 'Ear', 'Bones']
        for i in range(10):
            fixture = AutoFixture(Doctor,
                                  field_values={'user_name': 'GauravTyagi',    'speciality': random.choice(avail_item)})
            fixture.create(1)
    else:
        print 'Doctors exist in table .........))))))))))))'


text:
Q: git push --receive-pack option and security: how to prevent from hacking? git push --receive-pack option gives the flexibility of running git-receive-pack not in $PATH.
But it is also a security vulnerability, as it can run any other commands as well.
How can I prevent a user from hacking the server by specifying --receive-pack?
Similarly, how can I avoid the vulnerability from git pull --upload-pack?

A: Through https or ssh, you can add an authorization layer like gitolite between your git request (push/pull) and git itself.
For ssh, it will use the ssh forced-command mechanism to intercept all commands, rejecting non-git ones.
Its gitolite-shell will parse the command, and extract the repo name, calling git-upload-pack|git-receive-pack without taking into account the Path to the git-receive-pack program.


text:
Q: Syntax error in MySQL prepare statement using C API I created a MySQL database, with some stored procedures. Using MySQL Workbench the SP forks fine, and now I need to launch them using a c program.
I created the program, which connect successfully to my db, and I'm able to launch procedures which not requires parameters.
To launch more complex procedure I need to use the prepare statement in c: in particular, I want to call the procedure esame_cancella(IN code CHAR(5)) which deletes a selected row of the table 'esame'.
    int status;
    MYSQL_RES *result;
    MYSQL_ROW row;
    MYSQL_FIELD *field;
    MYSQL_RES *rs_metadata;
    MYSQL_STMT *stmt;
    MYSQL_BIND ps_params[6];
    unsigned long length[6];
    char cod[64];

    printf("Codice: ");
    scanf ("%s",cod);
    length[0] = strlen(cod);

    stmt = mysql_stmt_init(conn);
    if (stmt == NULL) {
        printf("Could not initialize statement\n");
        exit(1);
    }

    status = mysql_stmt_prepare(stmt, "call esame_cancella(?) ", 64);
    test_stmt_error(stmt, status); //line which gives me the syntax error

    memset(ps_params, 0, sizeof(ps_params));

    ps_params[0].buffer_type = MYSQL_TYPE_VAR_STRING;
    ps_params[0].buffer = cod;
    ps_params[0].buffer_length = 64;
    ps_params[0].length = &length[0];
    ps_params[0].is_null = 0;

    // bind parameters
    status = mysql_stmt_bind_param(stmt, ps_params); //muore qui
    test_stmt_error(stmt, status);

    // Run the stored procedure
    status = mysql_stmt_execute(stmt);
    test_stmt_error(stmt, status);

    }

I use test_stmt_error to see MySQL log calling procedures.
    static void test_stmt_error(MYSQL_STMT * stmt, int status)
    {
        if (status) {
            fprintf(stderr, "Error: %s (errno: %d)\n",
            mysql_stmt_error(stmt), mysql_stmt_errno(stmt));
            exit(1);
        }
    }

when I compile, and launch my program, I have the following log:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 (errno: 1064)

Any help?

A: It looks like the string length being passed to mysql_stmt_prepare is wrong - try changing the 64 to 24.
Or better yet, try something like:
const char sql_sp[] = "call esame_cancella(?) ";
...
status = mysql_stmt_prepare(stmt, sql_sp, sizeof(sql_sp));


text:
Q: Attempt to uninstall java on Mac failed I am willing to run Spark shell on my machine, which is incompatible with my version (java 11), so need to remove and install compatible version (jdk8). Run following commands as specified by oracle:
sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -fr ~/Library/Application\ Support/Oracle/Java

Commands run, but still java 11 present:
$ java -version
java version "11" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11+28)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

Not sure what causes this.

A: This doesn't remove JRE or JDK. If you need to locate all your Java installations just launch the following command:
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (6):
    11.0.1, x86_64: "Java SE 11.0.1"    /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
    10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
    1.8.0_40, x86_64:   "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
    1.7.0_11, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_11.jdk/Contents/Home
    1.6.0_37-b06-434, x86_64:   "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0_37-b06-434.jdk/Contents/Home
    1.6.0_37-b06-434, i386: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0_37-b06-434.jdk/Contents/Home


text:
Q: Where did iOS Simulator go after Xcode 4.3.1? I sometimes need to run iOS Simulator independent of Xcode to test on Safari. I used to be able to just look for it in Spotlight and run it from there. But ever since I upgraded to Xcode 4.3.1, Spotlight can no longer find it. Any idea where it went?

A: Launch the simulator from Xcode and when it appears in your dock, right click it and select keep in dock.
The simulator can also be launched directly from Finder:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\
  Simulator.app

Edit: I don't know if this has been here the whole time, but I just discovered that you can also launch the simulator by right clicking Xcode's icon in your dock >> Open Developer Tool >> iOS Simulator.

A: It's embedded in the Xcode.app bundle that you download from the Mac Store or the Developer website. The best way I've found to launch it now is to just launch some app and then kill the app but don't quit the simulator.

A: Here's the technical path to where the sim app now sits
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app
(Even though the display name when you look in finder is now changed to "iOS Simulator.app")

A: It appears that you can also install the Simulator by going to Xcode's Preferences > Downloads. After that, I presume the Simulator will be its own app like before.


text:
Q: RaphaelJS + Chrome: click event not triggering the first time after a toFront() call If you use the toFront()-method on an element after you dragged it in an svg-image with multiple elements, the click-event of the element does not fire the first time.
If you click on it or drag the same element again, all subsequent click events are fired.
If you change to another element though, again the first click does not fire.
(the same goes for double click, as it relies on the click)
I've created a simple JSFiddle script to reproduce the problem:
http://jsfiddle.net/061h4hv7/1/
You need to open your browser-console to view the output of the script.
If you drag i.e. the red square for the first time the click event is not firing. All subsequent dragging fires the click though (as well as clicking on it).
You can see if the click is not working if the console only logs
mouseDown  mouseUp

but not
mouseDown  mouseUp  click

I'm using the Ubuntu-chrome version Version 36.0.1985.125 Ubuntu 14.04 (283153).
The problem does also occur in Chrome on Windows.
But apparently not in FireFox. I did not yet tested IE (maybe someone can test it?)
Here is the code I'm using to reproduce the problem. Note if you comment out the line
    this.toFront();
everything works just fine.
Unfortunately in my real code the toFront()-call is essential.
It is also important to note, that the drag-method is not the sole trigger for that problem, because I have implemented a different drag-method, where I'm not using a transform, but the problem still persists.
var click = function(){
    console.log('click');
};

var dragger = function () {
    console.log('mouseDown');
    this.previousDx = 0;
    this.previousDy = 0;
};

var move = function (dx, dy) {
    console.log('mouseMove');
    var txGroup = dx - this.previousDx;
    var tyGroup = dy - this.previousDy;

    this.translate(txGroup, tyGroup);

    this.previousDx = dx;
    this.previousDy = dy;
};

var up = function () {
    console.log('mouseUp');

    this.toFront();
};

var paper = Raphael(0, 0, "100%", "100%");

var red = paper.rect(10,10,30,30).attr({ 'fill' : 'red' }).drag(move, dragger, up).click(click);
var black = paper.rect(50,10,30,30).attr({ 'fill' : 'black' }).drag(move, dragger, up).click(click);
var blue = paper.rect(90,10,30,30).attr({ 'fill' : 'blue' }).drag(move, dragger, up).click(click);

Do you guys know anything to fix the problem? Otherwise I have to implement the click and double click manually by recording the mouseDown and mouseUp calls.


text:
Q: Affine subspace equivalent Let $X$ be an affine space over a vector space $V$ such that $\emptyset \neq Y \subset X$ and consider the following 2 statements:

(1) $Y \leq_a X$
(2) There exists a subspace $W \leq V$ such that $Y$ is an affine
  space over $W$

It is not hard to show that (2) follows from (1), but my teacher told me the converse is not true.
However, I argued in the following way to prove it and I can't see where my proof fails. If someone can point me out the flaw in my proof, and if possible can provide a counterexample to the converse, I would be very glad.
So, here is my attempt:

Let $y_1, \dots, y_n \in Y, a_1, \dots a_n \in F$ such that $\sum_i
 a_i = 1$.
By definition of affine space, we then have an action $\lambda: W
 \times Y \to Y: (w,y) \mapsto y + w$.
Now, let $y \in Y$ and consider the affine combination $\sum_i a_i y_i
 = y + \sum_i a_i(y_i - y)$, which can be written as $\lambda\left(\sum_i a_i(y_i -y),y\right) \in Y$, such that indeed $Y
 \leq_a X$

Interesting to know:
One can define an affine space $X$ over a vector space $V$ if there exists an action $\lambda: V \times X \to X$ such that:
1) $\lambda(0,x) = x$
2) $\lambda(v, \lambda(w,x)) = \lambda(v+w,x)$
3) $\forall x,y \in X: \exists ! v \in V: \lambda(v,x) = y$
The following are then certainly equivalent:

(1) $Y \leq_a X$
(2) There exists a subspace $W \leq V$ such that $Y$ is an affine
  space over $W$ under the left action $\lambda \vert_{W \times Y}^Y: W
 \times Y \to Y: (w,y) \mapsto \lambda(w,y)$

A: The mistake is in the claim:

$y+\sum_ia_i(y_i-y)=\lambda\left(\sum_i a_i(y_i -y),y\right)$

The first parameter of $\lambda$ should be an element of $W$, whereas the term $\sum_i a_i(y_i -y)$ is in $Y$.
For a counterexample, consider a curved line in the plane, viewed as an affine space through its parametrization. For example, the graph of a parabola
$$f:\mathbb{R}\to\mathbb{R}^2,\quad f(t)=(t,t^2)$$
equipped with the action
$$\lambda:\mathbb{R}\times f(\mathbb{R})\to f(\mathbb{R}),\quad \lambda(s,f(t)) = f(t+s)$$
satisfies your requirements 1)-3).


text:
Q: Shared model variable in incompatible format A shared model variable has a format incompatible with a sub component, any idea on how should I handle the conversion without messing my application model?
import {Calendar} from 'primeng/primeng';

@Component({
    selector: 'foo',
    directives: [Calendar],
    template: `
    ...
    <p-calendar [(ngModel)]="model"></p-calendar>
    ...
`})
class FooComponent {
    // input format: "1970-01-01T00:00:00Z"
    // model is shared within the app
    // should stay in this format
    // Calendar doesn't support this format
    @Input() model;

}

A: I resolved in a way that I do not really like, any better solution is welcome.
Thanks.
@Pipe({
    name: 'iso2date'
})
export class Iso2Date {
    transform(value: any, args: Array<any>): string {
        return moment(value).format("YYYY-MM-DD");
    }
}

@Component({
    selector: 'foo',
    directives: [Calendar],
    pipes: [Iso2Date],
    template: `
    ...
    <p-calendar dateFormat="yy-mm-dd"
        [ngModel]="model | iso2date"
        (ngModelChange)="model=date2iso($event)"></p-calendar>
    ...
`})
class FooComponent {
    @Input() model;

    date2iso(value) {
        var m = moment(value, "YYYY-MM-DD");
        return m.toISOString();
    }

}

p.s.: pipes do not work in actions otherwise the following would have been cleaner
@Pipe({
    name: 'date2iso'
})
export class Date2Iso {
    transform(value: any, args: Array<any>): string {
        return moment(value,"YYYY-MM-DD").toISOString();
    }
}

...
(ngModelChange)="model=(event | date2iso)"></p-calendar>
...

however I get the following error:
Parser Error: Cannot have a pipe in an action expression at column 20 in [model=($event | date2iso)] in FooComponent@19:28 ("="yy-mm-dd"
                            [ngModel]="model | iso2date"
                            [ERROR ->](ngModelChange)="model=($event | date2iso)"


text:
Q: DOMPDF Calculation PHP Page
I have not understand what I have to do on this to show the net value.
It doesn't show me any value. What should I do please help me.PDF File
Here is the table code. I can't see the shipping charge net value in table footer.

Payment

                    '.$TRACK.'
                    '.$zones.'
                    '.$FECHA.'
                    '.$Mer.'
                    '.$DESTINA.'
                    '.$NUMBERPHONE.'
                    '.$ESTADO.'
                    '.$deliveryboy.'

                ';

                $sql=mysql_query("SELECT * FROM courier_online WHERE payment = 'OK' AND email='$qname' AND date   BETWEEN '$desde' AND '$hasta'");
                while($express=mysql_fetch_array($sql)){
                $initial = 0; // Empezar a contar desde 0
                $initial = $initial + $row['shipping_subtotal'];
                $codigoHTML.='

                        '.$express['cons_no'].'
                        '.$express['shipping_subtotal'].'
                        '.$express['date'].'
                        '.$express['user'].'
                        '.$express['rev_name'].'
                        '.$express['r_phone'].'
                        '.$express['status'].'

                                                            <?php echo $initial; ?>

                    ';

                }
        $codigoHTML.='

A: I see two issues with your code:
1) You're echoing the value of $initial rather than concatenating it to the value of your $codigoHTML variable. Because of this it is not included in the HTML document (as contained in the variable).
2) Your generated HTML is not valid. You should move the closing TBODY tag and the entire TFOOT block outside the closing brace for the while loop.


text:
Q: Разделить строку и кавычки У меня есть строка, например " \" HELLO FRIEND \" "
Мне нужно разделить её методом split(), в данном случае, на 4 части.
В итоге должен получиться массив {", HELLO, FRIEND, "}

A: Тут можно обойтись без RegExp'ов. Передай пробел аргументом в функцию split, а потом отфильтруй результат, что бы в массиве не было пустых строк:
" \" HELLO FRIEND \" ".split(' ').filter(str=>str!='');


text:
Q: How to handle intentionally missing survey responses for factor analysis I've been asked to do factor analysis with some data from a skills assessment questionnaire. The structure of the questionnaire is such that:

*

*36 questions total, divided equally between 3 latent skills (12 questions per skill).

*Each respondent is asked a random subset of 6 questions per skill, for a total of 18.

*So each respondent is missing 50% (18/36) of the data, and the missingness is MCAR.

I know that normally with MCAR it is considered kosher to do complete case analysis, but that isn't an option here because there are no complete cases (everyone is missing 50% of the responses). So my question is: what is an appropriate missing data strategy to use for this dataset in a factor analysis context?


text:
Q: How to orderBy before sum I have the following tables:
competitions (id, ...)
questions (id, ...)
teams (id, ...)
team_user (id, user_id, team_id, ...)
answer_user (user_id, competition_id, question_id, points, ...)

I am trying to build a query to list all teams who participated in the competition id = 20, given that we sort the list based on accumulation of the teams' users' points.  However, sometimes 2 teams receive the same total points, so we need to show the team who was able to reach that total of points first in the list before others (based on the answers created_at column)
I am able to get this list using the following query, but not able to sort based on answer_user created_at column:
$ranks = Team::withCount(['answers' => function ($q) use ($competition_id) {
        $q->where('competition_id', $competition_id)
            ->select(DB::raw('sum(points)'));
    }])
    ->where('competition_id', $competition_id)
    ->orderBy('answers_count', 'desc')
    ->get();

Edit 1
I can achieve the sort required when I replace the
->select(DB::raw('sum(points)')

with
->select(DB::raw('max(answer_user.created_at)')

However, I want actually both aggregations to work.  Basically, finding the total points each team scored, then sort them based on the time, first to score is the one show first.

A: Please try to use sortBy() or sortByDesc() function after get()
https://laravel.com/docs/5.8/collections#method-sortbydesc
    $ranks = Team::withCount(['answers'=>function($q) use($competition_id){
                $q->where('competition_id',$competition_id)->select(DB::raw('sum(points)'));
}])->where('competition_id',$competition_id)->get()->sortByDesc('answer_user');


text:
Q: Sympy Solve returning type error? I have written a program to solve a transcendental equation using Sympy Solvers, but I keep getting a TypeError. The code I have written is the following:
from sympy.solvers import solve
from sympy import Symbol
import sympy as sp
import numpy as np

x = Symbol('x',positive=True)

def converts(d):
    M = 1.0
    res = solve(-2*M*sp.sqrt(1+2*M/x)-d,x)[0]
    return res
print converts(0.2)

which returns the following error:
raise TypeError('invalid input: %s' % p)
TypeError: invalid input: -2.0*sqrt(1 + 2/x)

I've solved transcendental equations this way before, but this is the first time I'm facing this error.
From what I gather, it looks like Sympy is seeing my input as a string instead of a rational number, but I'm not sure if or why it is so. Can someone please tell me why I'm getting this error and/or how to fix it?
Edit: I've rewritten my code to make it clearer but the result is still the same
This is the equation I'm trying to solve

A: Let's first recreate the actual equation.
from sympy import *
init_printing()
M, x, d = symbols("M, x, d")
eq = Eq(-2*M * sqrt(1 + 2*M/x) - d, 0)
eq

As in your code, we can substitute values: M=1, d=0.2
to_solve = eq.subs({M:1, d:0.2})
to_solve

Now, we may attempt to solve it directly
solve(to_solve, x)

Unfortunately, solve fails to find the solution in this case. If we take a closer look at the equation, the square root part should return a negative number for this equation to be valid.
-2 * (-1/10) - 0.2 = 0

As square root of a number can not be negative, correct me if I'm wrong, sympy is unable to find a value for x such that sqrt(1+2/x) == -1/10
This problem is due to our choice of values for d and M. Solution exists if M and d are of opposite signs.
to_solve = eq.subs({M:-1, d:0.2})
to_solve

solve(to_solve, x)

[2.02020202020202]

Run this code on sympy live and experiment with other values.


text:
Q: QGIS graphical modeller naming layer output based on attribute I have built a model in QGIS that buffers some points and then clips them to a paddock boundary. I would like to use the Load Layer Into Project tool or the Rename Layer tool to name the layers output based on the paddocks name but I can't figure out how to do it.
I have been trying to use the precalucated value option for the output but maybe I am not getting the syntax right?
I have tried all sort of variations of attribute( $currentfeature,"Name")   or attribute( @Paddock, Name) I can think of.
In the expression dialog I get:

No feature was found on this layer to evaluate the expression.

The message from the log when running the model is:

Invalid (empty) layer name
Error encountered while running Load layer into project
Execution failed after 0.09 seconds

An model of what I am trying to do is below:
<!DOCTYPE model>
<Option type="Map">
  <Option name="children" type="Map">
    <Option name="native:buffer_1" type="Map">
      <Option value="true" name="active" type="bool"/>
      <Option name="alg_config"/>
      <Option value="native:buffer" name="alg_id" type="QString"/>
      <Option value="" name="color" type="QString"/>
      <Option name="comment" type="Map">
        <Option value="" name="color" type="QString"/>
        <Option value="" name="component_description" type="QString"/>
        <Option value="60" name="component_height" type="double"/>
        <Option value="320" name="component_pos_x" type="double"/>
        <Option value="115" name="component_pos_y" type="double"/>
        <Option value="100" name="component_width" type="double"/>
        <Option value="true" name="outputs_collapsed" type="bool"/>
        <Option value="true" name="parameters_collapsed" type="bool"/>
      </Option>
      <Option value="Buffer" name="component_description" type="QString"/>
      <Option value="30" name="component_height" type="double"/>
      <Option value="544" name="component_pos_x" type="double"/>
      <Option value="337" name="component_pos_y" type="double"/>
      <Option value="200" name="component_width" type="double"/>
      <Option name="dependencies"/>
      <Option value="native:buffer_1" name="id" type="QString"/>
      <Option name="outputs"/>
      <Option value="true" name="outputs_collapsed" type="bool"/>
      <Option value="true" name="parameters_collapsed" type="bool"/>
      <Option name="params" type="Map">
        <Option name="DISSOLVE" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="true" name="static_value" type="bool"/>
          </Option>
        </Option>
        <Option name="DISTANCE" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="1000" name="static_value" type="double"/>
          </Option>
        </Option>
        <Option name="END_CAP_STYLE" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="0" name="static_value" type="int"/>
          </Option>
        </Option>
        <Option name="INPUT" type="List">
          <Option type="Map">
            <Option value="PointsLayer" name="parameter_name" type="QString"/>
            <Option value="0" name="source" type="int"/>
          </Option>
        </Option>
        <Option name="JOIN_STYLE" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="0" name="static_value" type="int"/>
          </Option>
        </Option>
        <Option name="MITER_LIMIT" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="2" name="static_value" type="double"/>
          </Option>
        </Option>
        <Option name="SEGMENTS" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="10" name="static_value" type="int"/>
          </Option>
        </Option>
      </Option>
    </Option>
    <Option name="native:intersection_1" type="Map">
      <Option value="true" name="active" type="bool"/>
      <Option name="alg_config"/>
      <Option value="native:intersection" name="alg_id" type="QString"/>
      <Option value="" name="color" type="QString"/>
      <Option name="comment" type="Map">
        <Option value="" name="color" type="QString"/>
        <Option value="" name="component_description" type="QString"/>
        <Option value="60" name="component_height" type="double"/>
        <Option value="1039" name="component_pos_x" type="double"/>
        <Option value="455" name="component_pos_y" type="double"/>
        <Option value="100" name="component_width" type="double"/>
        <Option value="true" name="outputs_collapsed" type="bool"/>
        <Option value="true" name="parameters_collapsed" type="bool"/>
      </Option>
      <Option value="Intersection" name="component_description" type="QString"/>
      <Option value="30" name="component_height" type="double"/>
      <Option value="802" name="component_pos_x" type="double"/>
      <Option value="207" name="component_pos_y" type="double"/>
      <Option value="200" name="component_width" type="double"/>
      <Option name="dependencies"/>
      <Option value="native:intersection_1" name="id" type="QString"/>
      <Option name="outputs"/>
      <Option value="true" name="outputs_collapsed" type="bool"/>
      <Option value="true" name="parameters_collapsed" type="bool"/>
      <Option name="params" type="Map">
        <Option name="INPUT" type="List">
          <Option type="Map">
            <Option value="native:buffer_1" name="child_id" type="QString"/>
            <Option value="OUTPUT" name="output_name" type="QString"/>
            <Option value="1" name="source" type="int"/>
          </Option>
        </Option>
        <Option name="INPUT_FIELDS" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option name="static_value" type="StringList">
              <Option value="" type="QString"/>
            </Option>
          </Option>
        </Option>
        <Option name="OVERLAY" type="List">
          <Option type="Map">
            <Option value="VactorLayer" name="parameter_name" type="QString"/>
            <Option value="0" name="source" type="int"/>
          </Option>
        </Option>
        <Option name="OVERLAY_FIELDS" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option name="static_value" type="StringList">
              <Option value="" type="QString"/>
            </Option>
          </Option>
        </Option>
        <Option name="OVERLAY_FIELDS_PREFIX" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="" name="static_value" type="QString"/>
          </Option>
        </Option>
      </Option>
    </Option>
    <Option name="native:loadlayer_1" type="Map">
      <Option value="true" name="active" type="bool"/>
      <Option name="alg_config"/>
      <Option value="native:loadlayer" name="alg_id" type="QString"/>
      <Option value="" name="color" type="QString"/>
      <Option name="comment" type="Map">
        <Option value="" name="color" type="QString"/>
        <Option value="" name="component_description" type="QString"/>
        <Option value="60" name="component_height" type="double"/>
        <Option value="1442" name="component_pos_x" type="double"/>
        <Option value="554" name="component_pos_y" type="double"/>
        <Option value="100" name="component_width" type="double"/>
        <Option value="true" name="outputs_collapsed" type="bool"/>
        <Option value="true" name="parameters_collapsed" type="bool"/>
      </Option>
      <Option value="Doesn't Work" name="component_description" type="QString"/>
      <Option value="30" name="component_height" type="double"/>
      <Option value="957" name="component_pos_x" type="double"/>
      <Option value="315" name="component_pos_y" type="double"/>
      <Option value="200" name="component_width" type="double"/>
      <Option name="dependencies"/>
      <Option value="native:loadlayer_1" name="id" type="QString"/>
      <Option name="outputs"/>
      <Option value="true" name="outputs_collapsed" type="bool"/>
      <Option value="true" name="parameters_collapsed" type="bool"/>
      <Option name="params" type="Map">
        <Option name="INPUT" type="List">
          <Option type="Map">
            <Option value="native:intersection_1" name="child_id" type="QString"/>
            <Option value="OUTPUT" name="output_name" type="QString"/>
            <Option value="1" name="source" type="int"/>
          </Option>
        </Option>
        <Option name="NAME" type="List">
          <Option type="Map">
            <Option value=" attribute($currentfeature , 'Name')" name="expression" type="QString"/>
            <Option value="3" name="source" type="int"/>
          </Option>
        </Option>
      </Option>
    </Option>
    <Option name="native:loadlayer_2" type="Map">
      <Option value="true" name="active" type="bool"/>
      <Option name="alg_config"/>
      <Option value="native:loadlayer" name="alg_id" type="QString"/>
      <Option value="" name="color" type="QString"/>
      <Option name="comment" type="Map">
        <Option value="" name="color" type="QString"/>
        <Option value="" name="component_description" type="QString"/>
        <Option value="60" name="component_height" type="double"/>
        <Option value="1451" name="component_pos_x" type="double"/>
        <Option value="576" name="component_pos_y" type="double"/>
        <Option value="100" name="component_width" type="double"/>
        <Option value="true" name="outputs_collapsed" type="bool"/>
        <Option value="true" name="parameters_collapsed" type="bool"/>
      </Option>
      <Option value="Works" name="component_description" type="QString"/>
      <Option value="30" name="component_height" type="double"/>
      <Option value="916" name="component_pos_x" type="double"/>
      <Option value="413" name="component_pos_y" type="double"/>
      <Option value="200" name="component_width" type="double"/>
      <Option name="dependencies"/>
      <Option value="native:loadlayer_2" name="id" type="QString"/>
      <Option name="outputs"/>
      <Option value="true" name="outputs_collapsed" type="bool"/>
      <Option value="true" name="parameters_collapsed" type="bool"/>
      <Option name="params" type="Map">
        <Option name="INPUT" type="List">
          <Option type="Map">
            <Option value="native:intersection_1" name="child_id" type="QString"/>
            <Option value="OUTPUT" name="output_name" type="QString"/>
            <Option value="1" name="source" type="int"/>
          </Option>
        </Option>
        <Option name="NAME" type="List">
          <Option type="Map">
            <Option value="2" name="source" type="int"/>
            <Option value="Name" name="static_value" type="QString"/>
          </Option>
        </Option>
      </Option>
    </Option>
  </Option>
  <Option name="designerParameterValues" type="Map">
    <Option value="Point_e7a64aeb_f9a0_4250_a604_9f34e49de051" name="PointsLayer" type="QString"/>
    <Option value="true" name="VERBOSE_LOG" type="bool"/>
    <Option value="Polygon_81f8e358_ced8_4547_bf70_a02d1dbb28b8" name="VactorLayer" type="QString"/>
  </Option>
  <Option name="groupBoxes"/>
  <Option name="help"/>
  <Option name="modelVariables"/>
  <Option value="Test" name="model_group" type="QString"/>
  <Option value="Name Layer" name="model_name" type="QString"/>
  <Option name="parameterDefinitions" type="Map">
    <Option name="PointsLayer" type="Map">
      <Option name="data_types" type="List">
        <Option value="0" type="int"/>
      </Option>
      <Option name="default" type="invalid"/>
      <Option name="defaultGui" type="invalid"/>
      <Option value="Points Layer" name="description" type="QString"/>
      <Option value="0" name="flags" type="int"/>
      <Option value="" name="help" type="QString"/>
      <Option name="metadata"/>
      <Option value="PointsLayer" name="name" type="QString"/>
      <Option value="vector" name="parameter_type" type="QString"/>
    </Option>
    <Option name="VactorLayer" type="Map">
      <Option name="data_types" type="List">
        <Option value="2" type="int"/>
      </Option>
      <Option name="default" type="invalid"/>
      <Option name="defaultGui" type="invalid"/>
      <Option value="Polygon Layer" name="description" type="QString"/>
      <Option value="0" name="flags" type="int"/>
      <Option value="" name="help" type="QString"/>
      <Option name="metadata"/>
      <Option value="VactorLayer" name="name" type="QString"/>
      <Option value="vector" name="parameter_type" type="QString"/>
    </Option>
  </Option>
  <Option name="parameterOrder"/>
  <Option name="parameters" type="Map">
    <Option name="PointsLayer" type="Map">
      <Option value="" name="color" type="QString"/>
      <Option name="comment" type="Map">
        <Option value="" name="color" type="QString"/>
        <Option value="" name="component_description" type="QString"/>
        <Option value="60" name="component_height" type="double"/>
        <Option value="433" name="component_pos_x" type="double"/>
        <Option value="407" name="component_pos_y" type="double"/>
        <Option value="100" name="component_width" type="double"/>
        <Option value="true" name="outputs_collapsed" type="bool"/>
        <Option value="true" name="parameters_collapsed" type="bool"/>
      </Option>
      <Option value="PointsLayer" name="component_description" type="QString"/>
      <Option value="30" name="component_height" type="double"/>
      <Option value="212" name="component_pos_x" type="double"/>
      <Option value="333" name="component_pos_y" type="double"/>
      <Option value="200" name="component_width" type="double"/>
      <Option value="PointsLayer" name="name" type="QString"/>
      <Option value="true" name="outputs_collapsed" type="bool"/>
      <Option value="true" name="parameters_collapsed" type="bool"/>
    </Option>
    <Option name="VactorLayer" type="Map">
      <Option value="" name="color" type="QString"/>
      <Option name="comment" type="Map">
        <Option value="" name="color" type="QString"/>
        <Option value="" name="component_description" type="QString"/>
        <Option value="60" name="component_height" type="double"/>
        <Option value="600" name="component_pos_x" type="double"/>
        <Option value="15" name="component_pos_y" type="double"/>
        <Option value="100" name="component_width" type="double"/>
        <Option value="true" name="outputs_collapsed" type="bool"/>
        <Option value="true" name="parameters_collapsed" type="bool"/>
      </Option>
      <Option value="VactorLayer" name="component_description" type="QString"/>
      <Option value="30" name="component_height" type="double"/>
      <Option value="250" name="component_pos_x" type="double"/>
      <Option value="160" name="component_pos_y" type="double"/>
      <Option value="200" name="component_width" type="double"/>
      <Option value="VactorLayer" name="name" type="QString"/>
      <Option value="true" name="outputs_collapsed" type="bool"/>
      <Option value="true" name="parameters_collapsed" type="bool"/>
    </Option>
  </Option>
</Option>


text:
Q: Bluetooth internal card not recognized by Debian 11 I have an Asus X550Z laptop.I can boot into Ubuntu 22.04 LTS, Mint 21 and Debian 11.All OS work wonderfully, except for Bluetooth on Debian 11.Ubuntu and Mint recognize the internal Bluetooth card in my Asus laptop.Debian says I have to use a Bluetooth dongle.The dongle does work, however it's using up a USB port I could use for something else.
I have a feeling Debian 11 on installation did not load the appropriate firmware drivers for the internal Bluetooth card.
How can I fix this situation?


text:
Q: Could we have a by hand proof that $H^{0,q}_{\bar{\partial}}(\mathbb{C}P^n)=0$ for $q>0$? It is well known that $H^{0,q}_{\bar{\partial}}(\mathbb{C}P^n)=0$ for $q>0$ and the usual proof is through Hodge decomposition. See Page 118 of Principles of Algebraic Geometry by Griffiths and Harris.
Could we have a direct, by hand proof that $H^{0,q}_{\bar{\partial}}(\mathbb{C}P^n)=0$ for $q>0$ without involving Hodge decomposition?


text:
Q: How to properly set the data in swagger-js client for a PUT request which requires BOTH formData and path parameters? I have a method that requires both formData and path parameters. How can I set the data in the request?
I am using swagger-js v2.
Let's say the example below requires 3 parameters:

*

*ResetPassword is a path parameter

*password is a formData parameter

*repeat_password is a formData parameter

swagger_client.apis.users.resetPassword(<HELP!!>,
function(response) {
    // success
}, function(err) {
    // failure
});

A: I'm not sure if this is still relevant for you but I stucked at the same problem and found a solution.
Define your parameter object like this:

var paramObj = {
                              ResetPassword: "resetpw",
                              parameterContentType: "multipart/form-data",
                              password: formData1,
                              repeat_password: formData2

                           };

then call with
swagger_client.apis.users.resetPassword(paramObj,...


text:
Q: Nuxtjs + youtube data api Want to use youtube data api in my Nuxt app
Question:
in google docs in js example gapi is used (https://apis.google.com/js/api.js)
what's the purpose of this lib if I can simply use requests like:
https://www.googleapis.com/youtube/v3/videos?part=id&chart=mostPopular&key=MyAPIKey
as I've noticed, in there example with gapi (https://developers.google.com/youtube/v3/docs/videos/list) there is no API Key, but ClientId
and in simple get request above there is no ClientId but simply API Key
So,
1. why to use gapi? is it better and more correct than using simple get requests like example above?
2. why in one case they use ClientId and in another it's enough to send API key? is the first approach is more safe or what?
3. what's the best use of Youtube Data API in Nuxt? have to use gapi or send simple get requests with API key?


text:
Q: Resetting & reseeding DB using rake task Using the code below to reset & reseed the DB
task init: [:environment, 'db:migrate:reset', 'db:seed']

db:seed creates a few users & few objects. It also updates role for few users.
db:seed throws following error NoMethodError: undefined method 'role' for User.
There is a migration file which adds role column to User table.
Unable to resolve this. Tries to write separate task for db:seed. Tried following
task init: [:environment, 'db:migrate:reset', 'db:seed'] do
  Rake::Task['db:seed'].invoke
end

Same error as before. Why is column from migration file isn't loaded for db:seed or I am missing something here?
Error log:
NoMethodError: undefined method `role' for #<User:0x00007fd5ecb239e0>
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activemodel-6.0.3.2/lib/active_model/attribute_methods.rb:432:in `method_missing'
/Users/Desktop/rails_app/app/models/user.rb:17:in `update_role'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:428:in `block in make_lambda'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:200:in `block (2 levels) in halting'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:605:in `block (2 levels) in default_terminator'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:604:in `catch'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:604:in `block in default_terminator'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:201:in `block in halting'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:513:in `block in invoke_before'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:513:in `each'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:513:in `invoke_before'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:134:in `run_callbacks'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/callbacks.rb:825:in `_run_validation_callbacks'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activemodel-6.0.3.2/lib/active_model/validations/callbacks.rb:117:in `run_validations!'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activemodel-6.0.3.2/lib/active_model/validations.rb:337:in `valid?'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/validations.rb:68:in `valid?'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/validations.rb:84:in `perform_validations'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/validations.rb:53:in `save!'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/transactions.rb:318:in `block in save!'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/transactions.rb:375:in `block in with_transaction_returning_status'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/connection_adapters/abstract/database_statements.rb:280:in `block in transaction'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/connection_adapters/abstract/transaction.rb:280:in `block in within_new_transaction'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/concurrency/load_interlock_aware_monitor.rb:26:in `block (2 levels) in synchronize'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/concurrency/load_interlock_aware_monitor.rb:25:in `handle_interrupt'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/concurrency/load_interlock_aware_monitor.rb:25:in `block in synchronize'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/concurrency/load_interlock_aware_monitor.rb:21:in `handle_interrupt'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activesupport-6.0.3.2/lib/active_support/concurrency/load_interlock_aware_monitor.rb:21:in `synchronize'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/connection_adapters/abstract/transaction.rb:278:in `within_new_transaction'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/connection_adapters/abstract/database_statements.rb:280:in `transaction'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/transactions.rb:212:in `transaction'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/transactions.rb:366:in `with_transaction_returning_status'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/transactions.rb:318:in `save!'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/suppressor.rb:48:in `save!'
/Users/Desktop/.rvm/gems/ruby-2.7.1/gems/activerecord-6.0.3.2/lib/active_record/persistence.rb:55:in `create!'
/Users/Desktop/rails_app/app/services/init_data:6:in `process'
/Users/Desktop/rails_app/db/seeds.rb:3:in `<main>'

A: Using db:reset solved the issue. i.e.
task init: [:environment, 'db:reset']

db:reset executes db:drop, db:setup.
db:setup executes db:schema:load whereas db:migrate:reset executes db:migrate. And db:schema:load is faster than db:migrate.
Not sure why db:migrate causes the issue.
As Sergio suggested stale cache could be the cause. And his suggestion in the comments User.reset_column_information loads all the columns.


text:
Q: Why columns in views are always nullable? I'm using postgreSQL. Why the fields in the views always are nullable? I get that in some situation computed columns can be NULL, but in the below snippet I only "forward" those data.
I noticed that MySQL behaves like I'd have, and I don't need special feature from psql, so I think I'll switch to MySQL.
But I really wonder WHY postgreSQL doesn't behave "normally"?
It is quite annoying when you are working with system like SQLx in Rust bridging SQL and Rust types since you cannot rely on this tool when you refers to views in your Rust code.
postgres=# CREATE TABLE a( field INT NOT NULL);
CREATE TABLE
postgres=# CREATE VIEW b AS SELECT field FROM a;
CREATE VIEW

postgres=# SELECT column_name,is_nullable, data_type
FROM information_schema.columns
WHERE table_name ='a';
 column_name | is_nullable | data_type
-------------+-------------+-----------
 field       | NO          | integer
(1 row)

postgres=# SELECT column_name,is_nullable, data_type
FROM information_schema.columns
WHERE table_name ='b';
 column_name | is_nullable | data_type
-------------+-------------+-----------
 field       | YES         | integer
(1 row)

A: It sounds like this is just the way it is in PostgreSQL (which I understand is a sucky answer). It seems like under certain conditions for certain versions of PostgreSQL, a view's column may be attributed as non-nullable. This StackOverflow answer gives the example where if the field is a primary key of the base table, in a vanilla view, it is showing as non-nullable in the view's schema.
I suppose PostgreSQL has some strict requirements on what it assumes can truly be non-nullable in a view definition.

A: In the case of the view, nullability is just informational. No constraint is enforced on the view itself, but on the underlying tables.
I can see two uses of nullability information:

*

*It tells the optimizer something.  That is not interesting in the case of a view, because the statement is rewritten to operate on the underlying tables anyway, and there we have that information.

*It is nice information for the user.
So we are missing out on the second point here. But if you know the view definition, you can figure this out for yourself, albeit with a little extra work.
So I would say that PostgreSQL doesn't have it because it is not very important, and because nobody cared to implement it.


text:
Q: IIS - the request is rejected by HTTP filter when there are european char in the url I'm using a web api application that returns valid post-codes for given city. The application is hosted on WinServer 2008 R2, IIS 6.1.
Application works fine as long as there are no European-char (ä,ß,æ,ø,å) in the URL.
But with any special/European-char in URL I get the following error message:
Error Code: 500 Internal Server Error. The request was rejected by the HTTP filter. Contact the server administrator. (12217)
E.g. for working URL: edu.web/Api/PostCode/Heidenau
E.g. for non-working URL: edu.web/Api/PostCode/Heidehäuser
E.g. for non-working URL with URL encoding: edu.web/Api/PostCode/Heideh%C3%A4user
How to configure the IIS to accept european chars?
Thanks.

A: I've resolved the issue by involving our system administrator.
All Internet requests are passed through ISA server (Microsoft Forefront Threat Management Gateway) which by default filters all requests with special characters before they hit our Webservers.
After we changed the Configuration, everything started working as intended.


text:
Q: Filtering with regex in javascript I am working currently on a project where I want to filter against an input I give. At the moment, my approach is:
var num = some.innerText;
var filter = input.value.toUpperCase().trim();

if (num.toUpperCase() == filter) {do something}

If my filter is 11 I will find only the num where the text is exactly 11, but sometimes
my numbers have letters like 11A or 11B and I would like to find all instances of 11 when I filter for that. My idea is to use an or that I either check for an exact match or a match, where after the filter follows any letter character. I wanted to use regex, but this doesn't seem to work.
My regex approach
if (num.toUpperCase() == filter || num.toUpperCase() == filter + /[a-zA-Z]/)
{do something}

If I do this it works, but only for the letter d and I dont want to write 24 or conditions
if (num.toUpperCase() == filter || num.toUpperCase() == filter + "D") {do something}

I tried
if (num.toUpperCase().match(filter)  {do something}

, but I dont want to find 11, 123, and so on when I enter 1 into the filter.

A: This seems to work perfectly for my purpose. I can now get the results 11D, 11E, 11B and so on when entering 11 in to the filter and also 11D if I use that as the filter.
if (num.replace(/\D+/,'') == filter || num == filter) {do something}


text:
Q: Choice of asymptotic bound (O vs Θ) for three different implementations of algorithm to remove duplicates from list I'm trying to get my head around asymptotic notation for time complexity. I understand that big-O is the upper bound and theta is a tight bound, but I'm confused as to when to use which, and why sometimes one is given rather than the other.
Specifically, for the three implementations of the same algorithm given below, the author has described the time complexity as O(n²), Ө(nlogn) and Ө(n) on average respectively.
I want to understand what goes on in the mind of an expert in these matters when making these assignments. Why is the fist given as Big-O, while the other two as theta, and why does the last mention average case while the other two don't?
Any help much appreciated.
def RemoveDuplicates(A):
    m = 0
    for i in range(0, len(A)):
        if (not elem(A, m, A[i])):
            A[m] = A[i]
            m += 1
    return m

def elem(A, n, e):
    for i in range(0, n):
        if (A[i] == e):
            return 1
    return 0

A = [54, 26, 93, 54, 77, 31, 44, 55, 20]
RemoveDuplicates(A)
print(A)
# Time Complexity O(n²)

def RemoveDuplicates(A):
    A.sort()
    print(A)
    j = 0
    for i in range(1, len(A)):
        if (A[j] != A[i]):
            j += 1
            A[j] = A[i]

    print(A[:j + 1])

A = [54, 31, 93, 54, 77, 31, 44, 55, 93]
RemoveDuplicates(A)
# Time Complexity: Ө(nlogn)

A = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = []
helperSet = set()
for x in A:
    if x not in helperSet:
        unique.append(x)
        helperSet.add(x)

print(A)
print(unique)
# Time Complexity: Ө(n) on average

A: For the first case, the teacher wrote O(n²) and not Ө(n²) because there are cases where it might be faster than n²; for instance, if the array A is filled with copies of only one unique element, such as A = [3, 3, 3, 3, 3, 3, 3, 3, 3 ], then in this particular case the algorithm will take n operations instead of n². But it will never take more than n².
For the second case, the complexity of the algorithm will be the same as the complexity of A.sort(); the for-loop that follows is O(n), which is faster than A.sort(). So the complexity of the algorithm is that of sorting an array. The teacher assumed that this was always exactly n log(n). That's not entirely true - for instance, the implementation of .sort() in CPython is such that if you try to sort an array that is already sorted, it will be much faster.
For the third case, if we assume that helperSet.add(x) takes O(1) time complexity, then the algorithm is Ө(n), since it's just a for-loop. Now, if you look at the documentation of set.add, you'll read something like "set.add is almost-always O(1), unless you're extremely unlucky or you're under attack" (this has to do with hashing functions and probability of collision, because sets are usually implemented as hashmaps). So the teacher simplified this to "in average, set.add is O(1), so in average, our algorithm is Ө(n)".


text:
Q: How to put specific parameters as independent variables into csv-file in JMeter? Let's say I need to use in JMeter csv file with intrusion of variables into it, not only as a set of values, something like following:
(string1:)  parameter11_value;${variable12};parameter13_value;${variable14};parameter15_value
(string2:)  parameter21_value;${variable22};parameter23_value;parameter24_value;${variable24};parameter25_value
(string3:)  parameter31_value;parameter32_value;${variable32};parameter33_value;parameter34_value;parameter35_value
etc. (no template in structure, only mix of constant part with variable part and ";" between them).
I.e. resulting string should be build both from constant values and external independent variables (external - relatively to csv file).
Are there a way to use in JMeter csv file not only values, but put/get/use dynamic parameters as variables from the another external file on the fly?

A: Yep, check out __eval() function
Demo:

More information: Here's What to Do to Combine Multiple JMeter Variables


text:
Q: Dynamic data storage with version - asp.net My requirements are as follows,
The User will upload excel file contains metadata tables with data.Excel file can have multiple sheets and each sheet corresponds to a table. These are dynamic contents and using the sheet name we have to check such a table already exists or new table. These table information need to be stored in the server and displayed later.
Storage consists of two stages such as common/Personal. Common stage, all tables are common for all users and In personal each user will be having their own set of tables.
The common stage requires version control for tables, such as whenever there is a modification; such as edit table/new table, user having provision to overwrite to existing version, or create new version.
My question is: how can we store these data in the server?
Constraints are: Different versions in Common stage can have same table names and different users can have same table in Personal stage.
Is it OK to proceed with SQL schema or should I can go for XML to store the data and structure/ Any other thoughts?

A: As the schema of the worksheets are likely to change, you're better off looking at a NoSQL database (also known as Document Database) such as CouchDB, MongoDB or RavenDB (there are others). Document Databases do not have a schema, like relational databases (SqlServer, Oracle, MySQL, etc) so they store any data of any shape.
You will need to write some code that opens the Excel sheet. Check to see if the data is XLS (old Excel), XLSX (new Excel) or CSV (common format), because that will change which library you use to open them. Once you have the worksheet in memory, you should be able to save it straight the document database, making it common or personal as necessary.
I would avoid XML files because it is likely that you will need to search across the data or at least perform some sort of a lookup. This would be difficult with XML files and you might end up writing a database that does the same as a document DB!


text:
Q: $A = \sum_{n=0}^\infty a_n$ and $b_n \to B$ implies $\sum_{k=0}^n a_k b_{n-k} \to AB$ This question is motivated by the answer With $y_n$ a sequence of real numbers, prove that if $y_n=x_{n-1}+2x_{n}$ converges then $x_n$ also converges,
where essentially the following fact is used:

Let $A = \sum_{n=0}^\infty a_n$ be an absolutely convergent series,
  and $(b_n)$ a convergent sequence, $b_n \to B$.
   Then
  $$
 \lim_{n \to \infty} \sum_{k=0}^n a_k b_{n-k} = A B \, .
$$

This is not too difficult to prove (sketch): Write
$$
 \sum_{k=0}^n a_k b_{n-k} = B \sum_{k=0}^n a_k +
 \sum_{k=0}^n a_k \bigl( b_{n-k} - B \bigr)
$$
The first sum converges to $AB$. For $\varepsilon > 0$, split the second sum into two parts
$$
 \sum_{k=0}^{n-N} a_k \bigl( b_{n-k} - B \bigr) + \sum_{k=n-N+1}^n a_k \bigl( b_{n-k} - B \bigr) \\
=  \sum_{k=0}^{n-N} a_k \bigl( b_{n-k} - B \bigr) + \sum_{j=0}^{N-1} a_{n-j} \bigl( b_j - B \bigr)
$$
where $N$ is chosen such that $\lvert b_n - B \rvert < \varepsilon$
for $n \ge N$. The first part can be estimated by $\varepsilon
\sum_{n=0}^\infty |a_n|$, and the second (finite) sum converges to zero.
Now I am fairly sure that this is not new and must have been done before.
However, I could  not find a reference. So my question is:
Is there a name for the above statement, or
is there some "well-known theorem" for which this is just a special case?
The term $  \sum_{k=0}^n a_k  b_{n-k}$ reminds me of the Cauchy product,
but nothing is given about $\sum b_n$ here. Or is it perhaps
related to summation methods for series?
(Or is it so trivial that everybody just knows it?)

A: In electronics, we call such a sum : the numerical convolution of two signals. And like you've remarked, it is a Cauchy product.
This theorem was proved by Franz Mertens. What's missing from the above proof, is supposing that at least one of the series has to be absolutely convergent. Otherwise, the estimation of the first part of the second sum, isn't justified. A counterexample is given in the Wikipedia link.

A: As it turns out, the statement is equivalent to Merten's theorem about the Cauchy product of two series (with the first series being absolutely convergent).
We define
$$
\begin{align}
 \beta_0 &= b_0 \\
 \beta_n &= b_n - b_{n-1} \text{ for } n \ge 1 \, .
\end{align}
$$
and $\gamma_n = \sum_{k=0}^n a_k \beta_{n-k}$.
Then $b_n = \beta_0 + \ldots + \beta_n$ and $B = \sum_{n=0}^\infty \beta_n$. A simple calculation shows that
$$
 \sum_{k=0}^n a_k b_{n-k} = \sum_{k=0}^n \gamma_k \, .
$$
Therefore $\lim_{n \to \infty} \sum_{k=0}^n a_k b_{n-k} = A B $ is equivalent to $ \sum_{n=0}^\infty \gamma_n = A B$, and that is precisely he contents of Merten's theorem.


text:
Q: Why do I have to reinstall Kinect SDK everytime I restart PC I'm currently work with Kinect for Windows SDK version 1 under Win7, VS2010, C#.NET.
Demos in Microsoft Kinect for Windows SDK Sample Browser can't run properly after Kinect is connected to my PC.

*

*Kinect Explorer(in C#) says Kinect is not ready (which is different from Please insert a Kinect... if Kinect is not connected).

*Shapes Game(in C#) says Oops... Something's wrong with Kinect

*Skeletal Viewer(in C++) can run, but only depth image run properly. Color image has a frame rate less than 1! And skeleton view show nothing but a black background.

Here's what I have tried:

*

*The above thing will not happen(which means everything goes all right) if SDK is reinstalled and PC is not restarted. So... I have to reinstall Kinect SDK everytime I restart my PC!!!

*I checked the Resource Manager after Kinect USB is plugged to my PC. The strange thing is that if the PC is not restarted after reinstalling SDK, there're 4 devices concerning Kinect: Audio, Speech, NUI and Security. But after restart PC, the Security Device won't be shown after Kinect is connected to PC.

*I've tried with 2 different Kinect(one at a time) and have the same situation.

*Using different USB slots make no difference.

I don't know what's wrong with my PC or how to do next. The only thing I know is that I don't want to reinstall Kinect SDK everytime I restart my PC! So would anybody offer some solution? Thanks very much!

A: I came across this problem just now, and finally solve it. I accidentally killed the process names "KinectManagementService" in the task manager, and then I could not connect the Kinect any more. Have a glance at the task manager whether the process is there.
Open Windows Service, and start the service "Kinect Management". That's it!


text:
Q: problema GridView lineaFactura

*

*idLineaFactura

*cantidad

*idProducto

producto

*

*idProducto

*nombre

*referencia

*precioUnitario

*idCategoria
SELECT  L.cantidad, P.nombre , P.precioUnitario, (L.cantidad *
P.precioUnitario) as precioSubTotal FROM lineaFacturaTMP L , producto P
WHERE p.idProducto = L.idProducto

El problema que tengo es que estoy tratando de listar cantidad , nombre del producto , precio , subtotal
 en un gridView , aunque pongo precioSubTotal en el dataField me saca  error   :

{"No se encontró ningún campo o propiedad 'precioSubTotal' en el
  origen de datos seleccionado."},

Ejecuto la consulta en el sqlManagementStudio y si me trae los datos  ,pero el gridView me arroja el error

A:

GridView

<asp:GridView ID="gvLineaFactura" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="idLineaFactura" OnRowDeleting="gvLineaFactura_RowDeleting">
            <Columns>
                <asp:BoundField DataField="idLineaFactura" HeaderText="ID" />
                <asp:BoundField DataField="cantidad" HeaderText="Cantidad" />
                <asp:BoundField HeaderText="Descripcion" DataField="nombre" />
                <asp:BoundField DataField="precioUnitario" HeaderText="Valor Unitario" />
                <asp:BoundField DataField="precioSubTotal" HeaderText="sub Total" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#242121" />
        </asp:GridView>

capa  de presentacion presentacion

BusisnessVenta negocio = new BusisnessVenta();

gvLineaFactura.DataSource = negocio.listarLineafactura();
gvLineaFactura.DataBind();

capa negocio

 public List<LineaFacturaTMP> listarLineafactura()
        {
            return linea.listarLineafactura();
        }

capa datos

 public List<LineaFacturaTMP> listarLineafactura()
        {
            List<LineaFacturaTMP> lista = new List<LineaFacturaTMP>();

            try
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = this.datosConexion;
                    con.Open();

                    string query = "SELECT L.idLineaFactura,  L.cantidad, P.nombre , P.precioUnitario, (L.cantidad * P.precioUnitario) as precioSubTotal   FROM lineaFacturaTMP L , producto P WHERE p.idProducto = L.idProducto";

                    SqlCommand cmd = new SqlCommand(query, con);
                    SqlDataReader lector = cmd.ExecuteReader();

                    while (lector.Read())
                    {
                        LineaFacturaTMP lineaFacturaTMP = new LineaFacturaTMP()
                        {
                            idLineaFactura =  Convert.ToInt32(lector["idLineaFactura"]),
                            Cantidad = Convert.ToInt32(lector["cantidad"]),
                            nombre = Convert.ToString(lector["nombre"]),
                            PrecioUnitario = Convert.ToDecimal(lector["precioSubTotal"]),
                            SubTotal = Convert.ToDecimal(lector["precioSubTotal"])
                        };
                        lista.Add(lineaFacturaTMP);
                    }

                }
            }
            catch (Exception e)
            {

                throw e;
            }

            return lista;

        }


text:
Q: How can a server broadcast a message to other clients? The program is intended to have multiple clients connect to a single server and the clients are able to send and receive messages among other clients.
For example if Client A says "Hi", Client B and Client C connected to the server would also receive "Hi".
In my current code, the server only receives the messages sent by the clients.
I'm currently looking for a solution to have the server broadcast the message sent by a client (eg. ClientA) to other clients. Any advice would be much appreciated.
This server class handles the connections of multiple clients with the use of threads:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

class EchoThread extends Thread {
    private Socket socket;

    //constructor
    public EchoThread(Socket clientSocket) {
        this.socket = clientSocket;
    }

    @Override
    public void run() {
        DataInputStream inp = null;

        try {
            inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

            //print whatever client is saying as long as it is not "Over"
            String line = "";
            while (!line.equals("Over")) {
                try {
                    line = inp.readUTF();
                    System.out.println(line);
                } catch (IOException e) { System.out.println(e); }
            }

            //closes connection when client terminates the connection
            System.out.print("Closing Connection");
            socket.close();
        } catch (IOException e) { System.out.println(e); }
    }
}

public class Server {
    private static final int PORT = 5000;

    public static void main(String args[]) {
        ServerSocket serverSocket = null;
        Socket socket = null;

        //starts the server
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("Server started");
            System.out.println("Waiting for a client ...\n");
        } catch (IOException e) { System.out.println(e); }

        //while loop to accept multiple clients
        int count = 1;
        while(true) {
            try {
                socket = serverSocket.accept();
                System.out.println("Client " + count + " accepted!");
                count++;
            } catch (IOException e) { System.out.println(e); }

            //starts the server thread
            new EchoThread(socket).start();
        }
    }
}

and this is the client class (I have multiple instances of this code running):
import java.net.*;
import java.io.*;

public class ClientA {
    private Socket socket = null;
    private DataInputStream input = null;
    private DataOutputStream output = null;

    public ClientA(String address, int port) {
        //establish connection
        try {
            socket = new Socket(address, port);
            System.out.println("Connected");

            //takes input from terminal
            input = new DataInputStream(System.in);

            //sends output to the socket
            output = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) { System.out.println(e); }

        //string to read message from input
        String line = "";

        //keep reading until "Over" is input
        while (!line.equals("Over")) {
            try {
                line = input.readLine();
                output.writeUTF(line);
            } catch (IOException e) { System.out.println(e); }
        }
        //close the connection
        try {
            input.close();
            output.close();
            socket.close();
        } catch (IOException e) { System.out.println(e); }
    }

    public static void main (String args[]) {
        ClientA client = new ClientA("127.0.0.1", 5000);
    }
}

Do feel free to correct me on my code comments as I'm still not very familiar with socket programming.

A: I would have a single server thread which would maintain a register of the clients, possibly in a concurrent collection. Then I would send each message received from a client to all other clients.

A: You did well. Just add a thread to receive message in ClientA; and store socket clients in Server.
In fact, Server is also a "client" when is send message to client.
I add some code based on your code. It works well, hope it's helpful.
class EchoThread extends Thread {
//*****What I add begin.
private static List<Socket> socketList = new ArrayList<>();
//*****What I add end.

private Socket socket;

//constructor
public EchoThread(Socket clientSocket) {
    this.socket = clientSocket;
    socketList.add(socket);
}

@Override
public void run() {
    DataInputStream inp = null;

    try {
        inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

        //print whatever client is saying as long as it is not "Over"
        String line = "";
        while (!line.equals("Over")) {
            try {
                line = inp.readUTF();
                System.out.println(line);

                //*****What I add begin.
                sendMessageToClients(line);
                //*****What I add end.
            } catch (IOException e) { System.out.println(e); break;}
        }

        //closes connection when client terminates the connection
        System.out.print("Closing Connection");
        socket.close();
    } catch (IOException e) { System.out.println(e); }
}

//*****What I add begin.
private void sendMessageToClients(String line) throws IOException {
    for (Socket other : socketList) {
        if (other == socket) {
            continue;//ignore the sender client.
        }
        DataOutputStream output = new DataOutputStream(other.getOutputStream());
        output.writeUTF(line);
    }
}
//*****What I add end.

}
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;

public ClientA(String address, int port) {
    //establish connection
    try {
        socket = new Socket(address, port);
        System.out.println("Connected");

        //takes input from terminal
        input = new DataInputStream(System.in);

        //sends output to the socket
        output = new DataOutputStream(socket.getOutputStream());

        //*****What I add begin.
        //Here create a thread to receive message from server.
        DataInputStream inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
        new Thread(() -> {
            while (true) {
                String str;
                try {
                    str = inp.readUTF();
                    System.out.println(str);
                } catch (IOException e) {
                    e.printStackTrace();//error.
                    break;
                }
            }
        }, "Client Reveiver.").start();
        //*****What I add end.

    } catch (IOException e) { System.out.println(e); }

    //string to read message from input
    String line = "";

    //keep reading until "Over" is input
    while (!line.equals("Over")) {
        try {
            line = input.readLine();
            output.writeUTF(line);
        } catch (IOException e) { System.out.println(e); }
    }
    //close the connection
    try {
        input.close();
        output.close();
        socket.close();
    } catch (IOException e) { System.out.println(e); }
}