text:
Q: Context_processor does not define a " " class/attribute(error) I am following a Django course from Antonio's Melle Book, and I need a context_processor to use a cart instance throught the webapp. I constantly get the error, that the context processor does not define a "cart" object attribute.
Note: I am using cached sessions, if it matters
I tried putting the cart in a try catch statement, I have read the docs, I doesn't sort things out for me
context_processors.py
   from .cart import Cart
   def cart(request):
       return {'cart': Cart(request)}

settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
             (...)
            'cart.context_processors.cart,']}

cart.py
    class Cart(object):
    def __init__(self, request):
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

A: You haven't shown the actual error message. But the problem is probably because you've put the comma inside the quotes instead of outside. Change it to:
'cart.context_processors.cart',]}


text:
Q: Allow dashes for alphanumeric directive in angularjs I'm using a directive to allow only alphanumeric characters in my fields. I found this directive to do this:
app.directive('onlyAlphabets', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, ngModelCtrl) {
      function fromUser(text) {
        var transformedInput = text.replace(/[^0-9a-zA-Z\s]/g, '');
        console.log(transformedInput);
        if (transformedInput !== text) {
          ngModelCtrl.$setViewValue(transformedInput);
          ngModelCtrl.$render();
        }
        return transformedInput; // or return Number(transformedInput)
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  };
});

This works fine. Now I want to allow dashes as well. How can i do this?

A: change you regular expression to
 text.replace(/[^0-9a-zA-Z\-\s]/g, '');

Example

redpajama_set_name: RedPajamaStackExchange


text:
Q: In STL maps, is it better to use map::insert than []? A while ago, I had a discussion with a colleague about how to insert values in STL maps. I preferred map[key] = value; because it feels natural and is clear to read whereas he preferred map.insert(std::make_pair(key, value)).
I just asked him and neither of us can remember the reason why insert is better, but I am sure it was not just a style preference rather there was a technical reason such as efficiency. The SGI STL reference simply says: "Strictly speaking, this member function is unnecessary: it exists only for convenience."
Can anybody tell me that reason, or am I just dreaming that there is one?

A: A gotcha with map::insert() is that it won't replace a value if the key already exists in the map. I've seen C++ code written by Java programmers where they have expected insert() to behave the same way as Map.put() in Java where values are replaced.

A: The two have different semantics when it comes to the key already existing in the map. So they aren't really directly comparable.
But the operator[] version requires default constructing the value, and then assigning, so if this is more expensive then copy construction, then it will be more expensive. Sometimes default construction doesn't make sense, and then it would be impossible to use the operator[] version.

A: Another thing to note with std::map:
myMap[nonExistingKey]; will create a new entry in the map, keyed to nonExistingKey initialized to a default value.
This scared the hell out of me the first time I saw it (while banging my head against a nastly legacy bug).  Wouldn't have expected it.  To me, that looks like a get operation, and I didn't expect the "side-effect."  Prefer map.find() when getting from your map.

A: When you write
map[key] = value;

there's no way to tell if you replaced the value for key, or if you created a new key with value.
map::insert() will only create:
using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
    cout << "key " <<  key << " already exists "
         << " with value " << (res.first)->second << endl;
} else {
    cout << "created key " << key << " with value " << value << endl;
}

For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read map[key] = value.

A: One note is that you can also use Boost.Assign:
using namespace std;
using namespace boost::assign; // bring 'map_list_of()' into scope

void something()
{
    map<int,int> my_map = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
}

A: If the performance hit of the default constructor isn't an issue, the please, for the love of god, go with the more readable version.
:)

A: insert is better from the point of exception safety.
The expression map[key] = value is actually two operations:

*

*map[key] - creating a map element with default value.

*= value - copying the value into that element.

An exception may happen at the second step. As result the operation will be only partially done (a new element was added into map, but that element was not initialized with value). The situation when an operation is not complete, but the system state is modified, is called the operation with "side effect".
insert operation gives a strong guarantee, means it doesn't have side effects (https://en.wikipedia.org/wiki/Exception_safety). insert is either completely done or it leaves the map in unmodified state.
http://www.cplusplus.com/reference/map/map/insert/:

If a single element is to be inserted, there are no changes in the container in case of exception (strong guarantee).

A: If your application is speed critical i will advice using [] operator because it creates total 3 copies of the original object out of which 2 are temporary objects and sooner or later destroyed as.
But in insert(), 4 copies of the original object are created out of which 3 are temporary objects( not necessarily "temporaries") and are destroyed.
Which means extra time for:
1. One objects memory allocation
2. One extra constructor call
3. One extra destructor call
4. One objects memory deallocation
If your objects are large, constructors are typical, destructors do a lot of resource freeing, above points count even more. Regarding readability, i think both are fair enough.
The same question came into my mind but not over readability but speed.
Here is a sample code through which I came to know about the point i mentioned.
class Sample
{
    static int _noOfObjects;

    int _objectNo;
public:
    Sample() :
        _objectNo( _noOfObjects++ )
    {
        std::cout<<"Inside default constructor of object "<<_objectNo<<std::endl;
    }

    Sample( const Sample& sample) :
    _objectNo( _noOfObjects++ )
    {
        std::cout<<"Inside copy constructor of object "<<_objectNo<<std::endl;
    }

    ~Sample()
    {
        std::cout<<"Destroying object "<<_objectNo<<std::endl;
    }
};
int Sample::_noOfObjects = 0;

int main(int argc, char* argv[])
{
    Sample sample;
    std::map<int,Sample> map;

    map.insert( std::make_pair<int,Sample>( 1, sample) );
    //map[1] = sample;
    return 0;
}

A: Now in c++11 I think that the best way to insert a pair in a STL map is:
typedef std::map<int, std::string> MyMap;
MyMap map;

auto& result = map.emplace(3,"Hello");

The result will be a pair with:

*

*First element (result.first), points to the pair inserted or point to
the pair with this key if the key already exist.

*Second element (result.second), true if the insertion was correct or
false it something went wrong.
PS: If you don´t case about the order you can use std::unordered_map ;)
Thanks!

A: This is a rather restricted case, but judging from the comments I've received I think it's worth noting.
I've seen people in the past use maps in the form of
map< const key, const val> Map;

to evade cases of accidental value overwriting, but then go ahead writing in some other bits of code:
const_cast< T >Map[]=val;

Their reason for doing this as I recall was because they were sure that in these certain bits of code they were not going to be overwriting map values; hence, going ahead with the more 'readable' method [].
I've never actually had any direct trouble from the code that was written by these people, but I strongly feel up until today that risks - however small - should not be taken when they can be easily avoided.
In cases where you're dealing with map values that absolutely must not be overwritten, use insert. Don't make exceptions merely for readability.

A: Here's another example, showing that operator[] overwrites the value for the key if it exists, but .insert does not overwrite the value if it exists.
void mapTest()
{
  map<int,float> m;

  for( int i = 0 ; i  <=  2 ; i++ )
  {
    pair<map<int,float>::iterator,bool> result = m.insert( make_pair( 5, (float)i ) ) ;

    if( result.second )
      printf( "%d=>value %f successfully inserted as brand new value\n", result.first->first, result.first->second ) ;
    else
      printf( "! The map already contained %d=>value %f, nothing changed\n", result.first->first, result.first->second ) ;
  }

  puts( "All map values:" ) ;
  for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
    printf( "%d=>%f\n", iter->first, iter->second ) ;

  /// now watch this..
  m[5]=900.f ; //using operator[] OVERWRITES map values
  puts( "All map values:" ) ;
  for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
    printf( "%d=>%f\n", iter->first, iter->second ) ;

}

A: The fact that std::map insert() function doesn't overwrite value associated with the key allows us to write object enumeration code like this:
string word;
map<string, size_t> dict;
while(getline(cin, word)) {
    dict.insert(make_pair(word, dict.size()));
}

It's a pretty common problem when we need to map different non-unique objects to some id's in range 0..N. Those id's can be later used, for example, in graph algorithms. Alternative with operator[] would look less readable in my opinion:
string word;
map<string, size_t> dict;
while(getline(cin, word)) {
    size_t sz = dict.size();
    if (!dict.count(word))
        dict[word] = sz;
}

A: The difference between insert() and operator[] has already been well explained in the other answers. However, new insertion methods for std::map were introduced with C++11 and C++17 respectively:

*

*C++11 offers emplace() as also mentioned in einpoklum's comment and GutiMac's answer.

*C++17 offers insert_or_assign() and try_emplace().

Let me give a brief summary of the "new" insertion methods:

*

*emplace(): When used correctly, this method can avoid unnecessary copy or move operations by constructing the element to be inserted in place. Similar to insert(), an element is only inserted if there is no element with the same key in the container.

*insert_or_assign(): This method is an "improved" version of operator[]. Unlike operator[], insert_or_assign() doesn't require the map's value type to be default constructible. This overcomes the disadvantage mentioned e.g. in Greg Rogers' answer.

*try_emplace(): This method is an "improved" version of emplace(). Unlike emplace(), try_emplace() doesn't modify its arguments (due to move operations) if insertion fails due to a key already existing in the map.

For more details on insert_or_assign() and try_emplace() please see my answer here.
Simple example code on Coliru


text:
Q: Sniffing multiple ports of USB Hub simultaneously I want to send data to an upstream port of a USB hub and read it through all downstream ports of the hub, each connected to a different device i.e broadcasting USB data. Basically to observe & ensure if data coming through all downstream ports of hub are same or not.
Are there any ways or tools to do this?
I am trying this on USB 2.0 hub and Ubuntu 18.04LTS system.

A: To verify that all data are broadcast to all downstream ports of a USB 2.0 hub you will need the corresponding number of USB logic analyzers (like this one) that are synchronized with a special (and hard to find) cable. You will need one analyzer on upstream side, and analyzers on each downstream port, between the hub and each of your devices.
Unfortunately, as far as I know, only two analyzers can be synchronized. So testing several downstream ports at once will be a challenge.


