text:
Q: url extracted from Beautiful Soup from href Tag is not recognized by urllib2 I am learning Python and Beautiful Soup and as an exercise I webscrape a testing webpage.  My objective is to extract a url from the webpage and then follow this url to extract another url.
My code is the following:
First step:
path = "http://python-data.dr-chuck.net/known_by_Fikret.html"
pattern = re.compile(r'"(.+)"')
page = urllib2.urlopen(path)
soup = bs(page, 'lxml')
a = soup.find_all("a")
path = re.search(pattern, str(a[2])).group(0)
path

Out:
'"http://python-data.dr-chuck.net/known_by_Montgomery.html"'

Second step:
page = urllib2.urlopen(path)
soup = bs(page, 'lxml')
a = soup.find_all("a")
path = re.search(pattern, str(a[2])).group(0)
path

Out:
---------------------------------------------------------------------------
URLError                                  Traceback (most recent call last)
<ipython-input-33-14ad9508aea0> in <module>()
----> 1 page = urllib2.urlopen(path)
      2 soup = bs(page, 'lxml')
      3 a = soup.find_all("a")
      4 path = re.search(pattern, str(a[2])).group(0)
      5 path

C:\users\alex\Anaconda2\lib\urllib2.pyc in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    152     else:
    153         opener = _opener
--> 154     return opener.open(url, data, timeout)
    155
    156 def install_opener(opener):

C:\users\alex\Anaconda2\lib\urllib2.pyc in open(self, fullurl, data, timeout)
    427             req = meth(req)
    428
--> 429         response = self._open(req, data)
    430
    431         # post-process response

C:\users\alex\Anaconda2\lib\urllib2.pyc in _open(self, req, data)
    450
    451         return self._call_chain(self.handle_open, 'unknown',
--> 452                                 'unknown_open', req)
    453
    454     def error(self, proto, *args):

C:\users\alex\Anaconda2\lib\urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    405             func = getattr(handler, meth_name)
    406
--> 407             result = func(*args)
    408             if result is not None:
    409                 return result

C:\users\alex\Anaconda2\lib\urllib2.pyc in unknown_open(self, req)
   1264     def unknown_open(self, req):
   1265         type = req.get_type()
-> 1266         raise URLError('unknown url type: %s' % type)
   1267
   1268 def parse_keqv_list(l):

URLError: <urlopen error unknown url type: "http>

Why urlopen does not recognize the url?
Your advice will be appreciated.

A: The issue I guess is that you have extra quotes in you path
'"http://python-data.dr-chuck.net/known_by_Montgomery.html"'

Trim the string using strip() as
path = path.strip('"')
page = urllib2.urlopen(path)

You can use BeautifulSoup to extract the src of from the anchor tags. You need not use regex for this purpose
Example
>>> html = """<a href="http://www.google.com">"""
>>> soup.find_all('a')[0]['href']
'http://www.google.com'

A: Use .group(1) when retrieving result of regex matching. .group(0) returns the whole matched string including quotes.

A: path.strip('"')

out:
'http://python-data.dr-chuck.net/known_by_Montgomery.html'

the url is incorrect, just strip the " in the url or adjust your regex

A: Your problem is because you have " in url. Remove it.
But BeautifulSoup has own methods to get url - a[2]['href']
from bs4 import BeautifulSoup as bs
import urllib2

# - first page -

path = "http://python-data.dr-chuck.net/known_by_Fikret.html"

page = urllib2.urlopen(path)
soup = bs(page, 'lxml')

all_links = soup.find_all("a")

#for link in all_links:
#    print link['href']

print all_links[2]['href']

# - second page -

path = all_links[2]['href']

page = urllib2.urlopen(path)
soup = bs(page, 'lxml')

all_links = soup.find_all("a")

#for link in all_links:
#    print link['href']

print all_links[2]['href']

or shorter
from bs4 import BeautifulSoup as bs
import urllib2

def get_url(path):
    page = urllib2.urlopen(path)
    soup = bs(page, 'lxml')

    all_links = soup.find_all("a")

    #for link in all_links:
    #    print link['href']

    return all_links[2]['href']

# - first page -

path = "http://python-data.dr-chuck.net/known_by_Fikret.html"

path = get_url(path)

print path

# - second page -

path = get_url(path)

print path


text:
Q: Applying color to Jqgrid row I want to apply background color to row of jqGrid row based on value of company attributes, however the basic rowattr is not applying class to rows.  Below is the code,have added *** against the condition.
function drawGrid() {
                $("#grid").jqGrid("GridUnload");
                var grid = $("#grid"),lastSel;
                jQuery("#grid").jqGrid({
                    sortable: true,
                    datatype: "local",
                    data: $scope.jqGridData,
                    colNames: $scope.jqgridColHeader,
                    colModel: $scope.colModelValue,
                    viewrecords: true,
                    caption: "Peer Analysis",
                    rowNum:10,
                    rowList:[10,20,30],
                    recordpos: 'left',
                    footerrow : true,
                    userDataOnFooter : true,
                    restoreAfterSelect: false,
                    saveAfterSelect: true,
                    altRows : true,
                    multiselect: true,
                    cellEdit:   true,
                    autowidth:true,
                    treeGrid: true,
                    grouping: true,
                    shrinkToFit: true,
                    pager: '#pager',
                    gridview: true,
                    'cellEdit': true,
                    'cellsubmit' : 'clientArray',
                    editurl: 'clientArray',
                    onSelectRow: function(id){
                    },
                    ***rowattr: function (rd) {
                    console.log("rddetails"+rd.isBaseCompany);
                    if (rd.isBaseCompany=="true") {
                    return {"class": "baseCompanyClass"};
                    //alert("hi");
                    } }***,
                    gridComplete: function() {
                    },afterSaveCell:function (rowid, cellname, value, iRow, iCol){
                        var rowData = $('#grid').jqGrid('getRowData', rowid);
                        $('#grid').jqGrid('saveRow', rowData);
                        var price = rowData.price;
                        var tarPrice = rowData.tagetPrice
                        var formula0= rowData.formula0;
                        var formula1= rowData.formula1;
                        var formula2= rowData.formula2;
                        var formula3= rowData.formula3;
                        var formula4= rowData.formula4;

                        }else if(cellname=='tagetPrice'){
                            rowData.upside = Number(tarPrice/price)-1;
                            $('#grid').jqGrid('setRowData', rowid, rowData);
                        }else{
                            if(cellname=='formula0'){
                                rowData.formula0 = formula0;
                            }if(cellname=='formula1'){
                                rowData.formula1 = formula1;
                            }
                            if(cellname=='formula2'){
                                rowData.formula2 = formula2;
                            }if(cellname=='formula3'){
                                rowData.formula3 = formula3;
                            }if(cellname=='formula4'){
                                rowData.formula4 = formula4;
                            }
                            $('#grid').jqGrid('setRowData', rowid, rowData);
                        }
                    },ondblClickRow: function(rowid) {
                            $scope.newBaseComp = jQuery('#grid').jqGrid ('getRowData', rowid);
                            $scope.showChangeBase(rowid-1);
                        },
                        beforeSaveCell : function(rowid,celname,value,iRow,iCol) {
                          if(rowid) {
                              return value;
                          }
                        },
                        loadComplete:function()
                        {

                        }});

                    }

Here is the css class for the same.

 .ui-widget-content .baseCompanyClass{
    background-color: #DCFFFF;
    background-image: none;
}

So while checking the condition if(rd.isBaseCompany=="true")
      even though the the attribute comes to be true but  doesn't enter into the if condition for setting the class.what could be the issue??