text:
Q: jQuery cant load xml from server I'm trying to load the National weather service xml document for my local conditions. I can't seem to successfully load the file from their servers, but if I save the file locally, it works.
    $.ajax({
        type: 'GET',
        url: 'http://www.weather.gov/xml/current_obs/KROC.xml',
        datatype: 'xml' })
            .done(function(data) { alert("Server: success"); })
            .fail(function(jqXHR, textStatus, errorThrown) { alert("Server: error:"+jqXHR.statusText+' textStatus='+textStatus+', errorThrown='+errorThrown ); })
            .always(function() { alert("Server: complete"); });

That one gives this for an error alert:

Server: error:error textStatus=error, errorThrown=

But if I save the file locally like this:
    $.ajax({
        type: 'GET',
        url: 'xml/KROC.xml',
        datatype: 'xml' })
            .done(function(data) { alert("Client: success"); })
            .fail(function(jqXHR, textStatus, errorThrown) { alert("Client: error:"+jqXHR.statusText+' textStatus='+textStatus+', errorThrown='+errorThrown ); })
            .always(function() { alert("Client: complete"); });

Then it loads successfully. It's driving me crazy.

A: This approach must first tackle a basic limitation of the XMLHttpRequest object used by Ajax programs: the same domain problem.
For security reasons, an XMLHttpRequest call can only initiate requests to the same server that delivered the original Web page. Unless I work for the National Weather Service, my server is outside of their domain (www.nws.noaa.gov).
http://www.ibm.com/developerworks/xml/library/x-xmlajaxpt1/index.html


text:
Q: 8-Way Color Filling Algorithm for a Circle leaks out of the boundary My goal was to create an efficient version of flood fill polygon filling algorithm. The code works correctly for filling rectangles but for some reason it jumps out of the circle while filling the South-East Pixels.
The disadvantage of flood fill algorithm is that it does not work for really big shapes by causing a stack overflow because of many extra functions stored in the stack while recursively calling itself. TO overcome this, I have written this algorithm where I first fill all North,East,South and West pixels as they do not require the recursive function stack. Then, i call NorthEast, SouthEast , SouthWest and NorthWest pixels filling functions which make use of recursion stack. I have ensured that at any particular time, my recursion stack wont have more than 2 methods to avoid a stack overflow.
Please help me to fix the leak
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void northFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        northFill(a,b+1,newcolor,oldcolor);
    }
}
void westFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        westFill(a-1,b,newcolor,oldcolor);
    }
}
void southFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        southFill(a,b-1,newcolor,oldcolor);
    }
}
void eastFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        eastFill(a+1,b,newcolor,oldcolor);
    }
}
void northEastFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        northFill(a,b+1,newcolor,oldcolor);
        eastFill(a+1,b,newcolor,oldcolor);
        northEastFill(a+1,b+1,newcolor,oldcolor);
    }
}
void southEastFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        southFill(a,b-1,newcolor,oldcolor);
        eastFill(a+1,b,newcolor,oldcolor);
        southEastFill(a+1,b-1,newcolor,oldcolor);
    }
}
void northWestFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        northFill(a,b+1,newcolor,oldcolor);
        westFill(a-1,b,newcolor,oldcolor);
        northWestFill(a-1,b+1,newcolor,oldcolor);
    }
}
void southWestFill(int a,int b,int newcolor,int oldcolor){
    int current=getpixel(a,b);
    if(current==oldcolor){
        putpixel(a,b,newcolor);
        southFill(a,b-1,newcolor,oldcolor);
        westFill(a-1,b,newcolor,oldcolor);
        southWestFill(a-1,b-1,newcolor,oldcolor);
    }
}
void fillPoint(int x,int y,int color){
    int pixelColor=getpixel(x,y);
    putpixel(x,y,color);
    northFill(x,y+1,color,pixelColor);
    eastFill(x+1,y,color,pixelColor);
    southFill(x,y-1,color,pixelColor);
    westFill(x-1,y,color,pixelColor);
    northEastFill(x+1,y+1,color,pixelColor);
    southEastFill(x+1,y-1,color,pixelColor);
    southWestFill(x-1,y-1,color,pixelColor);
    northWestFill(x-1,y+1,color,pixelColor);
}
void main(){
    int gd = DETECT , gm;
    int x,y;
    initgraph(&gd,&gm,"");
    circle(320,240,230);     //<- Doesnt work for this
    //rectangle(40,40,630,470); <-Works for this
    printf("Enter x,y: ");
    scanf("%d %d",&x,&y);
    fillPoint(x,y,GREEN);
    getch();
    closegraph();
}


text:
Q: How to embed a digital signature with limited space I am using RFID tags to store some data which will then be read by a 3rd party. I need to include a digital signature (or some variation) along with the data so that the 3rd party can verify the authenticity of the tag.
Straightforward enough. But the problem is that I am constrained by the RFID tag's 32-byte memory array. My application is written in C# (.NET 3.5) and the available digital signature class (DSACryptoServiceProvider) results in a 40 byte signature.
Assume that I need 24 of the 32 bytes to store my data. Is there some way to come up with a 8 byte signature?
Any insight is much appreciated!

A: You might want to read this. Also, take a look at the PBC Library, supporting Boneh-Lynn-Shacham short signatures.


text:
Q: Input-group controls resize within nested rows in IE9 and Twitter Bootstrap 3 I've got a problem with this piece of code in IE9:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../../assets/ico/favicon.png">
    <title>Bootstrap 3 IE 9 problem</title>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

                <input id="ti1" class="form-control input-sm" name="ti1" type="text" placeholder="From">

                <input id="ti2" class="form-control input-sm" name="ti2" type="text" placeholder="To">

Text column1

Text column2

                            <input id="ti3" class="form-control input-sm" name="ti3" type="text" placeholder="Time">
                            <button class="btn btn-default btn-sm">T</button>

                            <input id="ti4" class="form-control input-sm" name="ti4" type="text" placeholder="Time">
                            <button class="btn btn-default btn-sm">T</button>

The problem appears when the mouse hovers over the input group buttons on the right. The input controls are suddenly increase their size. On the other hand, when you click on inputs, the size resets to normal.
I've tested this code in IE10 and there is no such a problem. So, the question is is this a bug or maybe the layout is wrong and causes the problem. If it's a bug then is there any work around?

A: I found out that the problem is in css line 9:
.input-group .form-control {
margin-bottom: 0;
width: 100%;
}

I couldn't understand exactly the source of the problem but a simple workaround could be to add display:block !important;

A: .input-group * {
        width:auto;
}

.input-group .form-control {
    width:auto;
}


text:
Q: Buffer appears faulty using ArcMap ModelBuilder - I have an automatic process in ModelBuilder, where I tell it to load some points through an Excel spreadsheet, make points in shapefiles and then make a buffer. The buffer parameters are as follows:

As the "Dissolve type" parameter says, this process must dissolve all the registers ("All") and remain as one. However, I have noticed that when I run the process in ModelBuilder it does not do such a process, but instead it divides them into more records not dissolving them:

What could be happening?
The version that I am using is ArcMap 10.3.1.


text:
Q: Swift unrecognized selector sent to instance - What am I missing? I can't see why the following button is throwing an error:2014-08-13 00:29:57.674 view1[26581:842344] -[view1.ViewController buttonAction:]: unrecognized selector sent to instance 0x797731c0
2014-08-13 00:29:57.677 view1[26581:842344] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[view1.ViewController buttonAction:]: unrecognized selector sent to instance 0x797731c0'. Any help appreciated. Many Thanks
    import UIKit

        class ViewController: UIViewController {

        override func viewDidLoad() {
        super.viewDidLoad()

        func buttonAction(sender:UIButton)
        {
            println("Button tapped")
        }

        let windowsize = CGRect(x: 0, y: 0, width: 320, height: 480)
        let labelsize = CGRect(x: 0, y: 200, width: 140, height: 60)
        let myButton = UIButton(frame: CGRectMake(0, 0, 100, 100))

        let myView = UIView(frame: windowsize)
        let viewwidth = myView.frame.width
        let spaceleft = (viewwidth - labelsize.width)/2

        myView.backgroundColor = UIColor .blackColor()
        let myLabel = UILabel(frame:labelsize)
        myLabel.frame.origin.x = spaceleft
        myLabel.text = "Hello"
        myLabel.font = UIFont(name: "Chalkduster", size: 22)
        myLabel.textColor = UIColor .whiteColor()
        myLabel.textAlignment = NSTextAlignment.Center

        myLabel.backgroundColor = UIColor .redColor()
        //myView.addSubview(myButton)

        myView.addSubview(myLabel)
        self.view.addSubview(myView)

        let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.frame = CGRectMake(100, 100, 100, 50)
        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Test Button", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        myView.addSubview(button)

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

A: Your buttonAction target is nested inside your viewDidLoad() method. Move it outside and it should be reachable.
class ViewController: UIViewController {

    func buttonAction(sender:UIButton)
    {
        println("Button tapped")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // ...

        let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
        // ...
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        myView.addSubview(button)
    }
}


text:
Q: confused with  watched tutorial from sebastian lague for pathfiending.and code example
public class Heap<T> where T : HeapIndex<T>
{

}
public interface HeapIndex<T> : IComparable<T>
{
    int IndexHeap
    {
        get;
        set;
    }
}
public class Node : HeapIndex<Node>
{
    public int IndexHeap { get; set; }

    public int CompareTo([AllowNull] Node other)
    {
        return IndexHeap.CompareTo(other.IndexHeap);
    }
}

and Heap<Node> heapNode = new Heap<Node>();
all its work. i start read for  and i confused. why i cant do with this way
public class NodeInt : HeapIndex<int>
{
    public int IndexHeap { get; set; }

    public int CompareTo([AllowNull] int other)
    {
        return IndexHeap.CompareTo(other);
    }
}
        NodeInt nd = new NodeInt();
        HeapIndex<NodeInt> hpD = nd as HeapIndex<NodeInt>;
        Heap<NodeInt> heapInt = hpD as Heap<NodeInt>;

bacause its not work Heap<NodeInt> heapNodeInt = new Heap<NodeInt>();
I probably just do not fully understand, and terribly blurred my eyes. but I thought that his code works, any instance that meets the requirement where T is an interface implementation, then you can use it to create a heap
why i cant just Heap<NodeInt> heapNodeInt = new Heap<NodeInt>();

A: Heap<T> where T : HeapIndex<T> means that if you want Heap<NodeInt>, then the NodeInt should inherit HeapIndex<NodeInt> just because T = NodeInt in the Heap declaration. But your NodeInt is HeapIndex<int>, so it does not meet requirement and this code won't compile.


text:
Q: IE7 won't show my website entirely I find myself in a pickle, I hope someone can help.
I have a website and if I open this website in any browser out there it works perfectly find until I open it with IE7. IE7 opens the website however it only load half of it... the html source code is downloaded successfully and the elements in the background are active, they are just not visible to clients o.O what can I do??
The website is: http://ambulanta-susnik.voblaku.com/
I'm not trying to advertise in ANY WAY. I just fell like this is the only way to really show you whats wrong.
Try opening it in IE7 or IE9 with Document type: IE7 standards.
Any ideas??? I tried everything ... different doctypes, xmls declaration, xml declaration, etc...
W3C HTML validator shows 5 Errors, 5 warning(s) but those are only for unencoded links...
Screenshots for those who can't use IE7 compatibility mode:
WRONG WAY: http://ambulanta-susnik.voblaku.com/files/wrong.png
RIGHT WAY: http://ambulanta-susnik.voblaku.com/files/right.png

A: Add position:relative to the #content {} css


text:
Q: Random symbols after manipulating a char array in C void coma(char* str){
int j, i = 0;
int size = strlen(str);
int commas = (size-3)/3;
int left = (size-3)%3;
char tmp[20];

for(j = 0; j<size; i++){
    if(left || commas == 0){
        tmp[i] = str[j++];
        left--;
    }else {
        tmp[i] = ',';
        left = 3;
        commas--;
    }
}
strcpy(str,tmp);    }

int main(){

char str[0x100];
float x = 5002052.1111;

sprintf(str,"%.2f", x);

coma(str);
printf("%s\n",str);  }

I am trying to insert commas every third place on a float number for example the number "5002052.1111" will be "5,002,052.11"
but when I run the program instead of getting what I am expecting I get the correct answer plus random symbols like "5,002,052.11@  {"
I notice that if I put the exact size of number in the char tmp[] it will work fine, but I need it to work with any size of numbers.
I am using gcc.

A: append '\0' to the tmp string, before calling strcpy()


text:
Q: Why does my WSGI app always get URL decoded path in environ['PATH_INFO']? I have a simple bare WSGI application:
def application(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    print('PATH_INFO:', environ['PATH_INFO'])
    return [b'
Hello World
']

if __name__ == '__main__':
    from wsgiref import simple_server
    server = simple_server.make_server('0.0.0.0', 8080, application)
    server.serve_forever()

I make two requests:
C:\>curl "http://localhost:8080/<foo>"

Hello World

C:\>curl "http://localhost:8080/%3Cfoo%3E"

Hello World

I get this output:
C:\code>python foo.py
PATH_INFO: /<foo>
127.0.0.1 - - [09/Mar/2014 13:48:39] "GET /<foo> HTTP/1.1" 200 18
PATH_INFO: /<foo>
127.0.0.1 - - [09/Mar/2014 13:48:47] "GET /%3Cfoo%3E HTTP/1.1" 200 18

See how my application gets the URL decoded path /<foo> even when the client requests /%3Cfoo%3E.
It shows that wsgiref.simple_server ensures that my application always gets the URL-decoded path in environ['PATH_INFO'].
But I can't find this behavior documented anywhere in PEP-3333. Can you please point me to an official documentation that documents this behavior?

A: The value of REQUEST_URI from the actual HTTP request line, if the server makes it available, would be:
REQUEST_URI: '/%3Cfoo%3E'

This is probably the case even if you used:
curl "http://localhost:8080/<foo>"

because curl would encode the URL before sending to use the % escapes.
REQUEST_URI is not I believe covered by any RFC but is a variable provided by many servers. You cannot rely on its presence though, so don't write your WSGI application to depend on it existing.
The web server will decode the % escapes in REQUEST_URI before processing it. The result which will end up in PATH_INFO will thus always be:
PATH_INFO: '/<foo>'

The decoding is covered by the CGI and related RFCs that WSGI builds on.
See for example:

*

*http://www.ietf.org/rfc/rfc3875

*http://www.ietf.org/rfc/rfc2396


text:
Q: How do I utilise Javascript merging? To be clear, this is not a post about Javascript Bundling. This is about Javascript Merging.
So, I'm in Production Mode and I'm starting to look at the optimisation of Javascript Merging. My benchmarks are as follows:

*

*Javascript Bundling = Off (226 js files load)

*Javascript Bundling = On (223 js files load)

I honestly expected this difference to be much more significant. Magento Documentation says to just turn it on. But clearly, there's another level to it than that.
What am I missing to fully utilise the Javascript Merging feature?

A: After lots of tutorials I could manage to make this work by running:
bin/magento deploy:mode:set production
bin/magento config:set dev/js/enable_js_bundling 1
bin/magento config:set dev/js/minify_files 1
bin/magento config:set dev/static/sign 1
then I've deleted manually everything except .htaccess from pub/static and
bin/magento setup:static-content:deploy -f


text:
Q: pushviewcontroller or pop to viewcontroller UINavigationController I have afew doubts about how I've being using UINavigationController.
My question simply is, is it better practice to completely populate the viewcontrollers stack with all the views it will need and navigate through the view using methods like popToViewController.
-Or-
Is it better to simpy push a view to the stack when you need it? For example If I push a view controller and then hit the back button and then push the same view controller again will there be 2 instances on that view in the stack or does the action of hitting the back button remove it?

A: Generally, pushing view controllers when you need them is what lazy loading is meaning: use resources when you need them. There is no point in creating whole hierarchy at start because that spells trouble and requires significant management overhead. Why do something by yourself when someone else implemented for you and you know it works?


text:
Q: Оператор join linq Изучаю LINQ, операцию JOIN.
Вот код:
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Pet
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

class Cat : Pet
{ }

class Dog : Pet
{ }

class Program
{
    static void Main(string[] args)
    {
        Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
        Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
        Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
        Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
        Person rui = new Person { FirstName = "Rui", LastName = "Raposo" };
        Person phyllis = new Person { FirstName = "Phyllis", LastName = "Harris" };

        Cat barley = new Cat { Name = "Barley", Owner = terry };
        Cat boots = new Cat { Name = "Boots", Owner = terry };
        Cat whiskers = new Cat { Name = "Whiskers", Owner = charlotte };
        Cat bluemoon = new Cat { Name = "Blue Moon", Owner = rui };
        Cat daisy = new Cat { Name = "Daisy", Owner = magnus };

        Dog fourwheeldrive = new Dog { Name = "Four Wheel Drive", Owner = phyllis };
        Dog duke = new Dog { Name = "Duke", Owner = magnus };
        Dog denim = new Dog { Name = "Denim", Owner = terry };
        Dog wiley = new Dog { Name = "Wiley", Owner = charlotte };
        Dog snoopy = new Dog { Name = "Snoopy", Owner = rui };
        Dog snickers = new Dog { Name = "Snickers", Owner = arlene };

        List<Person> people =
            new List<Person> { magnus, terry, charlotte, arlene, rui, phyllis };
        List<Cat> cats =
            new List<Cat> { barley, boots, whiskers, bluemoon, daisy };
        List<Dog> dogs =
            new List<Dog> { fourwheeldrive, duke, denim, wiley, snoopy, snickers };

        var query = from person in people
                    join dog in dogs on new { person.FirstName, person.LastName } equals new { dog.Owner.FirstName, dog.Owner.LastName }
                    join cat in cats on new { person.FirstName, person.LastName } equals new { cat.Owner.FirstName, cat.Owner.LastName }
                    select new {person, dog, cat};

        foreach(var item in query)
        {
            Console.WriteLine($"{item.person.FirstName} {item.person.LastName} owns cat {item.cat.Name} and dog {item.dog.Name}");
        }
    }

Результат:
Magnus Hedlund owns cat Daisy and dog Duke
Terry Adams owns cat Barley and dog Denim
Terry Adams owns cat Boots and dog Denim
Charlotte Weiss owns cat Whiskers and dog Wiley
Rui Raposo owns cat Blue Moon and dog Snoopy

Как видно, объект с именем Terry Adams дублируется из-за наличия у него двух котов.
Вопрос: Как нужно изменить запрос, чтобы в анонимный клас попадал список(ну или массив) котов и собак, и соответственно избежать дубликата


text:
Q: ReSharper errors - Cannot convert type from mscorlib to type from System.Runtime I have a .NET 4.5 class library (containing tests) with a project reference to a portable class library. The PCL targets the following platforms:

*

*.NET Framework 4.5

*Windows 8

*Xamarin.Android

*Xamarin.iOS

*Xamarin.iOS (Classic)

I'm on Visual Studio 2013 Premium with ReSharper 6. At some point recently, I started seeing many, many inline warnings (red squiggly underlines) in the test project indicating the following or similar:
Cannot convert source type 'string [mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]'
    to target type 'string [System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]'

There are no build errors or warnings, just the annoying inline errors. If I turn off "Enable code analysis" in ReShaper's settings, they go away, but of course so do many helpful features. This started happening just recently but I can't pinpoint what triggered it. I did upgrade from Windows 8.1 to Windows 10 recently, not sure if that has anything to do with it. Any tips that might help me pinpoint the cause would be greatly appreciated.

A: Could you test your solution with the latest R# version? There were known issues with PCL references, for example RSRP-430728.


text:
Q: Streaming bytes to ALSA playback device I'm having a lot of trouble writing random bytes to an ALSA playback device using libasound. Eventually, my goal is to be able to route playback stream over the network and have it played on a remote device.
The code presented in this question reads a WAV file into memory and writes it to the driver via snd_pcm_writei and it works. However, a crucial difference between what this code does and what I'm trying to do is the fact that I don't have all the data available to me right away. I'm looking to stream data as it becomes available.
Adapting the above sample code to fit my needs, I end up with this:
#include <stdio.h>
#include <unistd.h>
#include <alsa/asoundlib.h>

static snd_pcm_t *PlaybackHandle;

int init_playback(const char *device, int samplerate, int channels) {
    int err;

    printf("Init parameters: %s %d %d\n", device, samplerate, channels);

    if((err = snd_pcm_open(&PlaybackHandle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
        printf("Can't open audio %s: %s\n", device, snd_strerror(err));
        return -1;
    }

    if ((err = snd_pcm_set_params(PlaybackHandle, SND_PCM_FORMAT_S16, SND_PCM_ACCESS_RW_INTERLEAVED, channels, samplerate, 1, 500000)) < 0) {
        printf("Can't set sound parameters: %s\n", snd_strerror(err));
        return -1;
    }
    return 0;
}

int play_bytes(const void *bytes, int len) {
    snd_pcm_uframes_t frames, count;
    snd_pcm_uframes_t bufsize, period_size;
    frames = 0;
    count = 0;

    snd_pcm_prepare(PlaybackHandle);

    snd_pcm_get_params(PlaybackHandle, &bufsize, &period_size);
    printf("bufsize=%d\n", (int) bufsize);

    do {
        int remaining = len - count;
        int buflen = remaining < bufsize ? remaining : bufsize;
        frames = snd_pcm_writei(PlaybackHandle, bytes + count, buflen);
        // If an error, try to recover from it
        if (frames == -EPIPE) {
            printf("EPIPE\n");
            snd_pcm_prepare(PlaybackHandle);
        }
        if (frames < 0) {
            printf("Recovering\n");
            frames = snd_pcm_recover(PlaybackHandle, frames, 0);
        }
        if (frames < 0)
        {
            printf("Error playing wave: %s\n", snd_strerror(frames));
            break;
        }

        // Update our pointer
        count += frames;
        //printf("count=%d len=%d\n", (int)count, len);

    } while (count < len);

    // Wait for playback to completely finish
    if (count == len)
        snd_pcm_drain(PlaybackHandle);
    return 0;
}

int close_playback() {
    snd_pcm_close(PlaybackHandle);
    return 0;
}

int main(int argc, char **argv) {
    if(argc < 1) {
        printf("Usage: %s <WAV-file>\n", argv[0]);
        return -1;
    }

    int fd;
    unsigned long long len;

    fd = open(argv[1], O_RDONLY);
    // Find the length
    len = lseek(fd, 0, SEEK_END);

    // Skip the first 44 bytes (header)
    lseek(fd, 44, SEEK_SET);
    len -= 44;

    char *data = malloc(len);
    read(fd, data, len);

    init_playback("default", 44100, 2);
    play_bytes(data, len);
    close_playback();
    return 0;
}

This code can be compiled with gcc playback.c -o playback -lasound. The WAV file I'm using can be found here.
When I run this code snippet, where I chunk the incoming data based on bufsize there are fragments of audio that is repeated in the playback depending on the chunk size. A large chunk size yields fewer repetitions than a small chunk size. Combining this with how the audio sounds, I believe that a small fragment at the end of each chunk is being repeated.
The parameters I used were:

*

*samplerate: 44100

*channels: 2

Why does sending the entire WAV file in one shot work whereas sending chunks of it not work? How do I send chunks of audio data to the driver and have it play properly?

A:     frames = snd_pcm_writei(PlaybackHandle, bytes + count, buflen);
    count += frames;

snd_pcm_writei() measures the size in frames, but you treat it as bytes. So you skip over only one fourth of the data that was just played.


text:
Q: How to copy network credentials from PEAP authenticated computer to a new PC Backstory
I'm a student on our school's school network. There's three tears of network at our school. There's the Student network which the student iPads are connected to. We don't have the keys, but I was able to extract the WPA2 code and connect my own devices. The internet is just slow because of all of the iPads that are connected. The network traffic is slow on the 'student' network. There's the educator network key which I got from a school computer I have special access to. I'm a lighting designer, and needed an internet connected PC. The IT guy gave me one, and I extracted the WPA2 key. I can connect my devices to the network using that key, and the IT guy knows about it. It's not much faster though, and he actually cares about the devices on that network, and he can easily catch me probably through ICMP protocols and a bunch of other ways. He doesn't want me connecting to it. The other option is the 'radius' network. My school-issued crappy laptop has also been given the credentials to this network. This is very long-range, and the network is supposed to be slower, but since there's no traffic on it, it's actually speedy. No one uses it, because it's intended to extend to the football field, soccer, base ball fields. That's the reason for its existence. It's got some more fancy security for some reason, and I've heard that the IT guy doesn't care about it as much. However, it uses some unfamiliar PEAP authentication, meaning I can't just copy and paste the key. That's the one I want to put on my personal laptop which has much better specs than the 8 year old i3, 4gb Ram PC I'm using now to use this network. The IT guy will probably just tell me to use the Student network (which he knows I have), which is too slow.
Actual Question
How can I copy a PEAP authenticated network profile from one PC from my school connected PC to my personal laptop? When Windows says the network is AES encrypted, does that mean that the authentication certificate is encrypted or the network traffic? Is there a way to extract a WPA2 password from the certificate. I have administrator access on the school PC, and obviously administrator access on my personal laptop. If I don't know how enterprise network authentication works, is this even worth my time?
Thanks Superuser!

A: PEAP has options for what kind of login credentials it uses. It can use usernames and passwords or it can use public key certificates and their matching private keys.
The credentials can be stored in the user accounts, or they can be stored in a system-wide location so the machine can be on the network even when no user is logged in (like for remote management and overnight backups).
You can see what public key certificates are installed by using certmgr.mmc, which is the Certificate Manager snap-in for the Microsoft Management Console. You can use that tool to export certificates, and, in some cases, also export their matching private keys, which are a necessary part of the login credentials. You can't use a cert to auth to a network if you don't have the private key that goes with it.
If the private key you need was marked as non-exportable when it was installed, Microsoft's tools won't let you export it. However, there are third party tools that can help you extract non-exportable private keys out of the certificate store, if you have the right level of access to the PC. IIRC, you need to know the local admin password.


text:
Q: Find an infinite sequence of numbers that can't be the derivatives of power series
First, I noticed that the nth derivative of $f$ at $0$ is $n!\cdot a_n$, but this does not really help me to construct a sequence of numbers that can not be generated by the sequence ${f(0),f'(0),f''(0),\ldots}$.  How should I construct the sequence?
Thank you in advance.

A: Find a sequence that grows fast enough to make the radius of convergence of
$$
\sum_{n=0}^\infty \frac{a_n}{n!} z^n
$$
less than $1$.


text:
Q: Render a status code when an error occured When someone accesses my API with something different than an integer value, it should return a 400 Error.
My minimalized index method is:
def index
    @returnType = MyType.all

    if params["limit"].present?
        begin
            limit = Integer(limit)
        rescue Exception=>e
            render status: :bad_request
        end
     end

    respond_to do |format|
        format.json
    end
end

But, in the exception-case I get a AbstractController::DoubleRenderError.
The problem is, Rails doesn't stop the method at render, it continued with the respond_to part.

A: You need to render and return:
if params["limit"].present?
    begin
        limit = Integer(limit)
    rescue Exception=>e
        render status: :bad_request
        return
    end
 end

This will render the error and then stop execution of the method.


text:
Q: Yii2 article name in url I have action 'show' for showing articles in blog whose URL is: localhost/myblog/web/blog/blog/post?id=4.
I want the URL to be localhost/myblog/web/blog/blog/post/unique/title-of-article.  How to accomplish something like this?

A: You must use SluggableBehavior in your model to generate the url part which is human readable. This data is saved saved to your database model.
With this slug and some modifications to your controller and UrlManager rules you can create what you want.
This would be a complete tutorial and this was already answered here on Stackoverflow.
If you need more detailed tutorials I would suggest to google. Multiple tutorials can be easily found like this.


text:
Q: Rounding to eliminate decimal I have query below as:
SELECT ds,
       round(count(CASE WHEN action = 'accepted' THEN 1
             ELSE NULL END) * 1.0 / count(action),2) * 100 as perc
FROM friend_requests
group by 1

Output:
perc
50.00
100.00
50.00

desired output:
perc
50
100
50

If I want to remove decimals and just have 50 or 100 how can I edit this? I try changing the ,2 parameter in round to ,0 and it just rounds all values to 100
Thanks

A: Cast your perc field as an int type and remove the round function:
SELECT
    ds,
    cast(count(CASE WHEN action = 'accepted' THEN 1 ELSE NULL END) * 1.0 / count(action) * 100 as int) as perc
FROM friend_requests
group by 1

A: I would suggest phrasing the logic as:
SELECT ds,
       round(avg( (action = 'accepted')::int) * 100), 0) as perc
FROM friend_requests
GROUP BY 1


text:
Q: How to simplify nested If's in Python 3 for better performance and readability? I have been trying to maximize the readability and eliminate the verbosity of the algorithm that I created to detect entities.
I have a function with this structure:
    def function(ex, pr):
    if ex[pr.start - 1] and not \
            pr.start - 1 < 0 and not \
            ex[pr.start - 1].is_space and not \
            ex[pr.start - 1].is_punct:
        words = ex[pr.start - 1]
    elif ex[pr.start - 2] and not \
            pr.start - 2 < 0 and not \
            ex[pr.start - 2].is_space and not \
            ex[pr.start - 2].is_punct:
        words = ex[pr.start - 2]
    elif ex[pr.start - 3] and not \
            pr.start - 3 < 0 and not \
            ex[pr.start - 3].is_space and not \
            ex[pr.start - 3].is_punct:
        words = ex[pr.start - 3]
    elif ex[pr.start - 4] and not \
            pr.start - 4 < 0 and not \
            ex[pr.start - 4].is_space and not \
            ex[pr.start - 4].is_punct:
        words = ex[pr.start - 4]
    else:
        words = ''
    return words

This solution works, however, there are lots of repeated structures here.
I tried range() function
 def function(ex, pr):
    global words
    for index in range(1, 5):
        if ex[pr.start - index] and not \
                pr.start - index < 0 and not \
                ex[pr.start - index].is_space and not \
                ex[pr.start - index].is_punct:
            words = ex[pr.start - index]
        else:
            words = ''
    return words

Also I tried for index in (1,2,3,4):
How can I simplify this structure to eliminate the multiple elif's and hardcoded numbers?
Any suggestions would be appreciated.

A: My suggestion would be to create a function that does the check:
def check(ex, pr, number):
    if ex[pr.start - number] and not \
        pr.start - number < 0 and not \
        ex[pr.start - number].is_space and not \
        ex[pr.start - number].is_punct:

        return True

    else:
        return False

This would simplify the other function to:
def function(ex, pr):
    if check (ex, pr, -1):
        words = ex[pr.start - 1]
    elif check (ex, pr, -2):
        words = ex[pr.start - 2]
    elif check (ex, pr, -3):
        words = ex[pr.start - 3]
    elif check (ex, pr, - 4):
        words = ex[pr.start - 4]
    else:
        words = ''

   return words

Or you could even use the loop. Note that I added a break statement to make sure it performs the same as the code where no loop is used
def function(ex, pr):
    global words
    for index in range(1, 5):
        if check(ex, pr, index):
            words = ex[pr.start - index]
            break    # <-- added a break here
        else:
            words = ''
    return word


text:
Q: solve a nonlinear model with DICOPT solver in Pyomo How can I solve a nonlinear model with DICOPT solver in Pyomo?
Is this possible to use DICOPT solver through Neos for Pyomo?

A: Nowadays, the Neos server only supports a small number of solvers through Pyomo. I may consider installing 'gams' with at least a demo license and call DICOPT from gams from Pyomo.

A: You cannot use DICOPT solver in Pyomo, not supported. However, if your model is written in Pyomo then you can save it in gams format using model.write('mymodel.gms') then upload it to NEOS. Or open your model in GAMS Studio, select GAMS > Run NEOS - Short from the menu to automatically establish a connection with NEOS. In that case you can use GAMS demo without paying any license fees.


text:
Q: Insert and check data in PostgreSql database I have the following problem. Using Java application i need to insert data from external XML file to database table every 1 second.
In addition, I have to perform a select/update query on the same table.
Table is cleaned every few days. My question is: how to solve it optimally? Everything must work live. We can't allow a situation where there is a time shift( records are not checked every 1s).
Any ideas?

A: Depending on how complex you plan your application to be, you might consider JPA/Hibernate to access your database. It makes a lot simpler to access your DB (because you manipulate POJO's to access your data) but the downside is that it is not optimal in term of performance (manipulating raw sql and raw data will always be faster than manipulating objects).
For your job check, I would set up quartz which will offer you the possibility to schedule jobs periodically.
Your question is kind of vague to give more hints. Is it a web application? a Java EE one? A heavy-client? How bad do you need high-performance? Do you want to create a small-application with no future written on a pizza-napkin or do you plan to have an application that will extend in the future.

A: 10-20 records per second is not a large amount. Anyway, if you have any performance problem, make sure you use JDBC batch inserts:
PreparedStatement stmt = con.prepareStatement(
    "INSERT INTO table_name (field_name1, field_name2) VALUES (?, ?)");

stmt.setInt(1, 2000);
stmt.setString(2, "String value");
stmt.addBatch();

stmt.setInt(1, 3000);
stmt.setString(2, "Other String");
stmt.addBatch();

// submit the batch for execution
int[] insertCounts = stmt.executeBatch();


text:
Q: Office 365 App Only Auth MVC c# I have currently implemented the code into my app from https://github.com/mattleib/o365api-as-apponly-webapp
It all works when clicking sign up, Auth's the account properly and returns to the same Page and allows me to load the calendar events.
My issue is that i need this to be persistent across the entire app as my aim is to do the following.

*

*Administrator on initial login and or app start up, Auth's the app to Office 365.

*When a user logs in they have a link to a page that will display the calendar that is configured for the page, a Resource.

Im assuming i need to setup a token cache, but not sure where from the above code sample, the token is generated and returned. I think it is stored in this variable on postback, Request.Form["id_token"] but unsure on how to store this in a cache/make it available for the entire application.
I have seen some examples that use Session Token Caches but if i am correct, this will require re auth to offcie 365 for each and every user and not be an app wide auth.
Ive tried searching for some samples or any pointers but cant seem to find any.
Anyone able to point me in the right direction


text:
Q: upgraded depricated uuid pacakge in Window npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN mongoskin@2.0.3 requires a peer of mongodb@~2.0 but none is installed. You must install peer dependencies yourself.
I want to upgraded my deprecated uuid packages.
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic


text:
Q: I want to compile the Istio source code in a Centos7 environment, but there are a lot of problems [root@VM-0-15-centos istio]# make build
useradd: UID 0 is not unique
ISTIO_OUT=/work/out/linux_amd64 ISTIO_BIN=/gobin GOOS_LOCAL=linux bin/retry.sh SSL_ERROR_SYSCALL bin/init.sh
Skipping envoy debug. Set DEBUG_IMAGE to download.
/work /work
Downloading envoy: https://storage.googleapis.com/istio-build/proxy/envoy-alpha-432cb173c1e497ae3b05c2af3dadddc91ffa8c65.tar.gz to

real    0m5.408s
user    0m0.731s
sys     0m0.296s
cp: cannot create regular file '': No such file or directory
Unexpected failure: Skipping envoy debug. Set DEBUG_IMAGE to download.
/work /work
Downloading envoy: https://storage.googleapis.com/istio-build/proxy/envoy-alpha-432cb173c1e497ae3b05c2af3dadddc91ffa8c65.tar.gz to

real    0m5.408s
user    0m0.731s
sys     0m0.296s
cp: cannot create regular file '': No such file or directory
Makefile.core.mk:227: recipe for target '/work/out/linux_amd64/istio_is_init' failed
make[1]: *** [/work/out/linux_amd64/istio_is_init] Error 1
make: *** [build] Error 2


text:
Q: UIBinder and MVP in GWT When using the MVP pattern as described here in GWT, how do you create a presenter associated with a view when the view is part of another uibinder-defined view.

A: You instantiate it yourself via:

*

*@UiFactory method:
@UiFactory
public Widget getMyView(){

    // here you instantiate your view & activity
    ...

    // your view contais a widget or is a widget
    return widget
}

*@UiField(provided=true) field :
@UiField(provided=true)
public Widget myView;

// then instantiate it in constructor


text:
Q: how to make gvim hold terminal until it ends? I am trying to find and replace over file hierarchy using gvim like this:
  find . | xargs grep -l pattern | xargs -n 1 gvim -c "%s/pattern/replacement/gc" -c "wq"

I could probably try to make it work properly without the n flag, but I could have theoretically many, many files with matches. What happens now is that gvim dettaches from terminal, so xargs starts all instances of gvim one after another with little delay. If I could force gvim to hold terminal, xargs would wait for gvim to finish, thus there would ever only be one instance of gvim running.
Unfortunately I can't use vim in the environment that this is relevant to. I obtained a working binary for gvim from a colleague, but they did not have a vim binary and I failed to compile vim myself and gave up on it for now.

A: You're looking for the -f command-line option:

-f        GUI: Do not disconnect from the program that started Vim.
          'f' stands for "foreground".  If omitted, the GUI forks a new
          process and exits the current one.  "-f" should be used when
          gvim is started by a program that will wait for the edit
          session to finish (e.g., mail or readnews).  If you want gvim
          never to fork, include 'f' in 'guioptions' in your |gvimrc|.


text:
Q: How to split 16-bit unsigned integer into array of bytes in python? I need to split a 16-bit unsigned integer into an array of bytes (i.e. array.array('B')) in python.
For example:
>>> reg_val = 0xABCD
[insert python magic here]
>>> print("0x%X" % myarray[0])
0xCD
>>> print("0x%X" % myarray[1])
0xAB

The way I'm currently doing it seems very complicated for something so simple:
>>> import struct
>>> import array
>>> reg_val = 0xABCD
>>> reg_val_msb, reg_val_lsb = struct.unpack("<BB", struct.pack("<H", (0xFFFF & reg_val)))
>>> myarray = array.array('B')
>>> myarray.append(reg_val_msb)
>>> myarray.append(reg_val_lsb)

Is there a better/more efficient/more pythonic way of accomplishing the same thing?

A: For non-complex numbers you can use divmod(a, b), which returns a tuple of the quotient and remainder of arguments.
The following example uses map() for demonstration purposes. In both examples we're simply telling divmod to return a tuple (a/b, a%b), where a=0xABCD and b=256.
>>> map(hex, divmod(0xABCD, 1<<8)) # Add a list() call here if your working with python 3.x
['0xab', '0xcd']

# Or if the bit shift notation is distrubing:
>>> map(hex, divmod(0xABCD, 256))

Or you can just place them in the array:
>>> arr = array.array('B')
>>> arr.extend(divmod(0xABCD, 256))
>>> arr
array('B', [171, 205])

A: (using python 3 here, there are some nomenclature differences in 2)
Well first, you could just leave everything as bytes.  This is perfectly valid:
reg_val_msb, reg_val_lsb = struct.pack('<H', 0xABCD)

bytes allows for "tuple unpacking" (not related to struct.unpack, tuple unpacking is used all over python).  And bytes is an array of bytes, which can be accessed via index as you wanted.
b = struct.pack('<H',0xABCD)

b[0],b[1]
Out[52]: (205, 171)

If you truly wanted to get it into an array.array('B'), it's still rather easy:
ary = array('B',struct.pack('<H',0xABCD))
# ary = array('B', [205, 171])

print("0x%X" % ary[0])
# 0xCD

A: You can write your own function like this.
def binarray(i):
    while i:
        yield i & 0xff
        i = i >> 8

print list(binarray(0xABCD))
#[205, 171]


text:
Q: JSON Data types passed through an API In a JSON formatted file there are 8 data types that I am aware of.

*

*Number

*String

*Boolean

*Array

*Value

*Object

*Whitespace

*Null

I know in a JSON formatted file numeric values do not need double quotes and strings do. My question is when data is sent using any API how do the data types get parsed. If you send a Boolean in quotes does that get interpreted as a string or a Boolean and more specific does a Boolean of 0 or 1 get processed as a numeric value and T or F a string? The same would go for Whitespace and Null would the Whitespace get processed as a empty string and a null just pass as a null string.

A: In all JSON APIs, false and true are parsed as booleans, 0 and 1 as numbers, null as null, " " and "" as a strings.
Now when trying to map the data to an existing class, some framework may take the liberty to provide automatic conversions from one type to another, but I wouldn't count on it.
Also, you can sometimes customise the mapping to a class and do whatever you want.
To summarise, it all depends on the framework your using.


text:
Q: javascript google maps only one function works at once, rest not At start I want to tell I don't have experience with JavaScript. I found the script and change to what I want. I try to load google map on two diffrent views (I work on Codeigniter) but only one Map load. When I go to second view the map dont display. Heres the code:
header:

first view:

<input type="hidden" id="lat" name="lat"/>

<input type="hidden" id="lng" name="lng"/>

second view:

<input type="hidden" id="lat" name="lat"/>

<input type="hidden" id="lng" name="lng"/>

footer:

And I notice when I type at first Rejestracja here:
mapa = new GMap2(document.getElementById("Rejestracja" || "doMeeting"));

Map load in view where is "Rejestracja" id but in second view where is id "doMeeting" not. If I reverse this element its opposite situation

A: In JavaScript, || can be used as an "OR" operator, or it can be used to return the first non "falsy" value. In your code:
mapa = new GMap2(document.getElementById("Rejestracja" || "doMeeting"));

The function call to document.getElementId will only retrieve "Rejestracja" because it is the first value in the condition that returns a truthy value. (truthy means not false, null, undefined, 0, empty string or NaN).
I am not sure how the google maps api works, but if it cannot take two DOM elements, you will need to store each map in its own variable:
var map1 = new GMap2(document.getElementById("Rejestracja"));
var map2 = new GMap2(document.getElementById("doMeeting"));

Or extract the code into its own function and pass in each DOM element.
Update: here is an example of what I mean - this will only work if your mapa variable is not used outside of the function where it is initialized.
function mapaStart()
{
    if(GBrowserIsCompatible())
    {
        var map1 = new GMap2(document.getElementById("doMeeting"));
        var map2 = new GMap2(document.getElementById("Rejestracja"));
        initializeMap(map1);
        initializeMap(map2);
    }
}

function initializeMap (mapa)
{
    mapa.setCenter(new GLatLng(52.348763181988076, 18.61083984375), 6, G_HYBRID_MAP);
    mapa.addControl(new GLargeMapControl());
    mapa.addControl(new GMapTypeControl());

    // remainder of original mapaStart function goes here
}

I hope this helps!


text:
Q: How to make phone input with country code in React JS For reference you can see this image I need something like this
I am new and learning React JS and I want to take the phone input in +917896541230 or +91 78965412330 in this format, not in this +91 (123)789 654 0 or not in any other format  ("I gave +91 as a exam of country code but it will accept all countries code around the world")  because then number stored in the database is in above format. I try to include jQuery but it did not work. I don't understand How to do this the npm packages I got all are in a different format which does not work for me.
This is my code

import React from 'react'
import firebase from './firebase'
import "./App.css";
import { getDatabase, ref, child, get } from "firebase/database";
// import PhoneInput from 'react-phone-number-input'

class Login extends React.Component {

    // jQuery code

    // var phoneNumber = window.intlTelInput(document.querySelector("#phoneNumber"), {
    //         separateDialCode: true,
    //         preferredCountries:["in"],
    //         hiddenInput: "full",
    //         utilsScript: "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js"
    //         });

    //         $("#getCode").click(function() {
    //         var full_num = phoneNumber.getNumber(intlTelInputUtils.numberFormat.E164);
    //         $("input[name='phoneNumber[full]'").val(full_num);

    //         localStorage.setItem("Phone_No", full_num)
    //         });
    //
  handleChange = (e) =>{
    const {name, value } = e.target
    this.setState({
        [name]: value
      })
      this.setState({ phoneNumber: value }, () => {
        console.log(this.state.phoneNumber);
      });
  }
  configureCaptcha = () =>{
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {

        // reCAPTCHA solved, allow signInWithPhoneNumber.

        this.onSignInSubmit();
        // console.log("Recaptca varified")
      },
      //  defaultCountry: "IN"
     }
    );
  }
  onSignInSubmit = (e) => {
    e.preventDefault()
    this.configureCaptcha()
    const phoneNumber =  this.state.mobile
    const appVerifier = window.recaptchaVerifier;
    const dbRef = ref(getDatabase());
    get(child(dbRef, `Users/${phoneNumber}`)).then((snapshot) => {
      if (snapshot.exists()){
        firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)

        .then((confirmationResult) => {

          // SMS sent. Prompt user to type the code from the message, then sign the
          // user in with confirmationResult.confirm(code).

          window.confirmationResult = confirmationResult;

          alert('An OTP has been sent to your registered mobile number')
          localStorage.setItem("Phone_No", phoneNumber )
          console.log(localStorage.getItem('Phone_No'));

        }).catch((error) => {

          console.error(error);
          alert("Oops! Some error occured. Please try again.")
        });
      }
      else{
        alert('Sorry, this mobile number is not registered with us. Please use your registered mobile number.');
      }

  })
  }
  onSubmitOTP = (e) =>{
    e.preventDefault()
    const code = this.state.otp
    console.log(code)
    window.confirmationResult.confirm(code).then((result) => {
      // User signed in successfully.
      const Users = result.user;
      console.log(JSON.stringify(Users))
      this.props.history.push("/home");
    }).catch((error) => {
      alert("You have entered wrong code")
     });
  }

  render() {
    return (

Login Form

Limtless Water. From Unlimited Air.

        <form onSubmit={this.onSignInSubmit}>

          {/* <PhoneInput */}

          Mobile Number

          {/* for="phoneNumber"  */}

          <input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange}/>

          <button type="submit">Submit</button>

        </form>

        <form onSubmit={this.onSubmitOTP}>
        Code

        {/* for="code" */}

          <input type="number" name="otp" placeholder="Enter The 6 Digit OTP" required onChange={this.handleChange}/>

          <button type="submit">Submit</button>

        </form>

    )
  }
}
export default Login;

A: try React Moduel
first install package

*

*npm i react-phone-input-2
second require it on page

*import PhoneInput from 'react-phone-input-2'
third import css

*import 'react-phone-input-2/lib/style.css'

in side return (
<PhoneInput
country={"in"}
/>
)


text:
Q: What is new(this) mean in Javascript Function? I found this code, to add before and after the ability to run a function, searched and don't know, what is new(self) mean there?
Function.prototype.before = function(fn) {
  const self = this
  return function() {
    fn.apply(new(self), arguments)
    return self.apply(new(self), arguments)
  }
}
Function.prototype.after = function(fn) {
  const self = this
  return function() {
    self.apply(new(self), arguments)
    return fn.apply(new(self), arguments)
  }
}

...

const validate = function(){
  // ...
}
const formSubmit = function() {
  // ...
  ajax( 'http:// xxx.com/login', param )
}
submitBtn.onclick = function() {
  formSubmit.before( validate )
}


text:
Q: C++ templated, statically allocated array I'm trying to do something like this for a project...
template <class N>
class MyClass
{
    float properties[N];
};
Is there anyway to accomplish this in C++?

A: What you need is called value template parameter:
template <size_t N> class MyClass { float properties[N]; };
        //^^^^^^ note this

Now you can instantiate this class template, passing any non-negative integral value as template argument. For example,
MyClass<10> c1;  //N=10
MyClass<100> c1; //N=100

You can pass const expression also as:
const size_t size = 200;
MyClass<size>  c2; //N=200


text:
Q: Bash script invoking subshell due to pipping lets say we have this script
#!bin/bash
count=0
count2=0
find "$1" -type f | while read file; do
count=$(($count +1))
find "$1" -type f | while read file2; do
count2=$(($count2 +1))
done
done
echo "count: $count" # prints 0
echo "count2: $count2" # prints 0

Now lets do a modification as follow:
#!bin/bash
count=0
count2=0
find "$1" -type f | {
while read file; do
count=$(($count +1))
find "$1" -type f | {
while read file2; do
count2=$(($count2 +1))
done
}
done
echo "count: $count" # prints some number
echo "count2: $count2" # prints 0
}

i know the problem lies in the subshell invoked by the pipe. The variables inside the subshell changes just inside the subshell and the changed values are not accessible from the main shell ( or at least something similar to this )
So my question is, is there any way to fix this? so that count2 prints its changed result ? ( other than writing and reading to a temp file, or changing the code to for loops ).
Thanks.

A: You can use process substitution to avoid piping and hence creating subshell:
#!bin/bash
count=0
count2=0

while read -r file; do
   ((count++))
   while read -r file2; do
      ((count2++))
   done < <(find "$1" -type f)
done < <(find "$1" -type f)

echo "count: $count"
echo "count2: $count2"

A: Sure. Avoid the pipes; avoid the subshells:
#!bin/bash
count=0
count2=0
while read file; do
  count=$(($count +1))
  while read file2; do
    count2=$(($count2 +1))
  done < <(find "$1" -type f)
done < <(find "$1" -type f)
echo "count: $count"
echo "count2: $count2"

When you have a pipe, as you know, you have an implied subshell. Here, though, we just have a redirection from a file. <(command) is a process substitution – it creates a named pipe or /dev/fd filehandle with the output (or input if you use >()) of the given process. Then it expands to the name of the file.
$ echo <(echo)
/dev/fd/63

The space, therefore, is important. This is not the same as
while read; do …; done << (command)

That's just a syntax error!
What we're doing is closer to this:
find "$1" -type f > tmpfile
while read; do …; done < tmpfile
rm tmpfile

Except the file creation and cleanup are handled by the system.
Of course, if you just want to count files:
find "$1" -type f -exec bash 'echo $#' _ {} + # Works up to ARG_MAX

# If number of files > ARG_MAX:
sum() {
  local IFS=+
  bc <<< "$*"
}
sum $( find "$1" -type f -exec bash 'echo $#' _ {} + )

A: If you are using bash 4, you can eliminate the calls to find along with the pipes.
#!bin/bash
count=0
count2=0
shopt -s globstar
for file in **/*; do
    [[ -f $file ]] || continue
    (( count++ ))
    for file2 in **/*; do
        [[ -f $file2 ]] || continue
        (( count2++ ))
    done
done

echo "count: $count" # prints some number
echo "count2: $count2" # prints 0


text:
Q: java -xvf test.jar not working i tried to extract the test.jar
command is executing successfully but no output.
user@host:home/test->ll
drwxr-xr-x 107 user abc  6040 Apr  4 09:55 ..
drwxr-xr-x   2 user abc    26 Apr  4 10:06 .
-rw-r--r--   1 user abc 51241 Apr  4 10:06 test.jar
user@host:home/test->jar -xvf test.jar
user@host:home/test->ll
total 262
drwxr-xr-x 107 user abc  6040 Apr  4 09:55 ..
drwxr-xr-x   2 user abc    26 Apr  4 10:06 .
-rw-r--r--   1 user abc 51241 Apr  4 10:06 test.jar

Kindly help me to resolve this
Actual Requirement:
Need to extract and access a resource in jar file.

A: According to Oracle Java toutorials:
https://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html
You should unpack it with:
jar xfv test.jar

Without '-' sign.

x option indicates that you want to extract files from the JAR archive.
f options indicates that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
v is verbose

A: try to this command also unzip test.jar and below commands help you view some file without extract all the files.
unzip -q -c test.jar META-INF/MANIFEST.MF


text:
Q: How to monitor the performance of InfluxDb and Apache Kafka I am creating a system that uses Apache Kafka queue and InfluxDB database. The system collects measurement data from sensors. I would like to know how I could monitor:

*

*database load,

*database performance,

*execution time of queries performed on the database

*length of the queue in Topic.

A: 1-3 : Try Prometheus Metrics exposed by the server. You can either install a separate Prometheus Server for monitoring, or I think you can use Telegraf to scrape the data to write metrics back to InfluxDB.
4 - Topic sizes are hard to determine, but you can add Prometheus JMX Exporter to the Kafka Brokers or (JVM-based) consumers to (partially) construct such useful information. Tools like Burrow also exist for exporting Kafka Consumer Lag. Then again, setup Prometheus server / Telegraf to scrape these endpoints.


text:
Q: Postfix fails to install in MySQL 5.7 I am trying to install postfix in my server with
Centos7
MySQL 5.7
Unfortunately  it seems to be they are incompatible.  Why?
Here the error message. Is there a way around this ?
[root@doc ~]# yum --enablerepo=remi install postfix
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centos.sonn.com
 * epel: mirror.nus.edu.sg
 * extras: centos.sonn.com
 * remi: mirrors.thzhost.com
 * updates: centos.sonn.com
Resolving Dependencies
--> Running transaction check
---> Package postfix.x86_64 2:2.10.1-6.el7 will be installed
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: 2:postfix-2.10.1-6.el7.x86_64
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: 2:postfix-2.10.1-6.el7.x86_64
--> Running transaction check
---> Package MariaDB-shared.x86_64 0:10.0.17-1.el7.centos will be installed
--> Processing Dependency: MariaDB-common for package: MariaDB-shared-10.0.17-1.el7.centos.x86_64
--> Running transaction check
---> Package MariaDB-common.x86_64 0:10.0.17-1.el7.centos will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=====================================================================================================================================================================================================
 Package                                          Arch                                     Version                                                   Repository                                 Size
=====================================================================================================================================================================================================
Installing:
 postfix                                          x86_64                                   2:2.10.1-6.el7                                            base                                      2.4 M
Installing for dependencies:
 MariaDB-common                                   x86_64                                   10.0.17-1.el7.centos                                      mariadb                                    23 k
 MariaDB-shared                                   x86_64                                   10.0.17-1.el7.centos                                      mariadb                                   1.2 M

Transaction Summary
=====================================================================================================================================================================================================
Install  1 Package (+2 Dependent packages)

Total size: 3.7 M
Installed size: 13 M
Is this ok [y/d/N]: y
Downloading packages:
Running transaction check
Running transaction test

Transaction check error:
  file /usr/share/mysql/charsets/Index.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/armscii8.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/ascii.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/cp1250.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/cp1256.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/cp1257.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/cp850.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/cp852.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/cp866.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/dec8.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/geostd8.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/greek.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/hebrew.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/hp8.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/keybcs2.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/koi8r.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/koi8u.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/latin1.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/latin2.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/latin5.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/latin7.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/macce.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/macroman.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /usr/share/mysql/charsets/swe7.xml from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-common-5.7.6-0.3.m16.el6.x86_64
  file /etc/my.cnf from install of MariaDB-common-10.0.17-1.el7.centos.x86_64 conflicts with file from package mysql-community-server-5.7.6-0.3.m16.el6.x86_64

Error Summary
-------------

A: You have configured your system with repositories for both MySQL 5.7 and MariaDB 10.0. This is not going to work; these packages cannot be run side-by-side on the same system. You will need to choose one or the other.
Obviously since CentOS is already expecting to use MariaDB and for various other reasons, you should probably choose MariaDB rather than MySQL.


text:
Q: Remove element from list when using enumerate() in python Object is a decoded json object that contains a list called items.
obj = json.loads(response.body_as_unicode())

for index, item in enumerate(obj['items']):
   if not item['name']:
       obj['items'].pop(index)

I iterate over those items and want to remove an item when a certain condition is met. However this is not working as expected. After some research I found out that one cannot remove items from a list while at the same time iterating of this list in python. But I cannot apply the mentioned solutions to my problem. I tried some different approaches like
obj = json.loads(response.body_as_unicode())
items = obj['items'][:]

for index, item in enumerate(obj['items']):
   if not item['name']:
       obj['items'].remove(item)

But this removes all items instead of just the one not having a name. Any ideas how to solve this?

A: Use a while loop and change the iterator as you need it:
obj = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# remove all items that are smaller than 5
index = 0
# while index in range(len(obj)): improved according to comment
while index < len(obj):
    if obj[index] < 5:
        obj.pop(index)
        # do not increase the index here
    else:
        index = index + 1

print obj

Note that in a for loop the iteration variable cannot be changed. It will always be set to the next value in the iteration range. Therefore the problem is not the enumerate function but the for loop.
And in the future please provide a verifiable example. Using a json object in the example is not sensible because we do not have this object.

A: Don't remove items from a list while iterating over it; iteration will skip items as the iteration index is not updated to account for elements removed.
Instead, rebuild the list minus the items you want removed, with a list comprehension with a filter:
obj['items'] = [item for item in obj['items'] if item['name']]

or create a copy of the list first to iterate over, so that removing won't alter iteration:
for item in obj['items'][:]:  # [:] creates a copy
   if not item['name']:
       obj['items'].remove(item)

You did create a copy, but then ignored that copy by looping over the list that you are deleting from still.


text:
Q: learning AWS components and tutorials My questions says it all, Looking forward to learn about AWS components ,creating instances and may be with screenshots of the website to give more better look,some videos,
Any website that could help me?
I am a quick learner but honestly Amazon website is just full of content with nothing catchy and understandable.

A: Not sure what your use case is or coding background, but if PHP here's a nice start:
http://docs.aws.amazon.com/aws-sdk-php-2/guide/latest/index.html
Also try YouTube AWS channel as suggested above. The various heads of the web service groups post videos and webinars.


text:
Q: Confused about the different between these two assignment operators I have the following class which is called CoordinatesList. It contains a dynamic array of Coordinates, where each coordinate has 3 integers; x,y, and z.
In the class CoordinatesList, I have two different member operator=, I am slightly confused about what is the difference between them?
Will it work the same if I inherited the class coordinates in the class CoordinatesList
class Coordinates {//this is a complete class, do not modify it.
public:
    Coordinates() {
        x = new int; y = new int; z = new int;
        *x = *z = *y = 0;
    }
    Coordinates(int _x, int _y, int _z) {
        x = new int; y = new int; z = new int;
        *x = _x;
        *z = _y;
        *y = _z;
    }
    Coordinates(const Coordinates& rhs) { // copy constructor
        x = new int; y = new int; z = new int;
        *x = *(rhs.x);
        *y = *(rhs.y);
        *z = *(rhs.z);
    }
    ~Coordinates() {
        delete x; delete y; delete z;
    }
    void operator=(const Coordinates& rhs) {//simplified operator=
        *x = *(rhs.x);
        *y = *(rhs.y);
        *z = *(rhs.z);
    }
    int getx() const { return *x; }
    int gety() const { return *y; }
    int getz() const { return *z; }
    void setx(int _x) { *x = _x; }
    void sety(int _y) { *y = _y; }
    void setz(int _z) { *z = _z; }
    friend ostream& operator<< (ostream& out, const Coordinates& rhs) {
    out << "[" << *(rhs.x) << "," << *(rhs.y) << "," << *(rhs.z) << "]" << endl;
    return out;
    }

private:
    int *x, *y, *z;
}; //--------------------------------------------------------------

class CoordinatesList {
public:

    /*CoordinatesList &  operator=(const CoordinatesList &rhs)
    {

        if (size != rhs.size)
        {
            delete[] list;
            size = rhs.size;
            list = new Coordinates[size];
        }
        for (int i = 0; i < size; i++)
        {
            list[i].Coordinates::operator=(rhs.list[i]);
        }
        return *this;

    } */

    CoordinatesList operator=(const CoordinatesList & rhs)
    {

        //check if sizes are differernt
        if (size != rhs.size)
        {
            delete[] list; //this calls ~coordinates
            size = rhs.size;
            list = new Coordinates[size];
        }
        //copy content
        for (int i = 0; i < size; i++) {
            //list[i] = rhs.list[i];
//will work as operator= is defined for Coordinates
            list[i].setx(rhs.list[i].getx());
            list[i].sety(rhs.list[i].gety());
            list[i].setz(rhs.list[i].getz());
        }
        return *this;
    }
    private:
    Coordinates * list;
    int size;
};

A: using CL = CoordinatesList; to save on typing.
The difference is that one returns a reference, one returns a copy.
The idiomatic way is to return a reference to *this, so use this one:
CL& operator=(const CL& rhs){/*...*/ return *this;}
Note that having both versions defined will result in a compiler error because functions cannot differ only by their return values.
Usage of operator=:
CL a = CL(<args>);// (1)
CL b,c;
b = a; // (2)
b.operator=(a); //(3)
c = b = a; // (4)
c.operator=(b.operator=(a)); // (5)

(1) Does not call any CL::operator= but a constructor CL::CL(<args>). An object is being created, so a constructor must be called no matter the equal sign.
(2) Is only syntactic sugar for (3). Calls CL::operator= and discards any returned value.
(4) Again, its only syntactic sugar for (5). First the right operator= is evaluated and the returned value is passed to the left operator= as its argument. In this case having operator= returning a copy will indeed make a copy. That's the reason why the second option is preferred as it does not incur this additional and unneeded cost. Also this should be a good explanation for why  the function returns anything at all, if it returned void then this syntax would not be possible.


text:
Q: GMail API - messages().list() only returns message IDs The list() method only returns a list of message IDs without any other message metadata.
There are SO posts from 2014 and 2016, but the official documentation states that the response is a list of user.messages resource ...
Is the documentation wrong or is there any other way to do this? I understand that bringing the entire message in a "list" call is not efficient for a REST API call - but maybe returning "some" metadata would make sense (e.g. output of service.users().messages().get(..., format='metadata')) as opposed to making a call to list() and then, for every message, make a get(..., format='metadata')
Thanks!
M

A: gmail.users.messages.get({
auth: auth,
userId: 'me',
id: messageid,
format: "raw"
}, function (err, response) {
});

You have to call the above api with each messageid. The response will be raw data for corresponding email


text:
Q: Regex for last point or comma in string I'm looking for a regex with gives me the last occurance of a point or a comma in a string (whichever one is the further back)
From what I googled myself I got this one ([,\.])(?!.*\1) but this gives me two results per string which isnt what I wanted.
I hope somebody can help me as I'm struggeling for the correct keyword to google for.
Cheers and thank you very much in advance

A: This pattern ([,\.])(?!.*\1) matches the last comma or dot asserting not any of the 2 being present on the right anymore.
That can occur for both a dot and a comma so you could possibly get 2 matches.
If you want a single match, you can match one of them and assert no more occurrences of either one of them to the right using a negated character class [^,.\r\n]* matching any char except the listed characters.
Note that you don't need the capture group for a match only.
[,.](?=[^,.\r\n]*$)

See a regex demo.

A: In this regex pattern the first capturing group is the last comma or point in each line.
We achieve this by looking for a comma or point and not allowing a point, comma or line ending between it and the end of the line.
([.,])[^.,\n\r]*$


text:
Q: I was trying to connect the oracle 10g database with C# console application. I get error of invalid username/password even though they are right I was trying to connect the oracle 10g database with C# console application. I get error of invalid username/password even though the credentials are correct.
Here is my code:
string s = @"provider=MSDAORA;datasource=orcl;username=system;password=PASS";

OleDbConnection conn = new OleDbConnection();

conn.ConnectionString = s;

conn.Open();  // Error in this line (ORA-01017: invalid username/password; logon denied)


text:
Q: Azure ML workbench failed installing on Windows 10 Enterprise Error installing component: azure_cli_ml_cliextension.windows "The action failed catastrophically with
Microsoft.MachineLearning.Installer.Engine.Actions.RegisteredActions.AzureCliException: Unable to get list of currently installed Azure CLI extensions
at
Microsoft.MachineLearning.Installer.Engine.Actions.RegisteredActions.InstallAzureCliExtensionAction.d__23.MoveNext() in C:\swarm\workspace\Installer-1.2\Installer.Engine\Actions\RegisteredActions\InstallAzureCliExtensionAction.cs:line 97
from there everything is stops....

A: Workbench is a preview product and issues may occur. Please try and get a newer exe and try again. It also seems like you have azure powershell issues here which I would have expected to be taken care of by the installer, but perhaps you can try and install azure powershell first.

A: Not your issue I think but i'll pop it here in case others have problems. For me the installer failed to do anything though it claimed to be installed. Turns out it had just dropped the files and the installer exe needed to be run manually. The installer exe was dropped here

C:\Users{User}\AppData\Local\AmlInstaller\Installer.Windows.exe

Non-obvious to tired developers trying to do a bit extra at the end of a busy day


text:
Q: Show that C is path-connected Let $C=\{(x,y)\mid x^2-y^2\le 3, x\ge 0\}$
I want to show that $\forall x,y \in C$ there a exist a path between them in order to show that $C$ is path-connected. Any ideas how? intuitively it is very clear. it looks like an half hourglass. But I'm having a very hard time formalizing it.
Thanks in advance!

A: Hint: prove that for each $P=(x,y)\in C$, there exists a path from $P$ to some point on the $y$-axis.


text:
Q: Hbase Row filtering doesn't work I have a Hbase table where my row key looks like as below mentioned
        12345678912:::timestamp:::1234567891:::john         cf:somedata
        12345678912:::timestamp:::1234567891:::smith        cf:somedata
        12345678912:::timestamp:::1234567891:::lotta        cf:somedata

Now, i want to filter out some rows using row key regex like as mentioned below
scan 'mytable', {STARTROW=>'.*:::starttimestamp:::.*:::john', STOPROW=>'.*:::endtimestamp:::.*:::john'}

But this doesn't seem to work either and i understood that we cannot use regex in rowkey by some study.
How can i use FuzzyRowFilter for this operation in hbase shell? Does this filter really help in my case?
I know that i can use SingleColumnValue filter for specific rows but my row key also matter here for me.

A: You requirement is range scan on row key.
It looks like, the range works for the entire string. For example, the following works.
scan 'scanRangeTest',{STARTROW=>'1234|20-10-2014|john', STOPROW=>'1234|24-10-2014|john'}

You will get all records for john between two timestamps. Point here is you should build the start and stop parameters.
There is a regex comparator. You can use it with RowKey Filter. Refer here. However, when you use regex in that manner, you will get all records which match, but it would not give you the range option, which might be important to you.
Alternatives to above 'rowfilter with regex comparator' are secondary indexes, and FuzzyRowFilter. These help in getting faster scans by skipping certain records. However, the range option is still not there. So you can take your call based on your requirement.
Solution to your problem
Get date range and for a specific user name(john), and some id's(12345678912, 1234567891). In my scan command, range works only for full row key and not regex. So as long as you have the name and id's common(you can get this params as usual) and then only change the time stamp(you can add this as your requirement), and using all three, you build entire row key, then u can use start and stop row. I hope I cleared your requirement.
create 'scanRangeTest', {NAME => 'srt', REPLICATION_SCOPE => '1'}
put 'scanRangeTest','1234|20-10-2014|john', 'srt:name','John Details'
put 'scanRangeTest','1235|21-10-2014|smita', 'srt:name','Smita Details'
put 'scanRangeTest','1236|22-10-2014|lotta', 'srt:name','Lotta Details'
put 'scanRangeTest','1234|23-10-2014|john', 'srt:name','John Details sec timestamp'
put 'scanRangeTest','1237|23-10-2014|john', 'srt:name','Ram Details'

scan 'scanRangeTest',{STARTROW=>'1234|20-10-2014|john', STOPROW=>'1234|24-10-2014|john'}

Output
ROW                                      COLUMN+CELL
 1234|20-10-2014|john                    column=srt:name, timestamp=1446045032763, value=John Details
 1234|23-10-2014|john                    column=srt:name, timestamp=1446045054544, value=John Details sec timestamp


text:
Q: rename command is not overwriting as it should by default, how do I force overwrite? I have a bash script that uses the rename command as follows:
sudo rename 's/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/Date-$1-$2-$3__Time-$4:$5:$6/' 2019*

According to the rename man page the command should overwrite by default and not overwrite by using the -o flag. But when I run the script it is not overwriting existing files. However I get an error thrown back and the duplicate files do not get any other processing done by the script.

Renaming Files
20190710220231.WAV not renamed: Date-2019-07-10__Time-22:02:31.WAV already exists
20190710220300.WAV not renamed: Date-2019-07-10__Time-22:03:00.WAV already exists
20190710220338.WAV not renamed: Date-2019-07-10__Time-22:03:38.WAV already exists
20190710220349.WAV not renamed: Date-2019-07-10__Time-22:03:49.WAV already exists

Frustrated, I tried to just use the mv command but gives me a different error:

mv: target '20190710222433.WAV' is not a directory

So I added a / and get the same error. Any advice?

A: you can use the option -f to force over write existing files:
rename -f ...

man rename:
-f, --force
               Over write: allow existing files to be over-written.


text:
Q: Is there a way to do it faster? ladder have around 15000 elements, this code snippet performed in 5-8sec, is there any way to do it faster? I try do it without checking for duplicate and without creating accs list and time was down to 2-3sec, but I don't need duplicate in csv file.
I work in python 2.7.9
accs =[]
with codecs.open('test.csv','w', encoding="UTF-8") as out:
        row = ''
        for element in ladder:
                if element['account']['name'] not in accs:
                        accs.append(element['account']['name'])
                        row += element['account']['name']
                        if 'twitch' in element['account']:
                                row +=  "," + element['account']['twitch']['name'] + ","
                        else:
                                row += ",,"
                        row += str(element['account']['challenges']['total']) + "\n"
        out.write(row)

A: You can't do much about the loop, since you need to go through every element in ladder after all. However, you can improve this membership test:
if element['account']['name'] not in accs:

Since accs is a list, this will essentially loop through all items of accs and check if the name is in there. And you loop for every element in ladder, so this can easily become very inefficient.
Instead, use a set instead of a list for accs as this will give you a constant membership lookup. So you reduce your algorithm from a quadratic complexity to a linear complexity. For that, just use accs = set() and change your code to use accs.add() instead of append.
Another issue is that you are doing string concatenation. Every time you do someString + "something" you are throwing away that string object and create a new one. This can become inefficient for a high number of operations too. Instead, use a list here to collect all the elements you want to write, and then join them:
row = []
row.append(element['account']['name'])
if 'twitch' in element['account']:
    row.append(element['account']['twitch']['name'])
else:
    row.append('')
row.append(str(element['account']['challenges']['total']))

out.write(','.join(row))
out.write('\n')

Alternatively, since you are writing to a file anyway, you could just call out.write multiple times with each string part.
Finally, you could also look into the csv module if you are interested in writing out CSV data.

A: seen    = set()
results = []

for user in ladder:
    acc  = user['account']
    name = acc['name']
    if name not in seen:
        seen.add(name)
        twitch_name = acc['twitch']['name'] if "twitch" in acc else ''
        challenges  = acc['challenges']['total']
        results.append("%s,%s,%d" % (name, twitch_name, challenges))

with codecs.open('test.csv','w', encoding="UTF-8") as out:
    out.write("\n".join(results))