A: You could make and call a function as the SetGridColors() bellow in your .js file.
With jqGridAfterGridComplete you bind your grid with the function so on completion of the grid the function will execute.
So with the bellow code, you read all rows and if you have a field called 'isBaseCompany' it will draw the row accordingly. (if you prefer to add a class to the row instead for css handle, use the the code in the comments)
function SetGridColors() {
    $("#your_grid_id").bind("jqGridAfterGridComplete", function () {
        var rows = $("#your_grid_id").getDataIDs();
        for (var i = 0; i < rows.length; i++) {
            var status = $("#your_grid_id").getCell(rows[i], "isBaseCompany");
            if (isBaseCompany== "1") {
                $("#your_grid_id").jqGrid('setRowData', rows[i], false, { color: 'black', weightfont: 'bold', background: 'lightgreen' });
                //$("#your_grid_id").find('#' + rows[i]).addClass("isBaseCompany-1");

            }
            else if (isBaseCompany= "0")
                $("#your_grid_id").jqGrid('setRowData', rows[i], false, { color: 'black', weightfont: 'bold', background: 'salmon' });
              //  $("#your_grid_id").find('#' + rows[i]).addClass("isBaseCompany-0");

    })
}

Hope it helps

A: Your datatype is local. The important part here is how is defined your data field isBaseCompany . If the data field is string the condition should be done if it is json definition then you just need to compare
if (rd.isBaseCompany) {
    // do something
}

or more strictly
if (rd.isBaseCompany === true ) {
    // do something
}

i.e isBaseCompany is a boolean and not string

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java TimeUnit error I wanted to make a Java program with Numberfields and a button.
When you click the button it waits and the time that was put in the Numberfield.The Integers work fine, but the function does not work.
Here is the code:
public void jButton1_ActionPerformed(ActionEvent evt) {
    sekunden = Integer.parseInt(jNumberField3.getText());
    minuten = Integer.parseInt(jNumberField2.getText());
    stunden = Integer.parseInt(jNumberField1.getText());
    zeit = sekunden + minuten*60 + stunden*60*60;//berechnet die zeit in sekunden
    TimeUnit.SECONDS.sleep(zeit);//here is the error
    System.out.println("zeit");
} // end of jButton1_ActionPerformed

The error message looks like this:
ES.java:78:27: error: unreported exception InterruptedException; must be caught or declared to be thrown TimeUnit.SECONDS.sleep(zeit);

A: Method call TimeUnit.SECONDS.sleep(zeit) throws an InterruptedException which has to be caught:
public void jButton1_ActionPerformed(ActionEvent evt) {
   try {
    sekunden = Integer.parseInt(jNumberField3.getText());
    minuten = Integer.parseInt(jNumberField2.getText());
    stunden = Integer.parseInt(jNumberField1.getText());
    zeit = sekunden + minuten*60 + stunden*60*60;//berechnet die zeit in sekunden
    TimeUnit.SECONDS.sleep(zeit);//here is the error
    System.out.println("zeit");
    }catch (InterruptedException e){
      //handle the exception
   }
}

A: You need to handle a potential InterruptedException that may happen when you call sleep(). This is why your code is getting a compilation error.
Please take a look at Catching and Handling Exceptions on JavaDocs to more details on exception handling.
In your case, you could easily solve it by handling the exception such as:
public void jButton1_ActionPerformed(ActionEvent evt) {
    sekunden = Integer.parseInt(jNumberField3.getText());
    minuten = Integer.parseInt(jNumberField2.getText());
    stunden = Integer.parseInt(jNumberField1.getText());
    zeit = sekunden + minuten*60 + stunden*60*60;//berechnet die zeit in sekunden
    try {
        // tries to call sleep
        TimeUnit.SECONDS.sleep(zeit);//here is the error
    } catch (InterruptedException e) {
        // handles any possible exception during the call to "sleep()"
        e.printStackTrace(); // prints the exception stack trace to the console
    }
    System.out.println("zeit");
} // end of jButton1_ActionPerformed

Some good references in exception handling are:

*

*Java exception handling

*Best practices in handling java exceptions


text:
Q: Flutter Type 'List' is not a subtype of type 'String' in type cast Problem
I'm new to flutter and right now I'm creating a delivery app.
The customer adds products in his cart, now I want to send this table of products chosen by the customer to the server to make his order and I have an error:
_TypeError (type 'List<dynamic>' is not a subtype of type 'String' in type cast

This is my class CartItem

class CartItem {
  String id, name, count, price, image;
  CartItem(this.id, this.name, this.count, this.price, this.image);
}

Here I add the product to the cart

List cart = [];

addItemCart(Food item) {
    adjustPrice(item.price, true);

    for (int i = 0; i < cart.length; i++) {
      if (cart[i].name == item.name) {
        setState(() {
          cart[i].count = (int.parse(cart[i].count) + 1).toString();
          adjustScroll(i);
        });
        return;
      }
    }
    setState(() {
      cart.add(new CartItem(item.id, item.name, '1', item.price.toString(), item.image));
      adjustScroll(cart.length - 1);
    });
  }

At this level where I get the error when I send to the server

payOnDelivery(
    adresseId,
    items,
    price,
    deliveryFee,
    tvaFee,
    finalPrice,
    paymentMode,
    devise,
  ) async {

    SharedPreferences sharedPreference = await SharedPreferences.getInstance();
    var token = sharedPreference.getString('token');
    var header = {'Authorization': 'Bearer $token'};

    Map data = {
      'adresseId': adresseId,
      'items': items,
      'price': price.toString(),
      'deliveryFee': deliveryFee.toString(),
      'tvaFee': tvaFee.toString(),
      'finalPrice': finalPrice.toString(),
      'paymentMode': paymentMode,
      'devise': devise
    };

    var jsonResponse;
    var response = await http.post(url + 'order/add/', body: data, headers: header);

    if (response.statusCode == 201) {
      jsonResponse = json.decode(response.body);

      setState(() {
        _isLoading = false;
        isLogged = true;
        cart = [];
      });
    } else {
      jsonResponse = json.decode(response.body);

      setState(() {
        _isLoading = false;
      });
    }
  }

A:  Post only take Map<String,String> in body but you are using
 Map<String,dynamic> that's why you  getting this error .In your
 Map<String,dynamic>   items  list is dynamic type you need to  encode it

 Map<String ,String> data = {
  'adresseId': adresseId,
  'items': json.encode(items)
  'price': price.toString(),
  'deliveryFee': deliveryFee.toString(),
  'tvaFee': tvaFee.toString(),
  'finalPrice': finalPrice.toString(),
  'paymentMode': paymentMode,
  'devise': devise
};

A: I solved the problem after several searches, I should just encode my List items in json by doing this:
var item = jsonEncode(items);

Map<String ,String> data = {
  'adresseId': adresseId,
  'items': item
  'price': price.toString(),
  'deliveryFee': deliveryFee.toString(),
  'tvaFee': tvaFee.toString(),
  'finalPrice': finalPrice.toString(),
  'paymentMode': paymentMode,
  'devise': devise
};


text:
Q: Dot product between rows of two matrices with same batch dimension Suppose I have two 2-dimensional tensors with the same batch dimension (that is, same number of rows).
import numpy as np

# Both t1 and t2 have shape (2, 3)

t1 = np.array([[1.0, 2.0, 3.0], [10.0, 11.0, 12.0]])
# array([[ 1.,  2.,  3.],
#        [10., 11., 12.]])

t2 = np.array([[21.0, 22.0, 23.0], [30.0, 31.0, 32.0]])
# array([[21., 22., 23.],
#        [30., 31., 32.]])

How do I compute the dot product between the rows of the two tensors? Specifically, I want to end up with the desired (2, 1) tensor result:
desired_result = np.array([np.dot(t1[0], t2[0]), np.dot(t1[1], t2[1])])
# array([ 134., 1025.])

I already tried:
np.dot(t1, t2)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<__array_function__ internals>", line 5, in dot
# ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)

np.tensordot(t1, t2)
# array(1159.)

Thanks for any help.

A: Since both t1 and t2 are 2d arrays, numpy.dot does matrix multiplication. For your case, you can just multiply the two arrays element wise and then sum rows:
(t1 * t2).sum(axis=1)
# [ 134. 1025.]

A: Using einsum:
np.einsum("ij,ij->i", t1, t2)

A: np.matmul/@ does batched dot, but the batch dimension is first of 3 (or more).  So we have to expand the arrays:
In [36]: t1[:,None,:]@t2[:,:,None]
Out[36]:
array([[[ 134.]],

       [[1025.]]])
In [37]: _.shape
Out[37]: (2, 1, 1)

and then squeeze out the extra dimension(s)
matmul is fast, but for this task the other answers might be clearer.


text:
Q: Deque: swap first and last element without using STL I have to implement deque using linked list without stl.
Issue:
I got stucked with function swap, and I can't figure out where is a problem.
My code you can see below:
#include <iostream>
using namespace std;

struct Node
{
    int mData;
    Node* pPrev, *pNext;
    Node()
    {
        pPrev = pNext = NULL;
    }
    Node(int value)
    {
        mData = value;
        pPrev = pNext = NULL;
    }
};

class Deque
{
private:
    Node *pFront, *pRear;
    int mSize;
public:
    Deque()
    {
        pFront = pRear = NULL;
        mSize = 0;
    }
    void pushFront(int data)
    {
        Node* newNode = new Node(data);
        if (newNode == NULL)
        {
            cout << "Error";
        }
        else
        {
            if (pFront == NULL)
            {
                pRear = pFront = newNode;
            }
            else
            {
                newNode->pNext = pFront;
                pFront->pPrev = newNode;
                pFront = newNode;
            }
            mSize++;
        }
    }
    void pushLast(int data)
    {
        Node* newNode = new Node(data);
        if (newNode == NULL)
        {
            cout << "Error";
        }
        else
        {
            if (pRear == NULL)
            {
                pFront = pRear = newNode;
            }
            else
            {
                newNode->pPrev = pRear;
                pRear->pNext = newNode;
                pRear = newNode;
            }
            mSize++;
        }
    }
    void deleteFront()
    {
        if (isEmpty())
        {
            cout << "Deque is empty";
        }
        else
        {
            Node* temp = pFront;
            pFront = pFront->pNext;

            if (pFront == NULL)
            {
                pRear = NULL;
            }
            else
            {
                pFront->pPrev = NULL;
            }
            delete temp;
            mSize--;
        }

    }
    void deleteLast()
    {
        if (isEmpty())
        {
            cout << "Deque is empty";
        }
        else
        {
            Node* temp = pRear;
            pRear = pRear->pPrev;

            if (pRear == NULL)
            {
                pFront = NULL;
            }
            else
            {
                pRear->pNext = NULL;
            }
            delete temp;
            mSize--;
        }
    }

    void swap()
    {
        if (isEmpty())
        {
            cout << "Deque is empty";
        }
        else
        {
            Node* tmp_head = pFront;
            tmp_head->mData = pFront->mData;
            tmp_head->pNext = pFront->pNext;
            tmp_head->pPrev = pFront->pPrev;

            Node* tmp_rear = pRear;
            tmp_rear->mData = pRear->mData;
            tmp_rear->pNext = pRear->pNext;
            tmp_rear->pPrev = pRear->pPrev;

            while (tmp_head->pNext != NULL && pRear->pPrev!=NULL) {
                tmp_head = tmp_head->pNext;
                tmp_rear = tmp_rear->pPrev;
            }
            pRear = tmp_head;
            pRear->mData = tmp_head->mData;

            pFront = tmp_rear;
            pFront->mData = tmp_rear->mData;

        }

    }
    bool isEmpty()
    {
        return (mSize == 0);
    }
    int getSize()
    {
        return mSize;
    }
    void show()
    {
        Node* node = pFront;
        while (node != NULL)
        {
            cout << node->mData << " ";
            node = node->pNext;
        }
    }
};

int main()
{
    Deque deque;
    deque.pushFront(1);
    deque.pushFront(2);
    deque.pushFront(3);
    deque.show();
    deque.swap();
    deque.show();
}

Being quite new in c++ algorithms, thus don't judge me in case I did some mistakes:)If there is any questions regarding code, don't hesitate to ask.
Thank You in advance!


text:
Q: How to add lib with jars to shared folder? I have a cross building scala-js project with a client, server and shared folder. If I add a lib folder with some jars in the server project folder I can reference the classes in the jars in my server code. But if add the lib folder in the shared project folder I can't reference the classes in my shared code. Can I add some command in my sbt build file to get my jars visible in my shared project or what should I do?

A: .jars should never be shared, since it is not the same .jar for Scala/JVM and Scala.js, even if they have the same source code.
If you have the two .jars for JVM and JS, you can put them in shared/jvm/lib/ and shared/js/lib/, respectively.
(if you use .crossType(CrossType.Pure), use .jvm/.js instead of jvm/js)


text:
Q: SMTP protocol + port numbers, IMAP, POP3 I need to provide a SMTP email service to a network and correctly configure the ports.
I understand SMTP uses port 25 over TCP, but have also read that SMTP is mainly used to transfer mail between mail servers and not the individual clients. Would either IMAP or POP3 be needed to send from the client to the server on port 993 or 995? or is there another port or way?
What other ports are needed to send an email via SMTP?
Thanks in advance


text:
Q: Azure requests being processed by staging after slot swap We have an App Service that hosts our website.
The website makes REST calls to our backend which is a Cloud Service (classic) web role running on two instances (behind one public IP).
We have one deployment slot, for the Cloud Service we deploy to the staging slot and when we're happy we swap staging and live slots.
Since I've increased the instance count from 1 to 2 in the Cloud Service it appears that swapping slots has little/no effect with most requests from the website still hitting the older instances (now staging). I've tried leaving it for 20+ hours and the picture remains the same. Now all 4 instances in both slots seem to be getting requests with the lion share hitting staging.
When I stop staging all requests go to the live slot.
Why is this happening? When I swap live/staging I expect staging to not get any more requests.

A: During swap,  the virtual IP addresses (VIPs) of Staging and Production for the deployments will be changed. I am sure that after swapped, the old instances can't be accessed using the production IP address. Please check whether there are other clients which accessed your old instances using the staging IP address.


text:
Q: How to resolve port 3000 for HTTPS using Nginx and NodeJs/NestJs? I'm just learning NestJs framework for NodeJs to create web-site with frontend using Vue and backend part.
All the components are on this one server: Nginx, frontend and backend (this article helps me https://scotch.io/tutorials/building-a-modern-app-using-nestjs-mongodb-and-vuejs)
All worked fine if I connect to web site by IP-address.
Then I need migrate it to real site with SSL for HTTPS access.
And here is a problem.
On frontend - side I changed the file /nestjs-frontend/src/helper.js to:
// ./src/helper.js
export const server = {
    baseURL: 'https://my_site.ru:3000'
}

NB! Port 3000
And the problem is in access from main domain https://my_site.com to inner API path https://my_site.com:3000
Please help me to resolve this problem.
My Nginx-config is:
server {

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name my_site.com www.my_site.com;

        location / {
                #proxy_set_header Host $host;

                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header        X-Real-IP $remote_addr;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header        X-Forwarded-Proto https;
                proxy_set_header        SSL_PROTOCOL $ssl_protocol;

                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                #proxy_set_header Host $http_host;
                proxy_set_header X-NginX-Proxy true;

                #proxy_set_header    X-Client-Verify  SUCCESS;
                #proxy_set_header    X-Client-DN      $ssl_client_s_dn;
                #proxy_set_header    X-SSL-Subject    $ssl_client_s_dn;
                #proxy_set_header    X-SSL-Issuer     $ssl_client_i_dn;

                proxy_redirect off;

                proxy_pass http://127.0.0.1:8080;
        }

    #listen 8080;
    listen 443 ssl; # managed by Certbot
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my_site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my_site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload;";

}

server {
    if ($host = www.my_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = my_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80 default_server;
        listen [::]:80 default_server;

        server_name my_site.com www.my_site.com;
    return 404; # managed by Certbot

}

upstream app_nodejs {
    server 127.0.0.1:3000;
  }

upstream web_nodejs {
    server 127.0.0.1:8080;
  }

A: The problem is that your nginx server is not listening on port 3000. It is only listening on port 443 (https standard port). It is also listening on port 80 (http standard port), but only to redirect to 443.
What you need to do is use a reverse proxy for the api requests from port 443 to port 3000 and the web resource requests to port 8080.
In order to do this, you need a way to distinguish between the API requests and the web requests and create a different location block for each. The typical way to do this is by comparing parts of the url path. For example, you can change your app so that all API request paths look something like:
/api/v1/customers

You can create a location block specifically for API requests like this:
location /api/v1 {
  ...
  proxy_pass http://127.0.0.1:3000;
}

And you keep your other location block in tact. The contents of the new location block should be roughly the same as the original except for the proxy_pass.
If you don't want to change your application, you could enumerate all of your request paths using a regex in a single location block, but this really isn't scalable. It would look like this:
location ~ ^/{customer|item|group}.*$ {
  ...
  proxy_pass http://127.0.0.1:3000;
}


text:
Q: How can I create a two-way binding with a value stored using Core Data? I am getting the following error when I try to bind to a nested property of an observed object from Core Data: Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'
Below is a simplified overview:
Parent.swift
@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
    animation: .default)
private var items: FetchedResults<Item>

var body: some View {
    NavigationView {
        List {
            ForEach(items) { item in
                Cell(showing: item)
            }
// ...

Cell.swift
struct Cell: View {
    @ObservedObject var item: Item

    init(showing: Item) {
        self.item = showing
    }

    var body: some View {
        TextField("Name", text: $item.name) // <-- error shows for this line
// ...

Why does this show an error? How can I create a two-way binding on this textfield with a value stored using Core Data?

A: It is there, in the error - TextField requires String binding, and item.name is String? (optional) binding. You can bypass it by making custom binding. Something like this:
TextField("", text: Binding(get: { item.name }, set: { newValue in item.name = newValue }))


text:
Q: Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died I tried to execute this Selenium Script,
public class FirePath_Ex {

    public static void main(String[] args)
    {// TODO Auto-generated method stub
        WebDriver d=new FirefoxDriver();
        d.get("https://facebook.com");
        d.findElement(By.xpath(".//*[@id='email']")).sendKeys("dhhfdssd");
        d.findElement(By.id("pass")).sendKeys("sjfsdfj");
    }
}

it shows the error below after closing FireFox,

Exception in thread "main"
  org.openqa.selenium.remote.UnreachableBrowserException: Error
  communicating with the remote browser. It may have died.
      Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 02:56:46'
      System info: host: 'Admin-PC', ip: '192.168.0.101', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version:
  '1.7.0-ea'
      Driver info: driver.version: RemoteWebDriver
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:589)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:445)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:358)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)
        at FirePath_Ex.main(FirePath_Ex.java:13)
      Caused by: org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 [/127.0.0.1] failed: Connection refused: connect

How do I resolve this?

A: Try to add this below code and replace the path of firefox exe with your absolute path:-
System.setProperty("webdriver.firefox.bin", "C:\\firefox.exe");

So your code should be like:-
public class FirePath_Ex {
public static void main(String[] args)
{// TODO Auto-generated method stub
    System.setProperty("webdriver.firefox.bin", "C:\\firefox.exe");
    WebDriver d=new FirefoxDriver();
    d.get("https://facebook.com");
    d.findElement(By.xpath(".//*[@id='email']")).sendKeys("dhhfdssd");
    d.findElement(By.id("pass")).sendKeys("sjfsdfj");
}
}

Hope it will help you :)

A: This was driving me crazy for quite a bit.
For me, simply re-instantiating it solved the problem some of the time. (like below). However, 95% of the time it's because my selenium version is not compatible with the firefox version. The documentation for supported version is not easy to parse, nor does it contain an exhaustive list. Sometimes it takes some trail and error.
public FirefoxWebPageReader firefoxWebPageReader() {
    return forceInit(3);
}

private FirefoxWebPageReader forceInit(final int tries) {
    if (tries == 0) {
        throw new RuntimeException("Can not initialize Firefox reader");
    }
    try {
        final String binaryPath = environment.getProperty("crawler.firefox.path");
        return new FirefoxWebPageReader(binaryPath);

    } catch (WebDriverException e) {
        LOGGER.error("Error occurred when building FirefoxWebPageReader, tries left: " + (tries - 1), e);
        return forceInit(tries - 1);
    }
}

A: The probable reason may be the incompatibility between the browser and the chromedriver, so installing the updated chromedriver or updating chrome might help


text:
Q: Matplotlib Axes Object, Get Data for Colorbar I have a function that does some plotting and returns an axes object:
def custom_plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()

    ax.scatter(x, y)

    return ax

ax = custom_plot(range(10), range(10))

colorbar(ax)

The last line will throw an error (as it should).  ax.get_children() returns  list of the line objects, so not suitable to pass to the colorbar.  Is it possible to access the scatter object via the axes or is it necessary to also return the scatter, e.g. s = plot.scatter(x,y,);return ax, scatter.
Similar, but not an answer:

*

*Getting data from matplotlib axes object

A: Sorry, misunderstood the question. From the source the scatter function only seems to return a path collection and not add it in any way that I noticed it to the axes class.
Depending on the conditions of your plot the easiest way to achieve that is just to replicate your plot into the colorbar instruction:
import matplotlib.pyplot as plt

def custom_plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()

    ax.scatter(x, y, c = x)

    return ax

x,y = range(10), range(10)
ax = custom_plot(x,y)
plt.colorbar(ax.scatter(x, y, c = x))
plt.show()

Effectively you are reproducing the plot from the axes without a shortcut variable. It's not, however, an ideal solution to your problem.
NOTE: I'll leave this post here just in case it might help you. If not tell me and I'll delete it.
ORIGINAL POST:
You can create a variable for the scatter plot itself and use that as argument. That being said you also should provide a map variable for the color. The following example adapted from your code:
import matplotlib.pyplot as plt

def custom_plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()

    axp = ax.scatter(x, y, c = x) # You have to give a map variable for the colorbar.

    return ax,axp # also return the plot itself

ax,axp = custom_plot(range(10), range(10))

plt.colorbar(axp) # give the plot as argument to colorbar
plt.show()

, results in this:


text:
Q: How to export proxy in Redhat Linux 7 using the current login credentials? I need to export proxy on RHEL 7 with the current logged user credentials.
I am able to achieve this by adding manually in .bashrc or .bash_profile.:
export http_proxy=http://username:password@proxy.example.com:6080
export https_proxy=http://username:password@proxy.example.com:6080

The above method works fine. But I don't want this method, since we are hard-coding the username and password and also it's not secure.
Is it possible to use the existing /etc/shadow file as password for exporting the proxy?

A: You could place something like the following as a script in /etc/profile.d/ directory:
#!/bin/bash
    if [ $SHLVL = 1 ]; then
    echo -n "Enter proxy password:"
    read -sr mypass
    export http_proxy="http://$USER:$mypass@proxy.example.com:6080"
    export https_proxy=$http_proxy
    echo
fi

if [ $SHLVL = 1 ] will prevent the script from running when spawning subshells such as when starting script for logging.
read -s will prevent echoing input as password is typed.
$USER is an environment variable that is the current username.
The final echo just prints a newline to get the next prompt on the next line.

A: The real problem is requiring username/password authentication when connecting to the proxty. One way or another, you will need to set the username and password somewhere when connecting to the proxy.
There is a reason why the proxy PAC configuration file format does not include password authentication.
Set the password within application
Instead of setting the proxy URL in the bash environment, you need to define the proxy URL on a per application basis. For example, for installing Redhat packages, you can define the proxy in /etc/yum.conf or any of the /etc/yum.repos.d/*.repo files.
Likewise for web browsers, set the proxy URL within the browser's settings.
Proxy chaining
Run a local proxy that does not accept password, but when it connects to the actual, upstream proxy, you can define the username and password.
Use a tool such as proxy-login-automator


text:
Q: Is this possible convert a Codeigniter project into phone gap? Currently I'm using codeigniter4 How can I integrate? please define briefly I'm a fresher.

A: No this is not possible. PhoneGap is HTML and Javascript based. Your PHP code won't run.
Even if you would have a HTML/JS project only you wouldn't be able to use it 1-on-1. You would have to implement PhoneGap hooks etc. to make it run properly.


text:
Q: Get dynamic model properties list for Razor template I'm looking into the RazorEngine for an e-mail templating system.
The system wil have lots of different e-mail templates so I don't want to create a typed model for each and every template.
Is it somehow possible to use a dynamic model and to retrieve a list of all the properties the dynamic model should have?
For example:
View/template
@model dynamic

Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum @Model.Customer Lorem ipsum Lorem ipsum
Lorem ipsum Lorem ipsum Lorem ipsum @Model.Product Lorem ipsum Lorem ipsum Lorem ipsum

From that View/template I want to be able to retrieve the following list (before calling Razor.Parse):
Customer
Product
With that list I will able to create my dynamic model (containing Customer en Product properties) that can be used in the call to Razor.Parse.
Is this possible and if so how do I do this? Are there alternatives?
Thanks for your time!

A: If you know enough about the model to know that it has a Customer and a Product than you should probably use a base class that all your email items inherit:
public class EmailItem
{
    public string Customer {get;set;}
    public string Product {get;set;}
}

And then use that as your model.
Then the item you pass in can be like so:
public class Sale: EmailItem
{
    // inherits EmailItem properties...
}


text:
Q: How to pass variables from controller to layout (not view) in Zend 3 I'm using zend MVC 3.1.1 and trying to pass variables from the called controller action to the layout but having real difficulties finding a way to do so. I haven't found a solution online for this problem.
Here is my base controller 'render' method that gets called to create the view model.
    protected function render ( array $data = array () ) {
        $controller = '';
        $action = '';

        $controller = strtolower( preg_replace( "/^(.*)\\\/", "", $controller ) );

        $data[ 'controller' ] = $controller;
        $data[ 'action' ] = $action;

        $viewModel = new ViewModel( $data );

        $viewModel->setTemplate( $controller . "/{$action}.php" );

        return $viewModel;
    }

And here is a snipped of my layout.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title><!-- I WANT TO PUT VARIABLE HERE --></title>
    </head>
    <body>
            <?=$this->content?>
    </body>
</html>

How can I pass a variable from the controller 'render' action, or anywhere else in the execution, and have access to it in the same way I do to '$this->content'?
Thank you.

A: Try
....
$viewModel = new ViewModel();

$viewModel->setVariables(
   [
      'controller' => $controller,
      'action' => $action,
   ]
);

$viewModel->setTemplate( $controller . "/{$action}.php" );

return $viewModel;
...

You can find setVariables() method description inside vendor/zendframework/zend-view/src/Model/ViewModel.php

A: In Zend 1.x you can set variable in controller like this
$this->view->layout()->isFlag = true;

and then catch it in layout
var_dump($this->layout()->isFlag);  // true


text:
Q: Pip install hiredis fails on building wheels I upgraded my python to version 3.10, but when I was installing dependencies for one of my projects (which worked fine before), I got this error from hiredis (hiredis==2.0.0):
 ERROR: Command errored out with exit status 1:
   command: /home/sajad/com/nilva/codebase/nilmal/nilmal-django-backend/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pp4tya0l/hiredis_77cc0a3cc0244a81bdc153910e791620/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pp4tya0l/hiredis_77cc0a3cc0244a81bdc153910e791620/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-11hzakag
       cwd: /tmp/pip-install-pp4tya0l/hiredis_77cc0a3cc0244a81bdc153910e791620/
  Complete output (27 lines):
  /tmp/pip-install-pp4tya0l/hiredis_77cc0a3cc0244a81bdc153910e791620/setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
    import sys, imp, os, glob, io
  /home/sajad/com/nilva/codebase/nilmal/nilmal-django-backend/venv/lib/python3.10/site-packages/setuptools/dist.py:691: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead
    warnings.warn(
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-x86_64-3.10
  creating build/lib.linux-x86_64-3.10/hiredis
  copying hiredis/__init__.py -> build/lib.linux-x86_64-3.10/hiredis
  copying hiredis/version.py -> build/lib.linux-x86_64-3.10/hiredis
  copying hiredis/hiredis.pyi -> build/lib.linux-x86_64-3.10/hiredis
  copying hiredis/py.typed -> build/lib.linux-x86_64-3.10/hiredis
  running build_ext
  building 'hiredis.hiredis' extension
  creating build/temp.linux-x86_64-3.10
  creating build/temp.linux-x86_64-3.10/src
  creating build/temp.linux-x86_64-3.10/vendor
  creating build/temp.linux-x86_64-3.10/vendor/hiredis
  x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Ivendor -I/home/sajad/com/nilva/codebase/nilmal/nilmal-django-backend/venv/include -I/usr/include/python3.10 -c src/hiredis.c -o build/temp.linux-x86_64-3.10/src/hiredis.o
  In file included from src/hiredis.c:1:
  src/hiredis.h:4:10: fatal error: Python.h: No such file or directory
      4 | #include <Python.h>
        |          ^~~~~~~~~~
  compilation terminated.
  error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
  ----------------------------------------
  ERROR: Failed building wheel for hiredis

I'm not sure what the problem is, could anyone help?

A: if your version of python is 3.9 :
py -3.9 -m pip install --upgrade pip

py -3.9 -m pip install hiredis

that work for me if doesnt work try :
py -3.9 -m pip uninstall hiredis


text:
Q: Better optimization I am writing a piece of code that compiles fine but is kind of sloppy and can be optimized. Is there a better or easier way to do this. Also am I using the compareTo() method in the correct way? I am trying to use different ways to make the code cleaner and faster than the example below.
import java.util.ArrayList;

public class Sort {

    public ArrayList<Name> sort(ArrayList<Name> names) {

        ArrayList<Name> results;
        results = new ArrayList<Name>();

        do {
            Name firstName = new Name("zzz", "zzz");
            for (int i = 0; i < names.size(); i++)
                if (names.get(i).getFirstName()
                        .compareTo(firstName.getFirstName()) < 0
                        || names.get(i).getFirstName() == firstName
                                .getFirstName() && names.get(i).getSurName()
                                .compareTo(firstName.getSurName()) < 0)
                firstName = new Name(names.get(i).getFirstName(),
                                names.get(i).getSurName());

            results.add(firstName);
            names.remove(firstName);
        } while (names.size() > 0);

        return results;
    }

}

class Name {
    private String firstName;
    private String surName;

    public Name() {
    }

    public Name(String firstName, String surName) {
        this.firstName = firstName;
        this.surName = surName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSurName() {
        return surName;
    }

    public void setSurName(String surName) {
        this.surName = surName;
    }

    public String toString() {
        return firstName + " " + surName;
    }

    public boolean equals(Object other) {
        return firstName == ((Name) other).firstName
                && surName == ((Name) other).surName;
    }

}

A:

Is there a better or easier way to do this. Also am I using the compareTo() method in the correct way?

Yes couple of issues:

*

*Comparing string should use equals method and not == like firstName == ((Name) other).firstName

*From the looks of it you are trying to sort names list. You are doing it probably with O(N^2) time. With JDK's sort, you could do the same in O(NlogN) time and hence making it worse than what you have currently.

So instead define your own comparator and use it like:
Collections.sort(names, new MyNamesComparator());

A: If you want efficiency I suggest you use the built in sort which O(N * log N)
// in Java 7
Arrays.sort(names, new Comparator<Name, Name>()) {
     public int compare(Name n1, Name n2) {
         int cmp = n1.firstName.compareTo(n2.firstName);
         if (cmp == 0)
             cmp = n1.lastName.compareTo(n2.lastName);
     }
});

// in Java 8
names = names.stream()
             .sorted(Comparator.comparing(Name::getFirstName)
                              .andThen(Name::getLastName))
             .collect(Collectors.toList());


text:
Q: How to fix duplicate symbols in xCode 4.5.2? Reading the previous posts on StackOverflow on this topic I could not find the right solution.
I'm compiling my project and I get lots of duplicate symbol errors like:
duplicate symbol _OBJC_METACLASS_$_XMPPXFacebookPlatformAuthentication in:
    /Users/mirzahat/Library/Developer/Xcode/DerivedData/Chattar-ajtakwrcojkkiehegfaxjkhesaej/Build/Intermediates/Chattar.build/Debug-iphonesimulator/ChatProject.build/Objects-normal/i386/XMPPXFacebookPlatformAuthentication.o
    /Users/mirzahat/Desktop/Apps/Externals/Quickblox.framework/Quickblox(XMPPXFacebookPlatformAuthentication.o)

I found the DerivedData folder of the project where the linker is stopping and I delete the folder. However it gets created every time I compile the project in simulator.
Any suggestions?


text:
Q: AndEngine Drop shadow for sprite I use AndEngine, And I need to drop shadow for sprite.
In sprite I use png texture. Can I draw shadow in code, or need draw it on Photoshop and impose under sprite?

A: If you really (!) need to create shadows dynamically then you could do something like this:
(removed)
Update
An easier way came into my mind:

*

*Create a RenderTexture.

*Render your Sprite to the RenderTexture several times with different scales and alpha values. i.e. scale=1, alpha=1 / scale=1.1, alpha=0.9 / scale=1.2, alpha=0.8 etc. Use as small steps as possible to achieve a smooth gradient.

*Create a Sprite using your RenderTexture and set its color to black (Color.Black).

*There you have your dynamic shadow ;)

A: You have to create shadow as PNG file, attach it to your sprite and make it visible when needed. Can't create shadows dinamically in andEngine.


text:
Q: nmcli Error: Connection activation failed: Not authorized to control networking I wrote a combination .sh and .exp scripts that:

*

*activate vpn connection

*connect to remote server

*download some files from server

*deactivate vpn connection

This scripts should run on schedule.
I use nmcli for activate and deactivate connections.
If I run scripts manually it work correctly, but if I run this scripts via cron, I receive message (about vpn conn activation): Error: Connection activation failed: Not authorized to control networking.
In logs I see that the script is run from under me:
Dec  6 18:48:01 maskalev-Aspire-A514-54 CRON[10975]: (maskalev) CMD (./dev/promomed/__DRAFTS__/utils/sftp_monitor/main.sh)

my groups:
maskalev@maskalev-Aspire-A514-54:~$ groups
maskalev root adm cdrom sudo dip plugdev netdev lpadmin lxd sambashare docker

nmcli permissions
maskalev@maskalev-Aspire-A514-54:~$ nmcli general permissions
PERMISSION                                                        VALUE
org.freedesktop.NetworkManager.checkpoint-rollback                auth
org.freedesktop.NetworkManager.enable-disable-connectivity-check  yes
org.freedesktop.NetworkManager.enable-disable-network             yes
org.freedesktop.NetworkManager.enable-disable-statistics          yes
org.freedesktop.NetworkManager.enable-disable-wifi                yes
org.freedesktop.NetworkManager.enable-disable-wimax               yes
org.freedesktop.NetworkManager.enable-disable-wwan                yes
org.freedesktop.NetworkManager.network-control                    yes
org.freedesktop.NetworkManager.reload                             auth
org.freedesktop.NetworkManager.settings.modify.global-dns         auth
org.freedesktop.NetworkManager.settings.modify.hostname           auth
org.freedesktop.NetworkManager.settings.modify.own                yes
org.freedesktop.NetworkManager.settings.modify.system             yes
org.freedesktop.NetworkManager.sleep-wake                         no
org.freedesktop.NetworkManager.wifi.scan                          yes
org.freedesktop.NetworkManager.wifi.share.open                    yes
org.freedesktop.NetworkManager.wifi.share.protected               yes

I think I'm interested enable-disable-network, amn't?
Have you any ideas?
May be I can solve this problem (mainly activate vpn) by other way?
OS -- Ubuntu 22.04


text:
Q: mysql join 3 tables and display result with WHERE payment = PENDING i have 3 tables
abd_table
  product_name
  price
  quantity
  total_cost
  session_id
  date

order_detail_table
  order_id
  product_name
  price
  quantity
  total_cost
  session_id
  order_date

order_table
  order_id
  payment_status (PAID,PENDING)
  order_date
  session_id

I want to retreive rows
1) WHERE same PRODUCT DETAILS dont exists or match in abd_table and order_detail_table from same session
2) WHERE nw.payment_status = PENDING
If i remove WHERE CONDITION from below query then it dispaly all rows whether the payment_status is pending or not.
if i insert WHERE CONDITION in the below query then it display nothing.
$qry="select
a.cart_id,a.date,a.quantity,a.total_cost,a.user_name,a.product_name,a.session_id,a.price,o.order_id,nw.payment_status,nw.session_id
from abd_table AS a
LEFT JOIN order_detail_table as o on a.session_id=o.session_id
LEFT JOIN order_table as nw on o.session_id = nw.session_id
where nw.payment_status = 'PENDING'";

so how to retreive rows
1) WHERE same PRODUCT DETAILS dont exists or match in abd_table and order_detail_table from same session.
2) WHERE nw.payment_status = PENDING
vineet


text:
Q: Laravel Lumen function env() returns null sometimes I am developing api with Lumen 6.2.0 which gets GET request with certain parameters and token. When it gets parameters it process it in a certain way and then encode with a secret key which is in my .env file and then compares result with the token which was provided with the request, if comparison result is true then user is authenticated else he is not. So the problem is sometimes env() function returns null. It doesn't happen pretty often, just like 1 request out of 15, but it's still a serious problem for me.
I googled a lot but found just few approaches. Firstly I found out that env() function should be only invoked in config file and since Lumen doesn't have a config directory and config files I have created it, but the issue remains the same. The second advice was for Laravel specifically - php artisan config:clear and php artisan config:cache but Lumen doesn't have such commands, although I ran the php artisan cache:clear command to no avail. So here is my code:
.env file
APP_NAME=Example
APP_ENV=local
APP_KEY=ApPkEyHeRe
APP_DEBUG=true
APP_URL=https://example.com
APP_TIMEZONE=UTC

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpass

CACHE_DRIVER=file
QUEUE_CONNECTION=sync

VK_APP_SECRET=SoMeFaNcYkEy

config/config.php
<?php

return [
    'vk_app_secret' => env('VK_APP_SECRET'),
    'events_per_page' => 16
];

And UsersController.php
<?php

namespace App\Http\Controllers;

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

class UsersController extends Controller
{
    public function check(Request $request) {
        $query_params = $request->all();

        $sign_params = [];
        foreach ($query_params as $name => $value) {
          if (strpos($name, 'vk_') !== 0) {
            continue;
          }
          $sign_params[$name] = $value;
        }

        ksort($sign_params);
        $sign_params_query = http_build_query($sign_params);
        $secret = config('config.vk_app_secret');
        $hash_hmac = hash_hmac('sha256', $sign_params_query, $secret, true);
        $base_encode = base64_encode($hash_hmac);
        $trim_chars = strtr($base_encode, '+/', '-_');
        $sign = rtrim($trim_chars, '=');
        $status = $sign === $query_params['sign'];

        return json_encode($status);
    }
}

I also logged every line of this algorithm, and noticed an interesting thing, the failing case contains [date] production.INFO: prefix before log's rows, and every successful case [date] local.INFO: So maybe it's affecting env() function somehow? I also don't get it why it sometimes logged as production when I have APP_ENV=local


text:
Q: Populating ListView with NavigationParameters? In my Xamarin Forms application, I have a ListView with different cells, using DataTemplates and DataTemplateSelectors. For one type of cell, it has a button on it, which when tapped, navigates to another page  which contains just a ListView which is made up of only strings.
My problem arises from the OnNavigatedTo method being called after the page has loaded, and therefore the list that I am passing to this new 'ListView only' page, updates the value that I bind the ListView to after the ListView is created and populated, but it is populated with nothing because the data comes from the previous page via the OnNavigatedTo method.
public class ListPageViewModel : _ViewModelBase
{
    private INavigationService _navigationService;

    public ListPageViewModel(INavigationService navigationService)
    {
        _navigationService = navigationService;
        _strings = new List<string>()
        {
            "Jaguar", "Elephant", "Nemo", "Cat", "Dog", "Iguana", "Puma", "Crow", "Hawk", "Owl", "Badger", "Meerket",
            "Shark", "Whale", "Monkey", "Snake", "Lion", "Zebra", "Hippo", "Squirrel", "Rhino", "Bear", "Moose",
            "Camel", "Chicken", "Cow", "Sheep", "Turkey", "Jellyfish", "Salmon", "Parrot", "Wolf", "Gecko"
            // Placeholder before we have lists of customers
        };
    }

    private IEnumerable<string> _strings;
    public IEnumerable<string> Strings { get { return _strings; } set { SetProperty(ref _strings, value); } }

    public override void OnNavigatedTo(NavigationParameters parameters)
    {
        base.OnNavigatedTo(parameters);

        if (parameters.ContainsKey("dataList"))
        {
            _strings = (List<string>)parameters["dataList"];
        }
    }
}

So when I navigate to this page, the _strings list is first populated with the list of animals, and then the page loads showing all the animals in the ListView, and then after the ListView has loaded it changes the value of the _strings list to be the same as the list passed along with the NavigationParameters. So how do I make the ListView update every time the _strings list is changed or updated?

A: Either
Strings = (List<string>)parameters["dataList"];

or use an ObservableCollection


text:
Q: How can one search for some text which is not part of a url? Suppose the text to search is pqr.
"http://abc.zzz/pqr/xyz"      -> Should not match
"/pqr/"                       -> Should Match
"pqr"                         -> Should Match
"http://abc.zzz/pqr/pqr/"     -> Should not match
"http://abc.zzz/pqr/pqr/ pqr" -> Should match the last "pqr"
"www.pqr.zzz"                 -> Should not match

I tried using the following regex,
((?:(?:(?:https?|ftp|file|mailto):)|www)[^ ]+?)?(pqr)

I then looked for group 1, if it is empty then I was considering it as a match. But this fails for http://abc.zzz/pqr/pqr/
Any help here in detecting if the text to match is not part of a url?
The worst case I think is to detect all the urls first and then store the start and end indexes of the matched urls. Then try to match pqr and exclude all those which are part of the url. I was thinking if there is something that can be done better.

A: Taking into account you are using Java, you can leverage the constrained-width lookbehind that Java regex engine supports. It means you can use {n,m} limiting quantifier in the pattern. Right now, Java 8 supports even * and + quantifiers inside a lookbehind (although unofficially), but this is a bug and is likely to be fixed in the next version. Thus, you may use some range, say 0 to 1000 (as the link is not likely to contain more than 1K symbols, but you may adjust it to the factual situation):
 (?<!(?:(?:https?|ftp|file)://|mailto:)(?:www\.)?\S{0,1000})(?<!\bwww\.\S{0,1000})pqr

See the regex demo
The first lookbehind (?<!(?:(?:https?|ftp|file)://|mailto:)(?:www\.)?\S{0,1000}) will check if the pqr is not preceded with a full URL, and (?<!\bwww\.\S{0,1000}) lookbehind will check if the pqr is not preceded with www..


text:
Q: Error 415 on angular although the headers are up I'm getting error 415 on angular api request but http header are set:
login.service.ts:
var httpHeaders = new HttpHeaders();
httpHeaders.set('Content-Type', 'application/json');
httpHeaders.set('Access-Control-Allow-Origin', '*');
return this.httpClient.post<any>(requestUrl, params, { headers: httpHeaders })

As backend i used django rest framework
Any idea ?
Thans in advance.

A: HttpHeaders class is immutable in Angular so now you did not really set any headers. You need to assign the result of set operation to you variable.
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.set('Content-Type', 'application/json');
// depending on the server settings might also be needed
httpHeaders = httpHeaders.set('Accept', 'application/json');
httpHeaders = httpHeaders.set('Access-Control-Allow-Origin', '*');
return this.httpClient.post<any>(requestUrl, params, { headers: httpHeaders })


text:
Q: BUILD FAILED Netbeans 7.4 C / C++ I am trying to fix my Netbeans IDE to compile C / C++ programs, but I get the following error:
"/D/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/Users/MOTIVECODEX/Documents/NetBeansProjects/make'
"/D/MinGW/msys/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW_TDM-Windows/make.exe
make.exe[2]: Entering directory `/c/Users/MOTIVECODEX/Documents/NetBeansProjects/make'
mkdir -p build/Debug/MinGW_TDM-Windows
make.exe[2]: mkdir: Command not found
make.exe[2]: *** [build/Debug/MinGW_TDM-Windows/main.o] Error 127
make.exe[2]: Leaving directory `/c/Users/MOTIVECODEX/Documents/NetBeansProjects/make'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/c/Users/MOTIVECODEX/Documents/NetBeansProjects/make'
make.exe": *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 1s)

I have added these to my windows user variables path and also system variables path:
D:\MinGW\bin; D:\MinGW\msys\1.0\bin; D:\MinGW\mingw32\bin;

But still getting this error.
I am using MinGW with MSYS with Netbeans IDE 7.4. Windows 7 64 bit.
I have reïnstalled both MinGW MSYS and Netbeans IDE 7.4. NetBeans IDE 7.4 has C / C++ installed.
Paths in Netbeans:

I know this is a duplicate, but those "solutions" did not work, so
  spare me the trouble of marking this as duplicate.

A: Solution to my problem: Remove MinGW and ALL of it's components, and also remove the folder x:\MinGW. Then install Cygwin, choose the packages you need, tutorial can be found on https://netbeans.org/community/releases/73/cpp-setup-instructions.html#cygwin or YouTube about which packages you need. Then add x:\cygwin to your system path, in my case D:\cygwin64 and reopen Netbeans, go to tools -> options -> C/C++ and click on Restore Defaults. It changed everything to cygwin, in my case cygwin64, and I can build now without errors.

A: I am making this post about a problem that I encounter when I made a clean and build on a C language program. There was a post about the same problem for a C++ program pointing towards a problem with the main function. This post and the message from the clean and build lead me toward a solution.
When you create a new project:
Categories: C/C++
Projects: C/C++ Application
After you click on Next you should uncheck the Create Main File box before proceeding. You should not have any problems afterward.


text:
Q: unexpected end of while when zlib.gunzipping very large file from s3 bucket I'm loading a very large file from an AWS s3 bucket, creating a readStream out of it, gunzipping it, and then passing it through Papa.parse. When I say "very large file", I mean it's 245 MB gzipped, and 1.1 GB unzipped. Doing this with smaller files has always worked flawlessly, but with this excessively large file, it sometimes succeeds, but most often failed.
When it fails, zlib.createGunzip() throws an "end of file" error. (Apparently something it likes to do; I'm finding lots of references to this everywhere, but nothing that fits my case.)
Clearly it can succeed. Sometimes it does. I don't know what causes it to fail. Random memory shortage? Buffering where gunzip wants to read faster than the file can be loaded? I have no idea.
const file = await readS3File(s3options);

return new Promise(((resolve, reject) => {
    Papa.parse(file.createReadStream().pipe(zlib.createGunzip()), { ...papaParseOptions });

I'm looking for a way to increase my chances of success. Is there a good way to do that? Some way to pipe this through a buffer that will retry loading the file while appeasing gunzip somehow? Am I looking in the wrong direction?


text:
Q: Loop through text and extract pre-defined words and word pairs in Rails I have a large string of text description, up to 500 words long. I would like to do the following:

*

*Loop through description and look for a large number of pre-defined words from array keywords, which contains single words, word pairs and word triplets.

*Every time a match is found, add this match to a new array matches (unless already added earlier in the process) and remove the matched word(s) from description.

I've had a look around for solutions, but most of them seem to either dive in at the deep end of natural language processing, which would be too complex for my current needs, or simply split the text string on spaces which means that it's then impossible to look for word pairs.
Would greatly appreciate any ideas as to how to do this efficiently.

A: description = "The quick brown fox jumped over the lazy dog, and another brown dog"

keywords = ["brown", "lazy", "apple"]

matches = []

keywords.each do |keyword|
  matches << description.match(keyword).to_s if description.match(keyword)
end

puts matches
 #=> ["brown", "lazy"]

matches.each do |keyword|
  description.gsub!(Regexp.new(keyword), '')
end

description.gsub!('  ', ' ')

puts description
 #=> "The quick fox jumped over the dog, and another dog"

A: You can set the Threshold frequency for each word in array
Loop through the text in Description
If word matches exactly with description text then increase the threshold frequency by 1 point

At the end, words who's frequency grater than 0 put it in to new array matches and delete it from description
For Example,
If any word repeated for 2 times,
It's frequency will be 0 + 2 and
Initially it should be 0.

A: This is the crude hack that occurred to me :)
keywords.select do |keyword|
  description =~ /\b#{Regexp.escape(keyword)}\b/
  # -or-
  description.gsub(/\b#{Regexp.escape(keyword)}\b/) do |match|
    # whatever
  end
end


text:
Q: React Form Input to Backend Job - Allow User to Navigate Away and Update State When Job is Complete I currently have a React App that is using Axios to post data to a Python backend. The jobs are heavy and could take anywhere from 30 seconds to 5 minutes.
Currently, the application sits there loading until the job is done. If you navigate away from the page, while the backend process finishes, the frontend process no longer catches the response due to leaving the page.
I'd like to set it up so that the job continues to run, the user can navigate away from the page and do other things on the app. Then, when the job is complete, it updates the state (which prompts a notification to appear that the file is ready).
Does anyone know how to do this? Can maybe point me in the direction of some documentation that goes over this type of functionality?
Appreciate the help!


text:
Q: how to create an intent to stop / pause / reset the Clock Timer not the scheduler? I would like to reset/ pause / resume the clock timer which is in the AlarmClock using an intent (mainly would be from another device).
the following code outlines my activity to launch the timer with a predefined value. My question is how to reset/ pause / resume that timer from the same activity.
public class MainActivity extends Activity {

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

    // launch the timer with a predefined value
    Intent startTimer=new Intent(AlarmClock.ACTION_SET_TIMER);
    startTimer.putExtra(AlarmClock.EXTRA_LENGTH, 300);
    startTimer.putExtra(AlarmClock.EXTRA_SKIP_UI, false);
    startTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startTimer);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}


text:
Q: Android: Download file from password protected website I need to download some pdf files from a site where users have to login before they can download any files.
If a user is not logged into the site, links to pdf files will redirect to the login page.
I managed to post user credentials to the login page and save the cookie from the response and I tried providing that cookie to the URLConnection when attempting download, but I am still getting the login page instead of my pdf file.
UPDATE: code added.
Posting user credentials:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write("username=" + username + "&password=" + password);
writer.flush();
writer.close();
os.close();

String result = HttpUtils.getResponseString(conn);
if (result.indexOf("Invalid") == -1) {
    String cookie = conn.getHeaderField("set-cookie");
    return cookie;
}

cookie is then stored and used in the following code segment
Attempting to download the pdf :
URLConnection conn = url.openConnection();
conn.setRequestProperty("Cookie", _cookie);
conn.connect();
InputStream inStream = new BufferedInputStream(url.openStream(), 1024);
OutputStream outStream = new FileOutputStream(_pdfFile);
byte buffer[] = new byte[1024];
int count = 0;
while ((count = inStream.read(buffer)) != -1)
    outStream.write(buffer, 0, count);
outStream.flush();
outStream.close();
inStream.close();


text:
Q: Angular - Como enviar um objeto dentro de um model em um método POST? Boa tarde, estou tendo um problema para enviar um POST para uma API publicada por conta de um dos parâmetros esperados ser um objeto, de maneira que o json esperado está da seguinte forma :
{"Cargo": string,
 "idFuncionario": 0,
 "idCadastro": 0,
  "cadastro": {
                "idCadastro": 0,
                "nome": "string",
                 "razao": "string",
                  "documento": "string"
              }

"dtAtualizacao": "2019-02-22T17:32:38.049Z",
}

o único valor que chega nulo na API é o do objeto "cadastro", tentei de diversas formas enviá-lo, sem êxito, uma vez que estou iniciando no angular agora, qualquer ajuda seria de extremo proveito, o método post em service está da seguinte maneira:
    postFuncionario(funcionario : Funcionario){

      try {
          var body = JSON.stringify(funcionario);
            var headerOptions = new Headers({'Content-Type':'application/json'});
            var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
            return this.http.post(this.localUrl+'Create'
            ,body,
            requestOptions).map(x => x.json());
        }

      catch (error) {
            return Observable.throw(error)
          }

    }

o método onSubmit , em componente:
 onSubmit(form:NgForm){

if (form.value.idFuncionario   == null) {
  this.service.postFuncionario(this.form.value)
    .subscribe(data => {
      this.toastr.success('Novo registro gravado com sucesso!', 'Funcionário Cadastrado')
      console.log(this.service.funcionario )
      console.log(this.form.value)
      console.log(form.value.idFuncionario)
      this.resetForm()
    })
}

exemplo do databinding no template:
      <input type="number" class="form-control" name="idFuncionario"  placeholder="ID Funcionário"
                 [(ngModel)]="service.funcionario.idFuncionario" value="{{service.funcionario?.idFuncionario}}">

      <input type="text" class="form-control" name="nome" placeholder="Nome" #nome="ngModel"
                [(ngModel)]="service.funcionario.cadastro.nome" value="{{service.funcionario?.cadastro.nome}}">

por fim, o model:
 import {Cadastro} from './cadastro.model'

 export class Funcionario {

 Cargo : string
 idFuncionario : number
 cadastro : Cadastro
 }

é isto, qualquer ajuda seria otimo!

A: no caso está faltando uma vírgula:
{"Cargo": string,
 "idFuncionario": 0,
 "idCadastro": 0,
  "cadastro": {
                "idCadastro": 0,
                "nome": "string",
                 "razao": "string",
                  "documento": "string"
              }
 aqui ,
"dtAtualizacao": "2019-02-22T17:32:38.049Z",
}


text:
Q: Finding an exact substring in a range of cells in Excel I'm looking for a way to find an exact string of text within a range of cells so I can count the number of occurrences of the substring.  By exact, I mean that if the range contains multiple occurrences of the values "apple" and "apples", and I want to count the number of occurrences of "apple", I don't want "apples" included.  I've tried this with COUNTIF and SUM(LEN/SUBSTITUTE) formulas, but they return counts for "apple" and "apples" since "apples" contains the string "apple".  Thoughts?

A: Try this little User Defined Function ( UDF )
Public Function FruitCounter(rIn As Range, s As String) As Long
    Dim r As Range
    Dim ary() As String
    For Each r In rIn
        ary = Split(Replace(r.Value, " ", ""), ",")
        For i = LBound(ary) To UBound(ary)
            If ary(i) = s Then
                FruitCounter = FruitCounter + 1
                GoTo ext1
            End If
        Next i
ext1:
    Next r
End Function

User Defined Functions (UDFs) are very easy to install and use:

*

*ALT-F11  brings up the VBE window

*ALT-I
ALT-M opens a fresh module

*paste the stuff in and close the VBE window

If you save the workbook, the UDF will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the UDF:

*

*bring up the VBE window as above

*clear the code out

*close the VBE window

To use the UDF from Excel:
=FruitCounter(A1:A10,"apple")

To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
and
http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx
for specifics on UDFs
Macros must be enabled for this to work!


text:
Q: 4 P-FET HBridge The other day I got a reel of 800 P MOSFETs, my workplace threw out, as the entire company is relocating. 800 are quite some, and I need to build me a couple of HBridges anyway, so "joy, oh joy!"
Unfortunately the joy did not last forever, since I cannot figure out how to make a HBridge with only four P MOSFETs and other discrete components.
I have made HBridges with 2xP + 2xN and with 4xN, but I get stuck with 4xP.
Therefore: Does anybody know of a HBridge design of only 4xP channel MOSFETs and other discrete components?

A: When all you have is a hammer, you try to consider all problems nails.  However, contorting all problems to the solution at hand is not always a good idea.
First, you need to understand the capabilities of the particular PFET you have.  Then you have to see if it is appropriate for some kind of usable H bridge.  If so, I'd probably use these PFETs for the high side switches only, and get other parts for the low side switches.  That means you'll only use 2 of your free PFETs per H bridge.  Oh well.
If you want a high current H bridge, you can parallel several of your free PFETs for the high side switches.  Again, link to the datasheet of these PFETs and tell us the requirements of whatever you want to drive with these H bridges.

A: Edit: Previous design was a fluke.  Voltages were too low and transistors didn't work properly.  As Dave Tweed has suggested, a negative voltage would be necessary for this to work properly.  Here is one such design.
You haven't stated whether negative voltages would be available to you, so this may or may not be impractical.
In this way, the transistors have minimal power loss, as you can see with 11.36V delivered to the load.  The upper PMOS has about 200mV across it, while the lower has about 400mV across it when they are on.


text:
Q: Evaluation (NSIntegers) inside if-statement Objective-C I am in doubt, why this work correctly:
NSInteger row = indexPath.row;
NSInteger preloadTrigger = self.nodes.count - 20;
if (row >= preloadTrigger) {
    [self.loader loadNextposts];
}

And this does not (just skips the if-statement):
if (indexPath.row >= self.nodes.count - 20) {
    [self.loader loadNextposts];
}

when the value of self.nodes.count - 20 is negative.
However, when the value of the expression is positive, it works fine always.
A very strange behavior, as I cannot see semantic difference in two expressions.
Update:
So, I decided to test it:
(lldb) po self.nodes.count - 20
18446744073709551601

(lldb) po preloadTrigger
-15

A: According to Apple Docs, count property is a NSUIntegerin objective-C.
When you write  :
 NSInteger preloadTrigger = self.nodes.count - 20;

In fact you are casting count to a NSInteger object, and can have a negative value if count isn't greater than 20.
But when you write :
(indexPath.row >= self.nodes.count - 20)

count is a NSUInteger object, and subtract 20 from it will always lead to a positive number (a huge one by the way).

A: Because nodes.count is NSUInteger and row is NSInteger. Unsigned integer - 20 is never a negative value, but results a huge positive value where you expect it to be negative.

A: I'll add some explanation to the other, correct answers.
So, here is how it goes:
self.nodes.count is of type NSUInteger, which is the same as unsigned long int in 64 bit systems, or alternatively unsigned int in 32 bit systems.
The literal 20 is of type int.
When you form the expression self.nodes.count - 20, 20 is 'promoted' to the unsigned integer type of the other operand (self.nodes.count), because it has the wider range of the two.
That is because, when both operands have types of different sizes, the smaller one gets promoted to the larger one to make them equal and calculate the result in those terms (in hardware, arithmetical operations between values of different types aren't really defined - the bit representations differ).
The problem is that, in exchange for being able to represent a wider range of positive values with the same bit length, unsigned integers can not represent negative values. So, when 20 is greater than self.nodes.count, the result "wraps around" to a large, unsigned integer.
On the other hand indexPath.row, too, is an unsigned integer (NSUInteger), so you end up comparing the relatively small row value with the huge result of the subtraction operation; the test:
if (indexPath.row >= self.nodes.count - 20)

...always fails (the left side is smaller).
If you first cast both results to signed integer and then compare those signed integers:
NSInteger row = indexPath.row;
NSInteger preloadTrigger = self.nodes.count - 20;
if (row >= preloadTrigger) {

...then no wrapping/underflow occurs and you get the expected result.


text:
Q: GTK focus-out-event I am showing a user a popup menu when they right click.
According to the popup behaviour, I want to destroy the popup when it looses focus(when user clicks outside the popup window). For that I tried to connect the popup window to "focus-out-event", using Glade. But for some reason, that event is not getting fired. I tried to print something on the terminal when the event is fired, but nothing gets printed.
I am new to Python and GTK, and now I have no clue how to proceed further.
#handler to catch the focus out event
def on_popup_menu_add_attachment_focus_out_event(self, *args):
    print("Destroying the popup.....")

focus-out-signal and its handler

A: I just changed the Type as Top Level and it worked!


text:
Q: Is it possible to have flexible decimal_places for a model in django? I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals.
For example:
This is the class
class Asset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0)
    share_cost = models.DecimalField(max_digits=18, decimal_places=0, default=0)

If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute."
Maybe what i am trying is not possíble, probably i need to find another solution. I am open to suggestions
I would like to know if is possíble to have this decimal places fleixible.

A: Not sure if it is feasible to achieve what you described using a single field.
Django maps model structure to the corresponding table in the database and the exact storage implementation there might vary depending on the database type you are using. That said shares_amount field type will remain constant and could be changed only through the migration.
https://docs.djangoproject.com/en/4.0/ref/models/fields/#decimalfield
As an alternative, you could think of using a slightly different approach on how to store information. For example, have two nullable fields and fill for each category type with correct validation depending on the type. Or have a single field with the maximum possible number of the decimal places and round them to the desired precision where it is required.

A: I found out a solution that worked for what i was wondering to achieve.
I chaged the field to a FloatField type, instead of DecimalField. Than i got more flexibilie on how many decimals, without restrictions:
shares_amount = models.FloatField()

As there where using some mathemathic operations, started to show this conflict error:
*unsupported operand type(s) for : 'float' and 'decimal.Decimal'
The solution was here on the forum:
unsupported operand type(s) for *: 'float' and 'Decimal'
So for the mathematics it was just do that:
decimal.Decimal(self.shares_amount) * self.share_cost


text:
Q: Getting a URL of a record from HP TRIM's Desktop Client Is it possible to copy the URL of a Record/Document from HP's TRIM and sent it to someone in order to download?

A: Before TRIM 7, whether you can do this natively depends on which TRIM features are installed.
To see if you have the right stuff, make a TR5 file on your desktop, and rightclick on it - "TryURL" - copy the URL
(the TryURL right click action requires TRIM client stuff - if you don't have that, try opening the TR5 file in notepad, and see if there is a hyperlink in there).
You do get this functionality with the SharePoint connector for TRIM (TIPS or TSCI)
Or there is a cheap third party product that looks cool - from Icognition Pty Ltd.

A: There are a few ways of going about doing something like this. Assuming you're sending the link to someone on the same WAN, or the security-risky option of having your TRIM system internet accessible, what I'd do is build a simple web service over the top of the TRIM SDK. The TRIM SDK is COM (with a PIA wrapper) or a proper .Net assembly (in version 7.*), so a simple ASP.Net service would be quite easy.
Below is the code for an ASP.Net service I built, based on a code sample provided by HP (based on the TRIMSDKPIA20.dll, not the TRIM 7.0 HP.HPTRIM.SDK assembly). You could use it as a basis to make something more RESTful, but as it is, you'd call it using a URL like:
http://server/ViewRecord/recno=D11-001
You could then create an "External Link", an Addin based again on the SDK that you can register as a Right-Click option in the TRIM interface. Something like "Send Download URL..." that fires up an email and generates the URL, but that's a bit more complicated.
Anyway, the code for the webservice:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TRIMSDK;
using System.Configuration;
using Microsoft.Win32;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string errormsg = string.Empty;

        //Response.Clear();
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Database trim = new Database();
        trim.SetAsWebService();
        trim.Id = ConfigurationSettings.AppSettings["dbid"];
        trim.WorkgroupServerName = ConfigurationSettings.AppSettings["wgserver"];
        trim.WorkgroupServerPort = Int32.Parse(ConfigurationSettings.AppSettings["wgport"]);
        trim.Connect();
        string recno = Request.QueryString["recno"];
        if (String.IsNullOrEmpty(recno))
        {
            errormsg = "No recno parameter was passed.";
        }
        else
        {
            Record rec = trim.GetRecord(recno);
            if (rec == null)
            {
                errormsg = string.Format("Could not find a record with number \"{0}\". Either it doesn't exist, or you don't have permission to view it.", recno);
            }
            else
            {
                if (!rec.IsElectronic)
                {
                    errormsg = string.Format("Record {0} does not have an electronic attachment", rec.Number);
                }
                else
                {
                    IStream s = rec.GetDocumentStream(null, false, null);

                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "filename=" + rec.SuggestedFileName);
                    Response.AddHeader("Content-Length", rec.DocumentSize.ToString());
                    Response.Buffer = false;
                    Response.ContentType = GetContentType(rec.Extension);

                    uint BufferSize = 10000;
                    uint DocumentLength = (uint)rec.DocumentSize;
                    byte[] buffer = new byte[BufferSize];
                    uint bytesread;
                    uint totalread = 0;

                    Stream outstream = Response.OutputStream;

                    while (totalread < DocumentLength)
                    {
                        s.RemoteRead(out buffer[0], 10000, out bytesread);
                        if (bytesread < 10000)
                        {
                            for (uint i = 0; i < bytesread; i++)
                            {
                                outstream.WriteByte(buffer[i]);
                            }
                        }
                        else
                        {
                            outstream.Write(buffer, 0, 10000);
                        }
                        totalread += bytesread;
                    }
                    outstream.Close();
                    Response.Flush();
                    return;
                }
            }
        }
        Response.Write(errormsg);
    }

    private string GetContentType(string fileExtension)
    {
        string ct = Registry.GetValue(@"HKEY_CLASSES_ROOT\." + fileExtension.ToLower(), "Content Type", string.Empty) as string;

        if (ct.Length == 0)
        {
            ct = "application/octet-stream";
        }

        return ct;
    }
}


text:
Q: Safari jumpy background size calculation on window resize I have a 100% width background image on the body.
this image

and the css
body {
    background-image: url('../images/bg-width.gif');
    background-position: 0 0;
    background-attachment: scroll;
    background-repeat: repeat-y;
    background-size: 100%;
}

you see here when I resize the window in safari, it doesn't calculate the height and width proportionately, it squishes the width a bit and then jumps to whatever next increment, resulting in a jagged resizing that messes with other aspects of my site design that rely on the proportion of the grid size.
https://imgur.com/CyH5Z61
whereas in chrome, as show below, the scaling is proportional and smooth
https://imgur.com/OXhszPF
Anyone have any insight into why this happens, and perhaps how I can prevent it?
driving me crazy!
(would embed my images but don't have the rep!)


text:
Q: Raise Error, dispose object and re-create it Let's assume we have the following two classes, How can we listen for Errors and if any error occurred, recreate the singleton? I have put together the following code, but would like to know if there is a pattern for safely raise error, dispose object and recreate it automatically?
`
    static void Main(string[] args)
    {
        MyFirstClass.Instance.SayHello();
    }
}
class MySecondClass
{
    public int ID { get; set; }
    public void SayHelloFromSecondClass()
    {
        Console.WriteLine("Say Hello From Second Class");
    }
    public MySecondClass(int id)
    {
        ID = id;
    }
}

public sealed class MyFirstClass
{
    private static readonly MyFirstClass instance = new MyFirstClass();
    private static MySecondClass msc;

    public event EventHandler ErrorOccuredEvent;

    private MyFirstClass() { }

    public static MyFirstClass Instance
    {
        get
        {
            msc = new MySecondClass(id: 1);
            return instance;
        }
    }

    public void SayHello()
    {
        Console.WriteLine("Hello World...");

    }

    static void ErrorOccured(object sender, EventArgs e)
    {
        Console.WriteLine("Oops");
        msc = null;
        Thread.Sleep(5000);
        GC.Collect();
        msc = new MySecondClass(id: 2);

    }
}

`

A: If I understand well, MyFirstClass (which is a singleton) is a kind of wrapper around MySecondClass that turns MySecondClass into a singleton as well.
Let's call MyFirstClass: Wrapper
Let's call MySecondClass: Service
If the clients always consume the Service through the single instance of Wrapper, then re-creating a Wrapper will not help, because the clients might keep a reference to Wapper. Re-creating Service can help if the clients don't see it and cannot keep a reference to it. Therefore they must consume the service indirectly.
It's easiest to achieve this through an interface:
public interface IHelloService
{
    void SayHello();
}

public class HelloService : IHelloService
{
    public void SayHello()
    {
        Console.WriteLine("Hello");
    }
}

public class HelloServiceWrapper : IHelloService
{
    public static readonly IHelloService Instance = new HelloServiceWrapper();

    private HelloServiceWrapper () {}

    private IHelloService _service;

    public void SayHello()
    {
        EnsureServiceAvailable();
        _service.SayHello();
    }

    private void EnsureServiceAvailable()
    {
        if(_service == null) {
            _service = new HelloService();
        }
    }

    private void HandleError()
    {
        _service = null;
    }
}

But if the error happens when the client is using the service ...
HelloServiceWrapper.Instace.SayHello();

... this call might fail.
You would have to re-create the service instantly in order to make succeed the client's call (assuming that re-creating the service will solve the problem and that the error will not occur again immediately):
public void SayHello()
{
    try {
        _service.SayHello();
    } catch {
        _service = new HelloService();
        _service.SayHello();
    }
}

Note: Disposing the service invalidates the object and makes any reference a client has to it invalid. But re-creating a new one does not give the client a new reference! You would need to have a reference to the clients reference in order to be able to give the client a new instance.


text:
Q: Closed equivalence relations and closed equivalence classes. Given a Compact Hausdorff space X and a closed equivalence relation on it, I am trying to show that each equivalence class is a closed subset of X.
I am using the fact that the quotient space of X by this relation is necessarily Hausdorff as the relation is closed. So that by showing that each equivalence class is compact in the quotient space I'd be done, but I don't see how to show this!
Any suggestions? Maybe I am missing something, could you please point me in the right direction?
All help is appreciated!

A: If you already know that $X/{R}$ is Hausdorff then you're almost done: let $q: X \to X/{R}$ be the canonical quotient map sending each $x \in X$ to its class $[x]_R$ under $R$. As $X/{R}$ is Hausdorff, it is $T_1$, i.e. singletons are closed, and by definition every class $[x]_R = q^{-1}[\{q(x)\}]$, which is closed as the inverse image of a closed singleton set under the continuous $q$.


text:
Q: How to vectorize a function which contains an if statement? Let's say we have the following function:
def f(x, y):
    if y == 0:
        return 0
    return x/y

This works fine with scalar values. Unfortunately when I try to use numpy arrays for x and y the comparison y == 0 is treated as an array operation which results in an error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-9884e2c3d1cd> in <module>()
----> 1 f(np.arange(1,10), np.arange(10,20))

<ipython-input-10-fbd24f17ea07> in f(x, y)
      1 def f(x, y):
----> 2     if y == 0:
      3         return 0
      4     return x/y

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried to use np.vectorize but it doesn't make a difference, the code still fails with the same error. np.vectorize is one option which gives the result I expect.
The only solution that I can think of is to use np.where on the y array with something like:
def f(x, y):
    np.where(y == 0, 0, x/y)

which doesn't work for scalars.
Is there a better way to write a function which contains an if statement? It should work with both scalars and arrays.

A: I wonder what the problem is you're facing with np.vectorize. It works fine on my system:
In [145]: def f(x, y):
     ...:     if y == 0:
     ...:         return 0
     ...:     return x/y

In [146]: vf = np.vectorize(f)

In [147]: vf([[3],[10]], [0,1,2,0])
Out[147]:
array([[ 0,  3,  1,  0],
       [ 0, 10,  5,  0]])

Note that the result dtype is determined by the result of the first element. You can also set the desired output yourself:
In [148]: vf = np.vectorize(f, otypes=[np.float])

In [149]: vf([[3],[10]], [0,1,2,0])
Out[149]:
array([[  0. ,   3. ,   1.5,   0. ],
       [  0. ,  10. ,   5. ,   0. ]])

There are more examples in the docs.

A: You can use a masked array that will perform the division only where y!=0:
def f(x, y):
    x = np.atleast_1d(np.array(x))
    y = np.atleast_1d(np.ma.array(y, mask=(y==0)))
    ans = x/y
    ans[ans.mask]=0
    return np.asarray(ans)

A: A kind of clunky but effective way is to basically pre-process the data:
def f(x, y):
    if type(x) == int and type(y) == int: return x/y # Will it ever be used for this?

    # Change scalars to arrays
    if type(x) == int: x = np.full(y.shape, x, dtype=y.dtype)
    if type(y) == int: y = np.full(x.shape, y, dtype=x.dtype)

    # Change all divide by zero operations to 0/1
    div_zero_idx = (y==0)
    x[div_zero_idx] = 0
    y[div_zero_idx] = 1

    return x/y

I timed all the different approaches:
def f_mask(x, y):
    x = np.ma.array(x, mask=(y==0))
    y = np.array(y)
    ans = x/y
    ans[ans.mask]=0
    return np.asarray(ans)

def f_where(x, y):
    x = np.array(x)
    y = np.array(y)
    return np.where(y == 0, 0, x/y)

def f_vect(x, y):
    if y == 0:
        return 0
    return x/y

vf = np.vectorize(f_vect)

print timeit.timeit('f(np.random.randint(10, size=array_length), np.random.randint(10, size=array_length))', number=10000, setup="from __main__ import f; import numpy as np; array_length=1000")
print timeit.timeit('f_mask(np.random.randint(10, size=array_length), np.random.randint(10, size=array_length))', number=10000, setup="from __main__ import f_mask; import numpy as np; array_length=1000")
print timeit.timeit('f_where(np.random.randint(10, size=array_length), np.random.randint(10, size=array_length))', number=10000, setup="from __main__ import f_where; import numpy as np; array_length=1000")
print timeit.timeit('vf(np.random.randint(10, size=array_length), np.random.randint(10, size=array_length))', number=10000, setup="from __main__ import vf; import numpy as np; array_length=(1000)")

# f
# 0.760189056396

# f_mask
# 2.24414896965

# f_where
# RuntimeWarning: divide by zero encountered in divide return np.where(y == 0, 0, x/y)
# 1.08176398277

# f_vect
# 3.45374488831

The first function is the quickest, and has no warnings. The time ratios are similar if x or y are scalars. For higher dimensional arrays, the masked array approach gets relatively faster (it's still the slowest though).

A: One way is to convert x and y to numpy arrays inside your function:
def f(x, y):
    x = np.array(x)
    y = np.array(y)
    return np.where(y == 0, 0, x/y)

This will work when one of x or y is a scalar and the other is a numpy array.  It will also work if they are both arrays that can be broadcast.  It won't work if they're arrays of incompatible shapes (e.g., 1D arrays of different lengths), but it's not clear what the desired behavior would be in that case anyway.

A: Consider that you have a predicted vector / np array :
[0,1,0,1,1,0] and you want to convert it to the sequence ['N', 'Y', 'N', 'Y', 'Y', 'N']
import numpy as np

y_pred = np.array([0,1,0,1,1,0])

def toYN(x):
    if x > 0:
        return "Y"
    else:
        return "N"

vf_YN = np.vectorize(toYN)
Loan_Status = vf_YN(y_pred)

Loan_Status will contain ['N', 'Y', 'N', 'Y', 'Y', 'N']


text:
Q: Apache Fluent HttpClient behind a proxy results in unknown host I'm trying to use Apache fluent client with a proxy but I'm getting UnknownHostException for the target host.
Why httpclient is trying to resolve the host using dns directly instead of using the proxy?
Here's my code so far:
String response = Executor.newInstance()
    .auth(new HttpHost(proxyHost, proxyPort), "user", "pass")
    .authPreemptiveProxy(new HttpHost(proxyHost, proxyPort))
    .execute(Request.Get("http://example.com")).returnContent().asString();

I would need somehow to inform httpclient to use dns resolver that is based on the proxy (or don't use it at all, as all it needs is connecting to the proxy server).

A: Setting auth credentials is not enough. Try using Request#viaProxy to execute the request via a proxy
    String response = Executor.newInstance()
            .auth(new HttpHost(proxyHost, proxyPort), "user", "pass")
            .authPreemptiveProxy(new HttpHost(proxyHost, proxyPort))
            .execute(Request.Get("http://example.com").viaProxy(new HttpHost(proxyHost, proxyPort))).returnContent().asString();


text:
Q: Xcode SwiftUI modify extension variable I have an extension of Color that stores a colour variable. I am currently using this to set the main colour for the whole app, which currently works.
extension Color{ static var colour: Color = Color.red }
If I set it to red everything turns red. But at the moment I have to hard code what colour it will be. I want to be able to modify this colour during runtime.
I have tried to modify the extension at runtime but I can't seem to get it working and I'm not sure if it allows you to do this. I'm not sure the best way to approach this.
If anyone has anyway of changing the variable in an extension that would be ideal but if there's another way, any help would be greatly appreciated. If you have any questions or I haven't explained something clearly ask away.
Thanks so much


text:
Q: Verify Google + profile/page in the web master tools How can I vefiry the google + page/profile url into web master tools?
For a example google + page url is  https://plus.google.com/u/0/b/123456789

After added this into google web master tools I have to verify that.

I need to access the google tag manager?
Please anyone give me advices to do this? Appreciate your help.
Thank you

A: You are not an owner of plus.google.com so you will not be able to verify it.