Programs & Examples On #Vb6 migration

This tag is for questions about migrating existing applications, or legacy code, from Visual Basic 6 to a more modern platform. Unfortunately migration is usually a tricky task. The most common target platforms are VB.NET and C#.

How to get an Android WakeLock to work?

Make sure that mWakeLock isn't accidentally cleaned up before you're ready to release it. If it's finalized, the lock is released. This can happen, for example, if you set it to null and the garbage collector subsequently runs. It can also happen if you accidentally set a local variable of the same name instead of the method-level variable.

I'd also recommend checking LogCat for entries that have the PowerManagerService tag or the tag that you pass to newWakeLock.

How to create custom view programmatically in swift having controls text field, button etc

var customView = UIView()


@IBAction func drawView(_ sender: AnyObject) {

    customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
    customView.backgroundColor = UIColor.black     //give color to the view 
    customView.center = self.view.center  
    self.view.addSubview(customView)
       }

Python: TypeError: cannot concatenate 'str' and 'int' objects

There are two ways to fix the problem which is caused by the last print statement.

You can assign the result of the str(c) call to c as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last print simply with this:

print "a + b as integers: ", c  # note the comma here

in which case

str(c)

isn't necessary and can be deleted.

Output of sample run:

Enter a: 3
Enter b: 7
a + b as strings:  37
a + b as integers:  10

with:

a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b  # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

Example of SOAP request authenticated with WS-UsernameToken

The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.

Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.

Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.

<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
  <S11:Header>
  ...
    <wsse:Security>
      <wsse:UsernameToken>
        <wsse:Username>NNK</wsse:Username>
        <wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
        <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
        <wsu:Created>2003-07-16T01:24:32</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  ...
  </S11:Header>
...
</S11:Envelope>

adding to window.onload event?

This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed

How to use aria-expanded="true" to change a css property

_x000D_
_x000D_
li a[aria-expanded="true"] span{_x000D_
    color: red;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
li a[aria-expanded="true"]{_x000D_
    background: yellow;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

Pass Hidden parameters using response.sendRedirect()

Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.

RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);

The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.

Download/Stream file from URL - asp.net

You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is

    //Create a stream for the file
    Stream stream = null;

    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;

    // Buffer to read bytes in chunk size specified above
    byte[] buffer = new Byte[bytesToRead];

    // The number of bytes read
    try
    {
      //Create a WebRequest to get the file
      HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);

      //Create a response for this request
      HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();

      if (fileReq.ContentLength > 0)
        fileResp.ContentLength = fileReq.ContentLength;

        //Get the Stream returned from the response
        stream = fileResp.GetResponseStream();

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = "application/octet-stream";

        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

        int length;
        do
        {
            // Verify that the client is connected.
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);

                // Flush the data
                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }

Multi-statement Table Valued Function vs Inline Table Valued Function

I have not tested this, but a multi statement function caches the result set. There may be cases where there is too much going on for the optimizer to inline the function. For example suppose you have a function that returns a result from different databases depending on what you pass as a "Company Number". Normally, you could create a view with a union all then filter by company number but I found that sometimes sql server pulls back the entire union and is not smart enough to call the one select. A table function can have logic to choose the source.

Right Align button in horizontal LinearLayout

You should use the Relativelayout instead of Linearlayout as main layout. If you use Relativelayout as main then easily handle the button on right side because relative layout provide us alignParent right, left,top and bottom.

How do you create a UIImage View Programmatically - Swift

Thanks, MEnnabah, just to add to your code where you are missing the = sign in the declaration statement:

let someImageView: UIImageView = {
   let theImageView = UIImageView()
   theImageView.image = UIImage(named: "yourImage.png")
   theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
   return theImageView
}()

Everything else is, all perfect for Swift 3.

How to trigger an event after using event.preventDefault()

If this example can help, adds a "custom confirm popin" on some links (I keep the code of "$.ui.Modal.confirm", it's just an exemple for the callback that executes the original action) :

//Register "custom confirm popin" on click on specific links
$(document).on(
    "click", 
    "A.confirm", 
    function(event){
        //prevent default click action
        event.preventDefault();
        //show "custom confirm popin"
        $.ui.Modal.confirm(
            //popin text
            "Do you confirm ?", 
            //action on click 'ok'
            function() {
                //Unregister handler (prevent loop)
                $(document).off("click", "A.confirm");
                //Do default click action
                $(event.target)[0].click();
            }
        );
    }
);

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

See the wiki article:

In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https.

WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.

That is:

  • HTTPS is a transport layer (point-to-point) security mechanism
  • WS-Security is an application layer (end-to-end) security mechanism.

How to get URL parameter using jQuery or plain JavaScript?

Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:

-- Not depending on any outside libraries, including jQuery

-- Not polluting global function namespace, by extending 'String'

-- Not creating any global data and doing unnecessary processing after match found

-- Handling encoding issues, and accepting (assuming) non-encoded parameter name

-- Avoiding explicit for loops

String.prototype.urlParamValue = function() {
    var desiredVal = null;
    var paramName = this.valueOf();
    window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
        var nameVal = currentValue.split('=');
        if ( decodeURIComponent(nameVal[0]) === paramName ) {
            desiredVal = decodeURIComponent(nameVal[1]);
            return true;
        }
        return false;
    });
    return desiredVal;
};

Then you'd use it as:

var paramVal = "paramName".urlParamValue() // null if no match

What Ruby IDE do you prefer?

On Mac OS X, TextMate is a godsend.

Handling click events on a drawable within an EditText

I've taked the solution of @AZ_ and converted it in a kotlin extension function:

So copy this in your code:

@SuppressLint("ClickableViewAccessibility")
fun EditText.setDrawableRightTouch(setClickListener: () -> Unit) {
    this.setOnTouchListener(View.OnTouchListener { _, event ->
        val DRAWABLE_LEFT = 0
        val DRAWABLE_TOP = 1
        val DRAWABLE_RIGHT = 2
        val DRAWABLE_BOTTOM = 3
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= this.right - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
            ) {
                setClickListener()
                return@OnTouchListener true
            }
        }
        false
    })
}

You can use it just calling the setDrawableRightTouch function on your EditText:

yourEditText.setDrawableRightTouch {
    //your code
}

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Some of the Answers are correct, but in case of working with new xampp or with some one not working other answers try this:

just go to the xampp folder:

xampp/apache/conf/extra/httpd-xampp.c­onf

and if you are trying to access from local ip in your network so change,

 Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

Change to :

 Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require all granted
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

Note: this is just for text, for the security of the xampp has some search....

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

:last is not part of the css spec, this is jQuery specific.

you should be looking for last-child

var first = div.querySelector('[move_id]:first-child');
var last  = div.querySelector('[move_id]:last-child');

Pick images of root folder from sub-folder

../ takes you one folder up the directory tree. Then, select the appropriate folder and its contents.

../images/logo.png

Configuring Git over SSH to login once

Make sure that when you cloned the repository, you did so with the SSH URL and not the HTTPS; in the clone URL box of the repo, choose the SSH protocol before copying the URL. See image below:

enter image description here

Five equal columns in twitter bootstrap

BOOTSTRAP 4

I read all answers and I didn't find "the obvious one". Basically what you need to do is to take any bootstrap column (for example col-2) and edit few values. In this example I am using .col-custom class.

Five equal columns means each one occupies 20%, so: flex:0 0 20% and max-width:20%. The same way you can create other number of columns (7, 9, 11, 84 or whatever you want).

You can create CSS variables with custom width, and use it in your projects. Something like that:

:root {
  --col-custom: 20%;
}

.col-custom {
  flex: 0 0 var(--col-custom);
  max-width: var(--col-custom);
}

Working example:

_x000D_
_x000D_
.col-custom,_x000D_
.col-sm-custom,_x000D_
.col-md-custom,_x000D_
.col-lg-custom,_x000D_
.col-xl-custom {_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-right: 15px;_x000D_
  padding-left: 15px;_x000D_
}_x000D_
_x000D_
.col-custom {_x000D_
  flex: 0 0 20%;_x000D_
  max-width: 20%;_x000D_
}_x000D_
_x000D_
@media (min-width: 576px){_x000D_
  .col-sm-custom {_x000D_
    flex: 0 0 20%;_x000D_
    max-width: 20%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 768px){_x000D_
  .col-md-custom {_x000D_
    flex: 0 0 20%;_x000D_
    max-width: 20%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 992px){_x000D_
  .col-lg-custom {_x000D_
    flex: 0 0 20%;_x000D_
    max-width: 20%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 1200px){_x000D_
  .col-xl-custom {_x000D_
    flex: 0 0 20%;_x000D_
    max-width: 20%;_x000D_
  }_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
.col-custom,.col-sm-custom,.col-md-custom,.col-lg-custom,.col-xl-custom{height:100px;border:1px red solid}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-custom"></div>_x000D_
    <div class="col-sm-custom"></div>_x000D_
    <div class="col-sm-custom"></div>_x000D_
    <div class="col-sm-custom"></div>_x000D_
    <div class="col-sm-custom"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MongoDB or CouchDB - fit for production?

The BBC and meebo.com use CouchDB in production and so does one of my clients. Here is a list of other people using Couch: CouchDB in the wild

The major challenge is to know how to organize your documents and stop thinking in terms of relational data.

What's the use of "enum" in Java?

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Here is some code that shows you how to use the Day enum defined above:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;

            case FRIDAY:
                System.out.println("Fridays are better.");
                break;

            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;

            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

The output is:

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

If you run Planet.class from the command line with an argument of 175, you get this output:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

Source: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Making a triangle shape using xml definitions?

I provide this customView below if you don't want to hack xml. Please have a try.


/**
 * TriangleView
 *
 * @author Veer
 * @date 2020-09-03
 */
class TriangleView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private var triangleColor: Int = 0
    private var direction = Direction.Bottom

    private val paint by lazy {
        Paint().apply {
            isAntiAlias = true
            style = Paint.Style.FILL
            color = triangleColor
        }
    }

    init {
        initStyle(context, attrs, defStyleAttr)
    }

    private fun initStyle(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.TriangleView, defStyleAttr, 0)
        with(ta) {
            triangleColor =
                getColor(R.styleable.TriangleView_triangle_background, Color.parseColor("#000000"))

            val directionValue =
                getInt(R.styleable.TriangleView_triangle_direction, Direction.Bottom.value)
            direction = when (directionValue) {
                Direction.Top.value -> Direction.Top
                Direction.Bottom.value -> Direction.Bottom
                Direction.Left.value -> Direction.Left
                Direction.Right.value -> Direction.Right
                else -> Direction.Bottom
            }

            recycle()
        }
    }

    override fun onDraw(canvas: Canvas) {
        calculatePath(direction).let {
            canvas.drawPath(it, paint)
        }
    }

    private fun calculatePath(direction: Direction): Path {
        var p1: Point? = null
        var p2: Point? = null
        var p3: Point? = null

        val width = width
        val height = height

        when (direction) {
            Direction.Top -> {
                p1 = Point(0, height)
                p2 = Point(width / 2, 0)
                p3 = Point(width, height)
            }
            Direction.Bottom -> {
                p1 = Point(0, 0)
                p2 = Point(width / 2, height)
                p3 = Point(width, 0)
            }
            Direction.Left -> {
                p1 = Point(width, 0)
                p2 = Point(0, height / 2)
                p3 = Point(width, height)
            }
            Direction.Right -> {
                p1 = Point(0, 0)
                p2 = Point(width, height / 2)
                p3 = Point(0, height)
            }
        }

        val path = Path()
        path.moveTo(p1.x.toFloat(), p1.y.toFloat())
        path.lineTo(p2.x.toFloat(), p2.y.toFloat())
        path.lineTo(p3.x.toFloat(), p3.y.toFloat())
        return path
    }

    private enum class Direction(val value: Int) {
        Top(0),
        Bottom(1),
        Left(2),
        Right(3)
    }
}

<declare-styleable name="TriangleView">
    <attr name="triangle_direction" format="enum">
        <enum name="top" value="0" />
        <enum name="bottom" value="1" />
        <enum name="left" value="2" />
        <enum name="right" value="3" />
    </attr>
    <attr name="triangle_background" format="reference|color" />
</declare-styleable>

Unable to install Android Studio in Ubuntu

The Problem is caused by mksdcard not being installed correctly.

if you are running 64 bit, do this to fix the mksdcard problem.

    sudo dpkg --add-architecture amd64
    sudo apt-get update
    sudo apt-get install libncurses5:amd64 libstdc++6:amd64 zlib1g:amd64

and 32 bit:

    sudo dpkg --add-architecture i386
    sudo apt-get update
    sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386

In SDK 6.0, the error message is different but means the same thing.

    Unable to run mksdcard

manage.py runserver

I was struggling with the same problem and found one solution. I guess it can help you. when you run python manage.py runserver, it will take 127.0.0.1 as default ip address and 8000. 127.0.0.0 is the same as localhost which can be accessed locally. to access it from cross origin you need to run it on your system ip or 0.0.0.0. 0.0.0.0 can be accessed from any origin in the network. for port number, you need to set inbound and outbound policy of your system if you want to use your own port number not the default one.

To do this you need to run server with command python manage.py runserver 0.0.0.0:<your port> as mentioned above

or, set a default ip and port in your python environment. For this see my answer on django change default runserver port

Enjoy coding .....

MVC: How to Return a String as JSON

The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object.

What you are passing to the controller's Json method, though, is a JSON-formatted string object, so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem).

I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available.

return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here, 
//  or if that is done automatically

Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.

Case insensitive std::string.find()

wxWidgets has a very rich string API wxString

it can be done with (using the case conversion way)

int Contains(const wxString& SpecProgramName, const wxString& str)
{
  wxString SpecProgramName_ = SpecProgramName.Upper();
  wxString str_ = str.Upper();
  int found = SpecProgramName.Find(str_);
  if (wxNOT_FOUND == found)
  {
    return 0;
  }
  return 1;
}

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Watching this course https://app.pluralsight.com/library/courses/angular-2-getting-started-update/discussion

The author explains that new version of JavaScript has for of and for in, the for of is to enumerate objects and the for in is to enumerate the index of the array.

What is the difference between Hibernate and Spring Data JPA

Spring Data is a convenience library on top of JPA that abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name); that will be parsed in runtime and converted into appropriate JPA queries.

Its placement atop of JPA makes its use tempting for:

  1. Rookie developers who don't know SQL or know it badly. This is a recipe for disaster but they can get away with it if the project is trivial.

  2. Experienced engineers who know what they do and want to spindle up things fast. This might be a viable strategy (but read further).

From my experience with Spring Data, its magic is too much (this is applicable to Spring in general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data. For example, check this issue that led to hours of investigation/swearing:

 public TourAccommodationRate createTourAccommodationRate(
        @RequestBody TourAccommodationRate tourAccommodationRate
    ) {
        if (tourAccommodationRate.getId() != null) {
            throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
        }

        // This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
        // when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
        // information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
        // code creating the corresponding slim model. By detaching the entity from the persistence context we
        // force the ORM to re-fetch it from the database instead of taking it from the cache

        tourAccommodationRateRepository.save(tourAccommodationRate);
        entityManager.detach(tourAccommodationRate);
        return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
    }

I ended up going lower level and started using JDBI - a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.

How to correctly display .csv files within Excel 2013?

I know that an answer has already been accepted, but one item to check is the encoding of the CSV file. I have a Powershell script that generates CSV files. By default, it was encoding them as UCS-2 Little Endian (per Notepad++). It would open the file in a single column in Excel and I'd have to do the Text to Columns conversion to split the columns. Changing the script to encode the same output as "ASCII" (UTF-8 w/o BOM per Notepad++) allowed me to open the CSV directly with the columns split out. You can change the encoding of the CSV in Notepad++ too.

  • Menu Encoding > Convert to UTF-8 without BOM
  • Save the CSV file
  • Open in Excel, columns should be split

Android Left to Right slide animation

You can overwrite your default activity animation. Here is the solution that I use:

Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>

</style>

<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>

Create anim folder under res folder and then create this four animation files:

slide_in_right.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_in_left.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

This is my sample project in github.

That's all... Happy coding :)

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

td:first-child {
  padding-left:20px;
  padding-right:0;
}

First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;       
}

What is an uber jar?

ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:

  1. Unshaded: Unpack all JAR files, then repack them into a single JAR. Works with Java's default class loader. Tools maven-assembly-plugin
  2. Shaded: Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Works with Java's default class loader. Avoids some (not all) dependency version clashes. Tools maven-shade-plugin
  3. JAR of JARs: The final JAR file contains the other JAR files embedded within. Avoids dependency version clashes. All resource files are preserved. Tools: Eclipse JAR File Exporter

for more

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I faced the same problem and solved it by adding:

System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");

before openConnection method.

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

How can I see normal print output created during pytest run?

In an upvoted comment to the accepted answer, Joe asks:

Is there any way to print to the console AND capture the output so that it shows in the junit report?

In UNIX, this is commonly referred to as teeing. Ideally, teeing rather than capturing would be the py.test default. Non-ideally, neither py.test nor any existing third-party py.test plugin (...that I know of, anyway) supports teeing – despite Python trivially supporting teeing out-of-the-box.

Monkey-patching py.test to do anything unsupported is non-trivial. Why? Because:

  • Most py.test functionality is locked behind a private _pytest package not intended to be externally imported. Attempting to do so without knowing what you're doing typically results in the public pytest package raising obscure exceptions at runtime. Thanks alot, py.test. Really robust architecture you got there.
  • Even when you do figure out how to monkey-patch the private _pytest API in a safe manner, you have to do so before running the public pytest package run by the external py.test command. You cannot do this in a plugin (e.g., a top-level conftest module in your test suite). By the time py.test lazily gets around to dynamically importing your plugin, any py.test class you wanted to monkey-patch has long since been instantiated – and you do not have access to that instance. This implies that, if you want your monkey-patch to be meaningfully applied, you can no longer safely run the external py.test command. Instead, you have to wrap the running of that command with a custom setuptools test command that (in order):
    1. Monkey-patches the private _pytest API.
    2. Calls the public pytest.main() function to run the py.test command.

This answer monkey-patches py.test's -s and --capture=no options to capture stderr but not stdout. By default, these options capture neither stderr nor stdout. This isn't quite teeing, of course. But every great journey begins with a tedious prequel everyone forgets in five years.

Why do this? I shall now tell you. My py.test-driven test suite contains slow functional tests. Displaying the stdout of these tests is helpful and reassuring, preventing leycec from reaching for killall -9 py.test when yet another long-running functional test fails to do anything for weeks on end. Displaying the stderr of these tests, however, prevents py.test from reporting exception tracebacks on test failures. Which is completely unhelpful. Hence, we coerce py.test to capture stderr but not stdout.

Before we get to it, this answer assumes you already have a custom setuptools test command invoking py.test. If you don't, see the Manual Integration subsection of py.test's well-written Good Practices page.

Do not install pytest-runner, a third-party setuptools plugin providing a custom setuptools test command also invoking py.test. If pytest-runner is already installed, you'll probably need to uninstall that pip3 package and then adopt the manual approach linked to above.

Assuming you followed the instructions in Manual Integration highlighted above, your codebase should now contain a PyTest.run_tests() method. Modify this method to resemble:

class PyTest(TestCommand):
             .
             .
             .
    def run_tests(self):
        # Import the public "pytest" package *BEFORE* the private "_pytest"
        # package. While importation order is typically ignorable, imports can
        # technically have side effects. Tragicomically, that is the case here.
        # Importing the public "pytest" package establishes runtime
        # configuration required by submodules of the private "_pytest" package.
        # The former *MUST* always be imported before the latter. Failing to do
        # so raises obtuse exceptions at runtime... which is bad.
        import pytest
        from _pytest.capture import CaptureManager, FDCapture, MultiCapture

        # If the private method to be monkey-patched no longer exists, py.test
        # is either broken or unsupported. In either case, raise an exception.
        if not hasattr(CaptureManager, '_getcapture'):
            from distutils.errors import DistutilsClassError
            raise DistutilsClassError(
                'Class "pytest.capture.CaptureManager" method _getcapture() '
                'not found. The current version of py.test is either '
                'broken (unlikely) or unsupported (likely).'
            )

        # Old method to be monkey-patched.
        _getcapture_old = CaptureManager._getcapture

        # New method applying this monkey-patch. Note the use of:
        #
        # * "out=False", *NOT* capturing stdout.
        # * "err=True", capturing stderr.
        def _getcapture_new(self, method):
            if method == "no":
                return MultiCapture(
                    out=False, err=True, in_=False, Capture=FDCapture)
            else:
                return _getcapture_old(self, method)

        # Replace the old with the new method.
        CaptureManager._getcapture = _getcapture_new

        # Run py.test with all passed arguments.
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)

To enable this monkey-patch, run py.test as follows:

python setup.py test -a "-s"

Stderr but not stdout will now be captured. Nifty!

Extending the above monkey-patch to tee stdout and stderr is left as an exercise to the reader with a barrel-full of free time.

UITextField border color

Here's a Swift implementation. You can make an extension so that it will be usable by other views if you like.

extension UIView {
    func addBorderAndColor(color: UIColor, width: CGFloat, corner_radius: CGFloat = 0, clipsToBounds: Bool = false) {
        self.layer.borderWidth  = width
        self.layer.borderColor  = color.cgColor
        self.layer.cornerRadius = corner_radius
        self.clipsToBounds      = clipsToBounds
    }
}

Call this like: email.addBorderAndColor(color: UIColor.white, width: 0.5, corner_radius: 5, clipsToBounds: true).

How to Maximize window in chrome using webDriver (python)

This works for me, with Mac OS Sierra using Python,

options = webdriver.ChromeOptions()
options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=options)

font-weight is not working properly?

In my case, I was using Google's Roboto font. So I had to import it at the beginning of my page with its proper weights.

<link href = "https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto+Slab|Roboto:300,400,500,700" rel = "stylesheet" />

Remove Blank option from Select Option with AngularJS

Finally it worked for me.

<select ng-init="mybasketModel = basket[0]" ng-model="mybasketModel">
        <option ng-repeat="item in basket" ng-selected="$first">{{item}}</option>
</select>


How to add data via $.ajax ( serialize() + extra data ) like this

Personally, I'd append the element to the form instead of hacking the serialized data, e.g.

moredata = 'your custom data here';

// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);

// append to the form
$('#myForm').append($input);

// then..
data: $('#myForm').serialize()

That way, you don't have to worry about ? or &

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
    DTO dTO = new DTO();
    dTO.setrarchyID((Long) (rowMap.get("ID")));
}

How to use ES6 Fat Arrow to .filter() an array of objects

return arrayname.filter((rec) => rec.age > 18)

Write this in the method and call it

Delete specific line from a text file?

I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my DeleteLines method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).

DeleteLines was implemented as a FileInfo extension and ReadLineKeepNewLineChars a StreamReader extension (but obviously you don't have to keep it that way).

public static class FileInfoExtensions
{
    public static FileInfo DeleteLines(this FileInfo source, ICollection<int> lineNumbers, string targetFilePath)
    {
        var lineCount = 1;

        using (var streamReader = new StreamReader(source.FullName))
        {
            using (var streamWriter = new StreamWriter(targetFilePath))
            {
                string line;

                while ((line = streamReader.ReadLineKeepNewLineChars()) != null)
                {
                    if (!lineNumbers.Contains(lineCount))
                    {
                        streamWriter.Write(line);
                    }

                    lineCount++;
                }
            }
        }

        return new FileInfo(targetFilePath);
    }
}

public static class StreamReaderExtensions
{
    private const char EndOfFile = '\uffff';

    /// <summary>
    /// Reads a line, similar to ReadLine method, but keeps any
    /// new line characters (e.g. "\r\n" or "\n").
    /// </summary>
    public static string ReadLineKeepNewLineChars(this StreamReader source)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));

        char ch = (char)source.Read();

        if (ch == EndOfFile)
            return null;

        var sb = new StringBuilder();

        while (ch !=  EndOfFile)
        {
            sb.Append(ch);

            if (ch == '\n')
                break;

            ch = (char) source.Read();
        }

        return sb.ToString();
    }
}

What does "Object reference not set to an instance of an object" mean?

It means you did something like this.

Class myObject = GetObjectFromFunction();

And without doing

if(myObject!=null), you go ahead do myObject.Method();

Simple way to convert datarow array to datatable

DataTable dt = new DataTable(); 

DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria");

dt.Rows.Add(dr);

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

"Data too long for column" - why?

I try to create a table with a field as 200 characters and I've added two rows with early 160 characters and it's OK. Are you sure your rows are less than 200 characters?

Show SqlFiddle

Print all but the first three columns

Options 1 to 3 have issues with multiple whitespace (but are simple). That is the reason to develop options 4 and 5, which process multiple white spaces with no problem. Of course, if options 4 or 5 are used with n=0 both will preserve any leading whitespace as n=0 means no splitting.

Option 1

A simple cut solution (works with single delimiters):

$ echo '1 2 3 4 5 6 7 8' | cut -d' ' -f4-
4 5 6 7 8

Option 2

Forcing an awk re-calc sometimes solve the problem (works with some versions of awk) of added leading spaces:

$ echo '1 2 3 4 5 6 7 8' | awk '{ $1=$2=$3="";$0=$0;} NF=NF'
4 5 6 7 8

Option 3

Printing each field formated with printf will give more control:

$ echo '    1    2  3     4   5   6 7     8  ' |
  awk -v n=3 '{ for (i=n+1; i<=NF; i++){printf("%s%s",$i,i==NF?RS:OFS);} }'
4 5 6 7 8

However, all previous answers change all FS between fields to OFS. Let's build a couple of solutions to that.

Option 4

A loop with sub to remove fields and delimiters is more portable, and doesn't trigger a change of FS to OFS:

$ echo '    1    2  3     4   5   6 7     8  ' |
awk -v n=3 '{ for(i=1;i<=n;i++) { sub("^["FS"]*[^"FS"]+["FS"]+","",$0);} } 1 '
4   5   6 7     8

NOTE: The "^["FS"]*" is to accept an input with leading spaces.

Option 5

It is quite possible to build a solution that does not add extra leading or trailing whitespace, and preserve existing whitespace using the function gensub from GNU awk, as this:

$ echo '    1    2  3     4   5   6 7     8  ' |
awk -v n=3 '{ print gensub("["FS"]*([^"FS"]+["FS"]+){"n"}","",1); }'
4   5   6 7     8 

It also may be used to swap a field list given a count n:

$ echo '    1    2  3     4   5   6 7     8  ' |
  awk -v n=3 '{ a=gensub("["FS"]*([^"FS"]+["FS"]+){"n"}","",1);
                b=gensub("^(.*)("a")","\\1",1);
                print "|"a"|","!"b"!";
               }'
|4   5   6 7     8  | !    1    2  3     !

Of course, in such case, the OFS is used to separate both parts of the line, and the trailing white space of the fields is still printed.

Note1: ["FS"]* is used to allow leading spaces in the input line.

Converting a String to DateTime

Put this code in a static class> public static class ClassName{ }

public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
   try
   {
      datetime = datetime.Trim();
      datetime = datetime.Replace("  ", " ");
      string[] body = datetime.Split(' ');
      string[] date = body[0].Split(dateSpliter);
      int year = date[0].ToInt();
      int month = date[1].ToInt();
      int day = date[2].ToInt();
      int hour = 0, minute = 0, second = 0, millisecond = 0;
      if (body.Length == 2)
      {
         string[] tpart = body[1].Split(millisecondSpliter);
         string[] time = tpart[0].Split(timeSpliter);
         hour = time[0].ToInt();
         minute = time[1].ToInt();
         if (time.Length == 3) second = time[2].ToInt();
         if (tpart.Length == 2) millisecond = tpart[1].ToInt();
      }
      return new DateTime(year, month, day, hour, minute, second, millisecond);
   }
   catch
   {
      return new DateTime();
   }
}

In this way, you can use

string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();

DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');

Upgrade Node.js to the latest version on Mac OS

sudo npm install -g n

and then

sudo n latest for linux/mac users

For Windows please reinstall node.

Executing Javascript code "on the spot" in Chrome?

You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.

How do I display image in Alert/confirm box in Javascript?

Use jQuery dialog to show image, try this code

<html>
  <head>
    </head>
    <body>
     <div id="divid">
         <img>
     </div>
    <body>
  </html>


<script>
 $(document).ready(function(){
      $("btn").click(function(){
      $("divid").dialog();
   });
  });  
 </script>

`

first you have to include jQuery UI at your Page.

Working fiddle

How to include *.so library in Android Studio?

Android NDK official hello-libs CMake example

https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs

Just worked for me on Ubuntu 17.10 host, Android Studio 3, Android SDK 26, so I strongly recommend that you base your project on it.

The shared library is called libgperf, the key code parts are:

  • hello-libs/app/src/main/cpp/CMakeLists.txt:

    // -L
    add_library(lib_gperf SHARED IMPORTED)
    set_target_properties(lib_gperf PROPERTIES IMPORTED_LOCATION
              ${distribution_DIR}/gperf/lib/${ANDROID_ABI}/libgperf.so)
    
    // -I
    target_include_directories(hello-libs PRIVATE
                               ${distribution_DIR}/gperf/include)
    // -lgperf
    target_link_libraries(hello-libs
                          lib_gperf)
    
  • app/build.gradle:

    android {
        sourceSets {
            main {
                // let gradle pack the shared library into apk
                jniLibs.srcDirs = ['../distribution/gperf/lib']
    

    Then, if you look under /data/app on the device, libgperf.so will be there as well.

  • on C++ code, use: #include <gperf.h>

  • header location: hello-libs/distribution/gperf/include/gperf.h

  • lib location: distribution/gperf/lib/arm64-v8a/libgperf.so

  • If you only support some architectures, see: Gradle Build NDK target only ARM

The example git tracks the prebuilt shared libraries, but it also contains the build system to actually build them as well: https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs/gen-libs

Opening port 80 EC2 Amazon web services

For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.

See here on how to completely disable it (for testing purposes only!). And here for specific rules

What's the right way to pass form element state to sibling/parent elements?

The first solution, with keeping the state in parent component, is the correct one. However, for more complex problems, you should think about some state management library, redux is the most popular one used with react.

Change directory command in Docker?

You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.

In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.

Set UIButton title UILabel font size programmatically

this may help :

[objBtn.titleLabel setFont:[UIFont fontWithName:@“fontname” size:fontsize]];

LINQ: Select an object and change some properties without creating a new object

var item = (from something in someList
       select x).firstordefault();

Would get the item, and then you could do item.prop1=5; to change the specific property.

Or are you wanting to get a list of items from the db and have it change the property prop1 on each item in that returned list to a specified value? If so you could do this (I'm doing it in VB because I know it better):

dim list = from something in someList select x
for each item in list
    item.prop1=5
next

(list will contain all the items returned with your changes)

Java: How to convert List to Map

Here's a little method I wrote for exactly this purpose. It uses Validate from Apache Commons.

Feel free to use it.

/**
 * Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
 * the value of the key to be used and the object itself from the list entry is used as the
 * objct. An empty <code>Map</code> is returned upon null input.
 * Reflection is used to retrieve the key from the object instance and method name passed in.
 *
 * @param <K> The type of the key to be used in the map
 * @param <V> The type of value to be used in the map and the type of the elements in the
 *            collection
 * @param coll The collection to be converted.
 * @param keyType The class of key
 * @param valueType The class of the value
 * @param keyMethodName The method name to call on each instance in the collection to retrieve
 *            the key
 * @return A map of key to value instances
 * @throws IllegalArgumentException if any of the other paremeters are invalid.
 */
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
        final Class<K> keyType,
        final Class<V> valueType,
        final String keyMethodName) {

    final HashMap<K, V> map = new HashMap<K, V>();
    Method method = null;

    if (isEmpty(coll)) return map;
    notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
    notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
    notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));

    try {
        // return the Method to invoke to get the key for the map
        method = valueType.getMethod(keyMethodName);
    }
    catch (final NoSuchMethodException e) {
        final String message =
            String.format(
                    Messages.getString(METHOD_NOT_FOUND),
                    keyMethodName,
                    valueType);
        e.fillInStackTrace();
        logger.error(message, e);
        throw new IllegalArgumentException(message, e);
    }
    try {
        for (final V value : coll) {

            Object object;
            object = method.invoke(value);
            @SuppressWarnings("unchecked")
            final K key = (K) object;
            map.put(key, value);
        }
    }
    catch (final Exception e) {
        final String message =
            String.format(
                    Messages.getString(METHOD_CALL_FAILED),
                    method,
                    valueType);
        e.fillInStackTrace();
        logger.error(message, e);
        throw new IllegalArgumentException(message, e);
    }
    return map;
}

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Just Android studio run 'Run as administrator' it will work

Or verify your package name on google-services.json file

Tried to Load Angular More Than Once

In my case I have index.html which embeds 2 views i.e view1.html and view2.html. I developed these 2 views independent of index.html and then tried to embed using route. So I had all the script files defined in the 2 view html files which was causing this warning. The warning disappeared after removing the inclusion of angularJS script files from views.

In short, the script files angularJS, jQuery and angular-route.js should be included only in index.html and not in view html files.

Using R to list all files with a specified extension

Gives you the list of files with full path:

  Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory

How can I get the IP address from NIC in Python?

Yet another way of obtaining the IP Address from a NIC, using Python.

I had this as part of an app that I developed long time ago, and I didn't wanted to simply git rm script.py. So, here I provide the approach, using subprocess and list comprehensions for the sake of functional approach and less lines of code:

import subprocess as sp

__version__ = "v1.0"                                                            
__author__ = "@ivanleoncz"

def get_nic_ipv4(nic):                                                          
    """
        Get IP address from a NIC.                                              

        Parameter
        ---------
        nic : str
            Network Interface Card used for the query.                          

        Returns                                                                 
        -------                                                                 
        ipaddr : str
            Ipaddress from the NIC provided as parameter.                       
    """                                                                         
    result = None                                                               
    try:                                                                        
        result = sp.check_output(["ip", "-4", "addr", "show", nic],             
                                                  stderr=sp.STDOUT)
    except Exception:
        return "Unkown NIC: %s" % nic
    result = result.decode().splitlines()
    ipaddr = [l.split()[1].split('/')[0] for l in result if "inet" in l]        
    return ipaddr[0]

Additionally, you can use a similar approach for obtaining a list of NICs:

def get_nics():                                                                 
    """                                                                         
        Get all NICs from the Operating System.                                 

        Returns                                                                 
        -------                                                                 
        nics : list                                                             
            All Network Interface Cards.                                        
    """                                                                         
    result = sp.check_output(["ip", "addr", "show"])                            
    result = result.decode().splitlines()                                       
    nics = [l.split()[1].strip(':') for l in result if l[0].isdigit()]          
    return nics                                                

Here's the solution as a Gist.

And you would have something like this:

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> 
>>> import helpers
>>> 
>>> helpers.get_nics()
['lo', 'enp1s0', 'wlp2s0', 'docker0']
>>> helpers.get_nic_ipv4('docker0')
'172.17.0.1'
>>> helpers.get_nic_ipv4('docker2')
'Unkown NIC: docker2'

Why can't I use background image and color together?

Actually there is a way you can use a background color with a background image. In this case, the background part will be filled with that specified color instead of a white/transparent one.

In order to achieve that, you need to set the background property like this:

.bg-image-with-color {
    background: url("example.png") no-repeat, #ff0000;
}

Note the comma and the color code after no-repeat; this sets the background color you wish.

I discovered this in this YouTube video, however I'm not affiliated with that channel or video in any means.

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

SOAP­based Web Services In short, the SOAP­based Services model views the world as an ecosystem of co­equal peers that cannot control each other, but have to work together by honoring published contracts. It's a valid model of the messy real world, and the metadata ­based contracts form the SOAP Service Interface.

we can still associate SOAP with XML­based Remote Procedure Calls, but SOAP­based Web Services technology has emerged into a flexible and powerful messaging model.

SOAP assumes all systems are independent and no system has any knowledge of the internals of another and internal functionality. The most such systems can do is send messages to one another and hope they will be acted upon. Systems publish contracts that they undertake to honor, and other systems rely upon these contracts to exchange messages with them.

Contracts between systems are collectively called metadata, and comprise service descriptions, the message exchange patterns supported and the policies governing qualities of service (a service may need to be encrypted, reliably delivered, etc.) A service description, in turn, is a detailed specification of the data (message documents) that will be sent and received by the system. The documents are described using an XML description language like XML Schema Definition. As long as all systems honor their published contracts, they can inter operate, and changes to the internals of systems never affect any other. Every system is responsible for translating its own internal implementations to and from its contracts

REST - REpresentational State Transfer. The physical protocol is HTTP. Basically, REST is that all distinct resources on the web that are uniquely identifiable by a URL. All operations that can be performed on these resources can be described by a limited set of verbs (the “CRUD” verbs) which in turn map to HTTP verbs.

REST's is much less “heavyweight” than SOAP.

Working of web service

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Another possible solution, that worked for me:

Currently, react-router-redux is in beta and npm returns 4.x, but not 5.x. But the @types/react-router-redux returned 5.x. So there were undefined variables used.

Forcing NPM/Yarn to use 5.x solved it for me.

How do you comment an MS-access Query?

The first answer mentioned how to get the description property programatically. If you're going to bother with program anyway, since the comments in the query are so kludgy, instead of trying to put the comments in the query, maybe it's better to put them in a program and use the program to make all your queries

Dim dbs As DAO.Database
Dim qry As DAO.QueryDef

Set dbs = CurrentDb
'put your comments wherever in your program makes the most sense
dbs.QueryDefs("qryName").SQL = "SELECT whatever.fields FROM whatever_table;"
DoCmd.OpenQuery "qryname"

How to recover corrupted Eclipse workspace?

You should be able to start your workspace after deleting the following file: .metadata.plugins\org.eclipse.e4.workbench\workbench.xmi as shown here :

How to reposition Chrome Developer Tools

Looks like this is on the bottom left now as an icon with overlapping windows and the "Undock into separate window." tooltip.

enter image description here

How to append a char to a std::string?

str.append(10u,'d'); //appends character d 10 times

Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.

Fixing broken UTF-8 encoding

It looks like your utf-8 is being interpreted as iso8859-1 or Win-1250 at some point.

When you say "In my database I have a few instances of bad encodings" - how did you check this? Through your app, phpmyadmin or the command line client? Are all utf-8 encodings showing up like this or only some? Is it possible you had the encodings wrong and it has been incorrectly converted from iso8859-1 to utf-8 when it was utf-8 already?

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

Removing the line worked for me.

Convert a positive number to negative in C#

Use binary and to remove the last bit which is responsible for negative sign.

Or use binary or to add sign to a datatype.

This soln may sound absurd and incomplete but I can guarantee this is the fastest method.

If you don't experiment with what I have posted this post may look crap :D

Eg for int:

Int is 32 bit datatype so the last bit (32th one) determines the sign.

And with a value which has 0 in the 32 place and rest 1. It will convert negative no to +ve.

For just the opposite or with a value with 1 in 32th place and rest 0.

Retrieving the last record in each group - MySQL

SELECT * FROM table_name WHERE primary_key IN (SELECT MAX(primary_key) FROM table_name GROUP BY column_name )

download csv file from web api in angular js

I used the below solution and it worked for me.

_x000D_
_x000D_
 if (window.navigator.msSaveOrOpenBlob) {_x000D_
   var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
     type: "text/csv;charset=utf-8;"_x000D_
   });_x000D_
   navigator.msSaveBlob(blob, 'filename.csv');_x000D_
 } else {_x000D_
   var a = document.createElement('a');_x000D_
   a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data);_x000D_
   a.target = '_blank';_x000D_
   a.download = 'filename.csv';_x000D_
   document.body.appendChild(a);_x000D_
   a.click();_x000D_
 }
_x000D_
_x000D_
_x000D_

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

I had issues getting through a form because of this error.

I used Ctrl+Click to click the submit button and navigate through the form as usual.

Alternative to iFrames with HTML5

object is an easy alternative in HTML5:

_x000D_
_x000D_
<object data="https://github.com/AbrarJahin/Asp.NetCore_3.1-PostGRE_Role-Claim_Management/"
width="400"
height="300"
type="text/html">
    Alternative Content
</object>
_x000D_
_x000D_
_x000D_

You can also try embed:

_x000D_
_x000D_
<embed src="https://github.com/AbrarJahin/Asp.NetCore_3.1-PostGRE_Role-Claim_Management/"
width=200
height=200
onerror="alert('URL invalid !!');" />
_x000D_
_x000D_
_x000D_

Re-

As currently, StackOverflow has turned off support for showing external URL contents, run code snippet is not showing anything. But for your site, it will work perfactly.

Regular expression that doesn't contain certain string

By the power of Google I found a blogpost from 2007 which gives the following regex that matches string which don't contains a certain substring:

^((?!my string).)*$

It works as follows: it looks for zero or more (*) characters (.) which do not begin (?! - negative lookahead) your string and it stipulates that the entire string must be made up of such characters (by using the ^ and $ anchors). Or to put it an other way:

The entire string must be made up of characters which do not begin a given string, which means that the string doesn't contain the given substring.

Detect when input has a 'readonly' attribute

In vanilla/pure javascript you can check as following -

var field = document.querySelector("input[name='fieldName']");
if(field.readOnly){
 alert("foo");
}

How to set time delay in javascript

setTimeout(function(){


}, 500); 

Place your code inside of the { }

500 = 0.5 seconds

2200 = 2.2 seconds

etc.

Is there an addHeaderView equivalent for RecyclerView?

Easy and reusable ItemDecoration

Static headers can easily be added with an ItemDecoration and without any further changes.

// add the decoration. done.
HeaderDecoration headerDecoration = new HeaderDecoration(/* init */);
recyclerView.addItemDecoration(headerDecoration);

The decoration is also reusable since there is no need to modify the adapter or the RecyclerView at all.

The sample code provided below will require a view to add to the top which can just be inflated like everything else. It can look like this:

HeaderDecoration sample

Why static?

If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.

Empty list handling

If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)

The code

You can find the full source code here on GitHub including a Builder to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.

Please be sure to set a correct layout_height for your view. e.g. match_parent might not work properly.

public class HeaderDecoration extends RecyclerView.ItemDecoration {

    private final View mView;
    private final boolean mHorizontal;
    private final float mParallax;
    private final float mShadowSize;
    private final int mColumns;
    private final Paint mShadowPaint;

    public HeaderDecoration(View view, boolean scrollsHorizontally, float parallax, float shadowSize, int columns) {
        mView = view;
        mHorizontal = scrollsHorizontally;
        mParallax = parallax;
        mShadowSize = shadowSize;
        mColumns = columns;

        if (mShadowSize > 0) {
            mShadowPaint = new Paint();
            mShadowPaint.setShader(mHorizontal ?
                    new LinearGradient(mShadowSize, 0, 0, 0,
                            new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
                            new float[]{0f, .5f, 1f},
                            Shader.TileMode.CLAMP) :
                    new LinearGradient(0, mShadowSize, 0, 0,
                            new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
                            new float[]{0f, .5f, 1f},
                            Shader.TileMode.CLAMP));
        } else {
            mShadowPaint = null;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        // layout basically just gets drawn on the reserved space on top of the first view
        mView.layout(parent.getLeft(), 0, parent.getRight(), mView.getMeasuredHeight());

        for (int i = 0; i < parent.getChildCount(); i++) {
            View view = parent.getChildAt(i);
            if (parent.getChildAdapterPosition(view) == 0) {
                c.save();
                if (mHorizontal) {
                    c.clipRect(parent.getLeft(), parent.getTop(), view.getLeft(), parent.getBottom());
                    final int width = mView.getMeasuredWidth();
                    final float left = (view.getLeft() - width) * mParallax;
                    c.translate(left, 0);
                    mView.draw(c);
                    if (mShadowSize > 0) {
                        c.translate(view.getLeft() - left - mShadowSize, 0);
                        c.drawRect(parent.getLeft(), parent.getTop(), mShadowSize, parent.getBottom(), mShadowPaint);
                    }
                } else {
                    c.clipRect(parent.getLeft(), parent.getTop(), parent.getRight(), view.getTop());
                    final int height = mView.getMeasuredHeight();
                    final float top = (view.getTop() - height) * mParallax;
                    c.translate(0, top);
                    mView.draw(c);
                    if (mShadowSize > 0) {
                        c.translate(0, view.getTop() - top - mShadowSize);
                        c.drawRect(parent.getLeft(), parent.getTop(), parent.getRight(), mShadowSize, mShadowPaint);
                    }
                }
                c.restore();
                break;
            }
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) < mColumns) {
            if (mHorizontal) {
                if (mView.getMeasuredWidth() <= 0) {
                    mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
                }
                outRect.set(mView.getMeasuredWidth(), 0, 0, 0);
            } else {
                if (mView.getMeasuredHeight() <= 0) {
                    mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
                }
                outRect.set(0, mView.getMeasuredHeight(), 0, 0);
            }
        } else {
            outRect.setEmpty();
        }
    }
}

Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.

What does it do?

An ItemDecoration is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.

The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.

How do I get the opposite (negation) of a Boolean in Python?

Python has a "not" operator, right? Is it not just "not"? As in,

  return not bool

ImportError: No module named pandas

As of Dec 2020, I had the same issue when installing python v 3.8.6 via pyenv. So, I started by:

  1. Installing pyenv via homebrew brew install pyenv
  2. Install xz compiling package via brew install xz
  3. pyenv install 3.8.6 pick the required version
  4. pyenv global 3.8.6 make this version as global
  5. python -m pip install -U pip to upgrade pip
  6. pip install virtualenv

After that, I initialized my new env, installed pandas via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!

Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.

Get full path of a file with FileUpload Control

This will not problem if we use IE browser. This is for other browsers, save file on another location and use that path.

if (FileUpload1.HasFile)

{

string fileName = FileUpload1.PostedFile.FileName;

string TempfileLocation = @"D:\uploadfiles\";

string FullPath = System.IO.Path.Combine(TempfileLocation, fileName);

FileUpload1.SaveAs(FullPath);

Response.Write(FullPath);

}

Thank you

javascript set cookie with expire time

I use a function to store cookies with a custom expire time in days:

// use it like: writeCookie("mycookie", "1", 30)
// this will set a cookie for 30 days since now
function writeCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

PHP cURL error code 60

First you have to download the certificate from this link

https://curl.haxx.se/ca/cacert.pem

and put it in a location you want the name of downloadable file is : cacert.pem So in my case I will put it under C:\wamp64\bin\php\cacert.pem

Then you have to specify the location of the php.ini file

For example, I am using php 7 the php.ini file is located at : C:\wamp64\bin\php\php7.0.10\php.ini

So access to that file and uncommit this line ;openssl.cafile

also update it to be looks like this openssl.cafile="C:\wamp64\bin\php\cacert.pem"

Finally restart your apache server and that's all

HTML list-style-type dash

You can just set li::marker like so:

li::marker {
   content: '- ';
}

How to Display blob (.pdf) in an AngularJS app

I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):

$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);

function success(data) {
   openPDF(data.data, "myPDFdoc.pdf");
};

function failed(error) {...};

function openPDF(resData, fileName) {
    var ieEDGE = navigator.userAgent.match(/Edge/g);
    var ie = navigator.userAgent.match(/.NET/g); // IE 11+
    var oldIE = navigator.userAgent.match(/MSIE/g); 

    var blob = new window.Blob([resData], { type: 'application/pdf' });

    if (ie || oldIE || ieEDGE) {
       window.navigator.msSaveBlob(blob, fileName);
    }
    else {
       var reader = new window.FileReader();
       reader.onloadend = function () {
          window.location.href = reader.result;
       };
       reader.readAsDataURL(blob);
    }
}

Let me know if it helped! :)

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

I had this issue and what I did and solved the problem was that I used AsEnumerable() just before my Join clause. here is my query:

List<AccountViewModel> selectedAccounts;

 using (ctx = SmallContext.GetInstance()) {
                var data = ctx.Transactions.
                    Include(x => x.Source).
                    Include(x => x.Relation).
                    AsEnumerable().
                    Join(selectedAccounts, x => x.Source.Id, y => y.Id, (x, y) => x).
                    GroupBy(x => new { Id = x.Relation.Id, Name = x.Relation.Name }).
                    ToList();
            }

I was wondering why this issue happens, and now I think It is because after you make a query via LINQ, the result will be in memory and not loaded into objects, I don't know what that state is but they are in in some transitional state I think. Then when you use AsEnumerable() or ToList(), etc, you are placing them into physical memory objects and the issue is resolving.

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

How to change color in circular progress bar?

You can change your progressbar colour using the code below:

progressBar.getProgressDrawable().setColorFilter(
    getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_IN);

What are C++ functors and their uses?

Little addition. You can use boost::function, to create functors from functions and methods, like this:

class Foo
{
public:
    void operator () (int i) { printf("Foo %d", i); }
};
void Bar(int i) { printf("Bar %d", i); }
Foo foo;
boost::function<void (int)> f(foo);//wrap functor
f(1);//prints "Foo 1"
boost::function<void (int)> b(&Bar);//wrap normal function
b(1);//prints "Bar 1"

and you can use boost::bind to add state to this functor

boost::function<void ()> f1 = boost::bind(foo, 2);
f1();//no more argument, function argument stored in f1
//and this print "Foo 2" (:
//and normal function
boost::function<void ()> b1 = boost::bind(&Bar, 2);
b1();// print "Bar 2"

and most useful, with boost::bind and boost::function you can create functor from class method, actually this is a delegate:

class SomeClass
{
    std::string state_;
public:
    SomeClass(const char* s) : state_(s) {}

    void method( std::string param )
    {
        std::cout << state_ << param << std::endl;
    }
};
SomeClass *inst = new SomeClass("Hi, i am ");
boost::function< void (std::string) > callback;
callback = boost::bind(&SomeClass::method, inst, _1);//create delegate
//_1 is a placeholder it holds plase for parameter
callback("useless");//prints "Hi, i am useless"

You can create list or vector of functors

std::list< boost::function<void (EventArg e)> > events;
//add some events
....
//call them
std::for_each(
        events.begin(), events.end(), 
        boost::bind( boost::apply<void>(), _1, e));

There is one problem with all this stuff, compiler error messages is not human readable :)

Can I call a function of a shell script from another shell script?

The problem

The currenly accepted answer works only under important condition. Given...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

and

/foo/bar/second.sh:

#!/bin/bash

source ./first.sh
func1 World

this works only if the first.sh is executed from within the same directory where the first.sh is located. Ie. if the current working path of shell is /foo, the attempt to run command

cd /foo
./bar/second.sh

prints error:

/foo/bar/second.sh: line 4: func1: command not found

That's because the source ./first.sh is relative to current working path, not the path of the script. Hence one solution might be to utilize subshell and run

(cd /foo/bar; ./second.sh)

More generic solution

Given...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

and

/foo/bar/second.sh:

#!/bin/bash

source $(dirname "$0")/first.sh

func1 World

then

cd /foo
./bar/second.sh

prints

Hello World

How it works

  • $0 returns relative or absolute path to the executed script
  • dirname returns relative path to directory, where the $0 script exists
  • $( dirname "$0" ) the dirname "$0" command returns relative path to directory of executed script, which is then used as argument for source command
  • in "second.sh", /first.sh just appends the name of imported shell script
  • source loads content of specified file into current shell

ImportError: cannot import name

This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.

You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:

%reset

or menu->restart terminal

object==null or null==object?

This trick supposed to prevent v = null kind of typos.

But Java allows only boolean expressions as if() conditions so that trick does not make much sense, compiler will find those typos anyway.

It is still valuable trick for C/C++ code though.

Delete all the records

from a table?

You can use this if you have no foreign keys to other tables

truncate table TableName

or

delete TableName

if you want all tables

sp_msforeachtable 'delete ?'

Show/hide forms using buttons and JavaScript

Would you want the same form with different parts, showing each part accordingly with a button?

Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters &laquo; and &raquo; just print respectively « and » which might be interesting for the previous and next button characters.

_x000D_
_x000D_
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
  var i = 1, p = document.getElementById("form_part"+1);_x000D_
  while (p !== null){_x000D_
    if (i === n){_x000D_
      p.style.display = "";_x000D_
    }_x000D_
    else{_x000D_
      p.style.display = "none";_x000D_
    }_x000D_
    i++;_x000D_
    p = document.getElementById("form_part"+i);_x000D_
  }_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
  var sum =_x000D_
    parseInt(document.getElementById("num1").value) +_x000D_
    parseInt(document.getElementById("num2").value) +_x000D_
    parseInt(document.getElementById("num3").value);_x000D_
_x000D_
  alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
  Part 1<br>_x000D_
  <input type="number" value="1" id="num1"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
  Part 2<br>_x000D_
  <input type="number" value="2" id="num2"><br>_x000D_
  <button type="button" onclick="shows_form_part(1)">&laquo;</button>_x000D_
  <button type="button" onclick="shows_form_part(3)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
  Part 3<br>_x000D_
  <input type="number" value="3" id="num3"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&laquo;</button>_x000D_
  <button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Keyword not supported: "data source" initializing Entity Framework Context

The real reason you were getting this error is because of the &quot; values in your connection string.

If you replace those with single quotes then it will work fine.

https://docs.microsoft.com/archive/blogs/rickandy/explicit-connection-string-for-ef

(Posted so others can get the fix faster than I did.)

How do I force Kubernetes to re-pull an image?

You can define imagePullPolicy: Always in your deployment file.

"CAUTION: provisional headers are shown" in Chrome debugger

If you are developing an Asp.Net Mvc application and you are trying to return a JsonResult in your controller, make sure you add JsonRequestBehavior.AllowGet to the Json method. That fixed it for me.

public JsonResult GetTaskSubCategories(int id)
{
    var subcategs = FindSubCategories(id);

    return Json(subcategs, JsonRequestBehavior.AllowGet);  //<-- Notice it has two parameters
}

What is the difference between Digest and Basic Authentication?

HTTP Basic Access Authentication

  • STEP 1 : the client makes a request for information, sending a username and password to the server in plain text
  • STEP 2 : the server responds with the desired information or an error

Basic Authentication uses base64 encoding(not encryption) for generating our cryptographic string which contains the information of username and password. HTTP Basic doesn’t need to be implemented over SSL, but if you don’t, it isn’t secure at all. So I’m not even going to entertain the idea of using it without.

Pros:

  • Its simple to implement, so your client developers will have less work to do and take less time to deliver, so developers could be more likely to want to use your API
  • Unlike Digest, you can store the passwords on the server in whatever encryption method you like, such as bcrypt, making the passwords more secure
  • Just one call to the server is needed to get the information, making the client slightly faster than more complex authentication methods might be

Cons:

  • SSL is slower to run than basic HTTP so this causes the clients to be slightly slower
  • If you don’t have control of the clients, and can’t force the server to use SSL, a developer might not use SSL, causing a security risk

In Summary – if you have control of the clients, or can ensure they use SSL, HTTP Basic is a good choice. The slowness of the SSL can be cancelled out by the speed of only making one request

Syntax of basic Authentication

Value = username:password
Encoded Value =  base64(Value)
Authorization Value = Basic <Encoded Value> 
//at last Authorization key/value map added to http header as follows
Authorization: <Authorization Value>

HTTP Digest Access Authentication
Digest Access Authentication uses the hashing(i.e digest means cut into small pieces) methodologies to generate the cryptographic result. HTTP Digest access authentication is a more complex form of authentication that works as follows:

  • STEP 1 : a client sends a request to a server
  • STEP 2 : the server responds with a special code (called a i.e. number used only once), another string representing the realm(a hash) and asks the client to authenticate
  • STEP 3 : the client responds with this nonce and an encrypted version of the username, password and realm (a hash)
  • STEP 4 : the server responds with the requested information if the client hash matches their own hash of the username, password and realm, or an error if not

Pros:

  • No usernames or passwords are sent to the server in plaintext, making a non-SSL connection more secure than an HTTP Basic request that isn’t sent over SSL. This means SSL isn’t required, which makes each call slightly faster

Cons:

  • For every call needed, the client must make 2, making the process slightly slower than HTTP Basic
  • HTTP Digest is vulnerable to a man-in-the-middle security attack which basically means it could be hacked
  • HTTP Digest prevents use of the strong password encryption, meaning the passwords stored on the server could be hacked

In Summary, HTTP Digest is inherently vulnerable to at least two attacks, whereas a server using strong encryption for passwords with HTTP Basic over SSL is less likely to share these vulnerabilities.

If you don’t have control over your clients however they could attempt to perform Basic authentication without SSL, which is much less secure than Digest.

RFC 2069 Digest Access Authentication Syntax

Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:Hash2)

RFC 2617 Digest Access Authentication Syntax

Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:nonceCount:cnonce:qop:Hash2)
//some additional parameters added 

source and example

In Postman looks as follows:

enter image description here

Note:

  • The Basic and Digest schemes are dedicated to the authentication using a username and a secret.
  • The Bearer scheme is dedicated to the authentication using a token.

The application has stopped unexpectedly: How to Debug?

Filter your log to just Error and look for FATAL EXCEPTION

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

PHP - Merging two arrays into one array (also Remove Duplicates)

Merging two array will not remove the duplicate you can try the below example to get unique from two array

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_diff($a1,$a2);
print_r($result);

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

how to put focus on TextBox when the form load?

on your form, go to properties and make sure that "TopMost" property is set to true, that will solve your problem.

Remove unused imports in Android Studio

you can use Alt + Enter in Android Studio as Shortcut Key

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

Install MySQL on Ubuntu without a password prompt

Another way to make it work:

echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

Note that this simply sets the password to "root". I could not get it to set a blank password using simple quotes '', but this solution was sufficient for me.

Based on a solution here.

Implementing two interfaces in a class with same method. Which interface method is overridden?

As far as the compiler is concerned, those two methods are identical. There will be one implementation of both.

This isn't a problem if the two methods are effectively identical, in that they should have the same implementation. If they are contractually different (as per the documentation for each interface), you'll be in trouble.

Display Last Saved Date on worksheet

May be this time stamp fit you better Code

Function LastInputTimeStamp() As Date
  LastInputTimeStamp = Now()
End Function

and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this

=IF(C36>0,LastInputTimeStamp(),"")

Django templates: If false?

For posterity, I have a few NullBooleanFields and here's what I do:

To check if it's True:

{% if variable %}True{% endif %}

To check if it's False (note this works because there's only 3 values -- True/False/None):

{% if variable != None %}False{% endif %}

To check if it's None:

{% if variable == None %}None{% endif %}

I'm not sure why, but I can't do variable == False, but I can do variable == None.

ldconfig error: is not a symbolic link

Solved, at least at the point of the question.

I searched in the web before asking, an there were no conclusive solution, the reason why this error is: lib1.so and lib2.so are not OK, very probably where not compiled for a 64 PC, but for a 32 bits machine otherwise lib3.so is a 64 bits lib. At least that is my hipothesis.

VERY unfortunately ldconfig doesn't give a clean error message informing that it could not load the library, it only pumps:

ldconfig: /folder_where_the_wicked_lib_is/ is not a symbolic link

I solved this when I removed the libs not found by ldd over the binary. Now it's easier that I know where lies the problem.

My ld version: GNU ld version 2.20.51, and I don't know if a most recent version has a better message for its users.

Thanks.

Ignore .classpath and .project from Git

The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:

git update-index --skip-worktree .classpath .gitignore

It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.

Running git rm --cached doesn't work for the scenario mentioned in the question. If I simplify the question, it says:

How to have .classpath and .project on the repo while each one can change it locally and git ignores this change?

As I commented under the accepted answer, the drawback of git rm --cached is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath and .project won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.

What is SKIP-WORKTREE BIT?

Based on git documentaion:

Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.

More details is available here.

How to get multiple select box values using jQuery?

You can also use js map function:

$("#multipleSelect :selected").map(function(i, el) {
    return $(el).val();
}).get();

And then you can get any property of the option element:

return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...

How can I access "static" class variables within class methods in Python?

class Foo(object):
     bar = 1
     def bah(self):
         print Foo.bar

f = Foo() 
f.bah()

Visual Studio: How to show Overloads in IntelliSense?

It happens that none of the above methods work. Key binding is proper, but tool tip simply doesn't show in any case, neither as completion help or on demand.

To fix it just go to Tools\Text Editor\C# (or all languages) and check the 'Parameter Information'. Now it should work

MetadataException when using Entity Framework Entity Connection

I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.

Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.

To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.

How to call a Parent Class's method from Child Class in Python?

Python also has super as well:

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

Example:

class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls 'A.foo()'

myB = B()
myB.foo()

How can I hide select options with JavaScript? (Cross browser)

You can try wrapping the option elements inside a span so that they wont be visible but still be loaded in the DOM. Like below

jQ('#ddlDropdown option').wrap('<span>');

And unwrap the option which contains the 'selected' attribute as follows to display already selected option.

var selectedOption = jQ('#ddlDropdown').find("[selected]");
jQ(selectedOption).unwrap();

This works across all the browsers.

What's the best way to validate an XML file against an XSD file?

Validate against online schemas

Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("your.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource("your.xsd"));
Validator validator = schema.newValidator();
validator.validate(xmlFile);

Validate against local schemas

Offline XML Validation with Java

Why is volatile needed in C?

In my opinion, you should not expect too much from volatile. To illustrate, look at the example in Nils Pipenbrinck's highly-voted answer.

I would say, his example is not suitable for volatile. volatile is only used to: prevent the compiler from making useful and desirable optimizations. It is nothing about the thread safe, atomic access or even memory order.

In that example:

    void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
    {
      // wait while the gadget is busy:
      while (gadget->isbusy)
      {
        // do nothing here.
      }
      // set data first:
      gadget->data    = data;
      // writing the command starts the action:
      gadget->command = command;
    }

the gadget->data = data before gadget->command = command only is only guaranteed in compiled code by compiler. At running time, the processor still possibly reorders the data and command assignment, regarding to the processor architecture. The hardware could get the wrong data(suppose gadget is mapped to hardware I/O). The memory barrier is needed between data and command assignment.

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Define a global variable in a JavaScript function

If you read the comments there's a nice discussion around this particular naming convention.

It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.

Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

How do I trim leading/trailing whitespace in a standard way?

A bit late to the game, but I'll throw my routines into the fray. They're probably not the most absolute efficient, but I believe they're correct and they're simple (with rtrim() pushing the complexity envelope):

#include <ctype.h>
#include <string.h>

/*
    Public domain implementations of in-place string trim functions

    Michael Burr
    [email protected]
    2010
*/

char* ltrim(char* s) 
{
    char* newstart = s;

    while (isspace( *newstart)) {
        ++newstart;
    }

    // newstart points to first non-whitespace char (which might be '\0')
    memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\0' terminator

    return s;
}


char* rtrim( char* s)
{
    char* end = s + strlen( s);

    // find the last non-whitespace character
    while ((end != s) && isspace( *(end-1))) {
            --end;
    }

    // at this point either (end == s) and s is either empty or all whitespace
    //      so it needs to be made empty, or
    //      end points just past the last non-whitespace character (it might point
    //      at the '\0' terminator, in which case there's no problem writing
    //      another there).    
    *end = '\0';

    return s;
}

char*  trim( char* s)
{
    return rtrim( ltrim( s));
}

Find Oracle JDBC driver in Maven repository

If you are using Netbeans, goto Dependencies and manually install artifact. Locate your downloaded .jar file and its done. clean build will solve any issues.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

well, i had the same problem with my code, and it's because since android 4.2 bluetooth stack has changed. so my code was running fine on devices with android < 4.2 , on the other devices i was getting the famous exception "read failed, socket might closed or timeout, read ret: -1"

The problem is with the socket.mPort parameter. When you create your socket using socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID); , the mPort gets integer value "-1", and this value seems doesn't work for android >=4.2 , so you need to set it to "1". The bad news is that createRfcommSocketToServiceRecord only accepts UUID as parameter and not mPort so we have to use other aproach. The answer posted by @matthes also worked for me, but i simplified it: socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);. We need to use both socket attribs , the second one as a fallback.

So the code is (for connecting to a SPP on an ELM327 device):

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    if (btAdapter.isEnabled()) {
        SharedPreferences prefs_btdev = getSharedPreferences("btdev", 0);
        String btdevaddr=prefs_btdev.getString("btdevaddr","?");

        if (btdevaddr != "?")
        {
            BluetoothDevice device = btAdapter.getRemoteDevice(btdevaddr);

            UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // bluetooth serial port service
            //UUID SERIAL_UUID = device.getUuids()[0].getUuid(); //if you don't know the UUID of the bluetooth device service, you can get it like this from android cache

            BluetoothSocket socket = null;

            try {
                socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
            } catch (Exception e) {Log.e("","Error creating socket");}

            try {
                socket.connect();
                Log.e("","Connected");
            } catch (IOException e) {
                Log.e("",e.getMessage());
                try {
                    Log.e("","trying fallback...");

                    socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
                    socket.connect();

                    Log.e("","Connected");
                }
             catch (Exception e2) {
                 Log.e("", "Couldn't establish Bluetooth connection!");
              }
            }
        }
        else
        {
            Log.e("","BT device not selected");
        }
    }

jquery $('.class').each() how many items?

Use the .length property. It is not a function.

alert($('.class').length); // alerts a nonnegative number 

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

Try casting the ints to varchar, before adding them to a string:

SET @ActualWeightDIMS = cast(@Actual_Dims_Lenght as varchar(8)) + 
   'x' + cast(@Actual_Dims_Width as varchar(8)) + 
   'x' + cast(@Actual_Dims_Height as varhcar(8))

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

How can I completely remove TFS Bindings

In VS2017

  1. go to Home in Team Explorer
  2. Click on Settings in project section
  3. Click on Repository Settings in Git section
  4. From next window see Remotes section. you will see option for remove

NB: I check that for git repository

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

Disable Input fields in reactive form

setTimeout(() => { emailGroup.disable(); });

How to run a cron job on every Monday, Wednesday and Friday?

Use crontab to add job

0 0 9 ? * MON,WED,FRI *

The above expression will run the job at 9 am on every mon, wed and friday. You can validate this in : http://www.cronmaker.com/

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

Is it possible to import modules from all files in a directory, using a wildcard?

I was able to take from user atilkan's approach and modify it a bit:

For Typescript users;

require.context('@/folder/with/modules', false, /\.ts$/).keys().forEach((fileName => {
    import('@/folder/with/modules' + fileName).then((mod) => {
            (window as any)[fileName] = mod[fileName];
            const module = new (window as any)[fileName]();

            // use module
});

}));

After installing with pip, "jupyter: command not found"

The only thing that worked me is to export to PATH the Python version that is related to the pip3 of course :) (after a lot of struggling) just run:

which pip3

you should get something like (in Mac):

/Library/Frameworks/Python.framework/Versions/3.6/bin/pip3

Now run:

export PATH=/Library/Python/3.6/bin:$PATH

If it works for you :) just add it to your bashrc or zshrc

How to configure socket connect timeout

I found this. Simpler than the accepted answer, and works with .NET v2

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Connect using a timeout (5 seconds)

IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null );

bool success = result.AsyncWaitHandle.WaitOne( 5000, true );

if ( socket.Connected )
{
    socket.EndConnect( result );
}
else 
{
     // NOTE, MUST CLOSE THE SOCKET

     socket.Close();
     throw new ApplicationException("Failed to connect server.");
}

//... 

Run react-native application on iOS device directly from command line?

The following worked for me (tested on react native 0.38 and 0.40):

npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"

If you try to run run-ios, you will see that the script recommends to do npm install -g ios-deploy when it reach install step after building.

While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

HTML button to NOT submit form

For accessibility reason, I could not pull it off with multiple type=submit buttons. The only way to work natively with a form with multiple buttons but ONLY one can submit the form when hitting the Enter key is to ensure that only one of them is of type=submit while others are in other type such as type=button. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

How do you tell if caps lock is on using JavaScript?

You can detect caps lock using "is letter uppercase and no shift pressed" using a keypress capture on the document. But then you better be sure that no other keypress handler pops the event bubble before it gets to the handler on the document.

document.onkeypress = function ( e ) {
  e = e || window.event;
  var s = String.fromCharCode( e.keyCode || e.which );
  if ( (s.toUpperCase() === s) !== e.shiftKey ) {
    // alert('caps is on')
  }
}

You could grab the event during the capturing phase in browsers that support that, but it seems somewhat pointless to as it won't work on all browsers.

I can't think of any other way of actually detecting caps lock status. The check is simple anyway and if non detectable characters were typed, well... then detecting wasn't necessary.

There was an article on 24 ways on this last year. Quite good, but lacks international character support (use toUpperCase() to get around that).

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

This error tells you that you do not have the razor engine properly associated with your project.

Solution: In the Solution Explorer window right click on your web project and select "Manage Nuget Packages..." then install "Microsoft ASP.NET Razor". This will make sure that the properly package is installed and it will add the necessary entries into your web.config file.

How to retry image pull in a kubernetes Pods?

Try with deleting pod it will try to pull image again.

kubectl delete pod <pod_name> -n <namespace_name>

PLS-00201 - identifier must be declared

The procedure name should be in caps while creating procedure in database. You may use small letters for your procedure name while calling from Java class like:

String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";

In database the name of procedure should be:

GETDBUSERBYUSERID    -- (all letters in caps only)

This serves as one of the solutions for this problem.

SQL: set existing column as Primary Key in MySQL

alter table table_name
add constraint myprimarykey primary key(column);

reference : http://www.w3schools.com/sql/sql_primarykey.asp

Propagation Delay vs Transmission delay

Transmission Delay:

This is the amount of time required to transmit all of the packet's bits into the link. Transmission delays are typically on the order of microseconds or less in practice. 

L: packet length (bits)
R: link bandwidth (bps)
so transmission delay is = L/R

Propagation Delay:

Is the time it takes a bit to propagate over the transmission medium from the source router to the destination router; it is a function of the distance between the two routers, but has nothing to do with the packet's length or the transmission rate of the link. 

d: length of physical link
S: propagation speed in medium (~2x108m/sec, for copper wires & ~3x108m/sec, for wireless media)
so propagation delay is = d/s

Java substring: 'string index out of range'

Should anyone face the same problem.

Do this: str.substring (...(trim()) ;

Hope it helps somebodies

Type safety: Unchecked cast

You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version

someMap=getApplicationContext().getBean<HashMap<String, String>>("someMap");

on its todo list.

Rolling or sliding window iterator?

Optimized Function for sliding window data in Deep learning

def SlidingWindow(X, window_length, stride):
    indexer = np.arange(window_length)[None, :] + stride*np.arange(int(len(X)/stride)-window_length+4)[:, None]
    return X.take(indexer)

to apply on multidimensional array

import numpy as np
def SlidingWindow(X, window_length, stride1):
    stride=  X.shape[1]*stride1
    window_length = window_length*X.shape[1]
    indexer = np.arange(window_length)[None, :] + stride1*np.arange(int(len(X)/stride1)-window_length-1)[:, None]
    return X.take(indexer)

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

How to index characters in a Golang string?

Try this to get the charecters by their index

package main

import (
      "fmt"
      "strings"
)

func main() {
   str := strings.Split("HELLO","")
    fmt.Print(str[1])
}

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

I had the same problem , I used in instead of = , from the Northwind database example :

Query is : Find the Companies that placed orders in 1997

Try this :

SELECT CompanyName
    FROM Customers
WHERE CustomerID IN (
                        SELECT CustomerID 
                            FROM Orders 
                        WHERE YEAR(OrderDate) = '1997'
                    );

Instead of that :

SELECT CompanyName
    FROM Customers
WHERE CustomerID =
(
    SELECT CustomerID 
        FROM Orders 
    WHERE YEAR(OrderDate) = '1997'
);

How do you get an iPhone's device name

Here is class structure of UIDevice

+ (UIDevice *)currentDevice;

@property(nonatomic,readonly,strong) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,strong) NSString    *model;             // e.g. @"iPhone", @"iPod touch"
@property(nonatomic,readonly,strong) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,strong) NSString    *systemName;        // e.g. @"iOS"
@property(nonatomic,readonly,strong) NSString    *systemVersion;

How to change the floating label color of TextInputLayout

In my case I added this "app:hintTextAppearance="@color/colorPrimaryDark"in my TextInputLayout widget.

react-native :app:installDebug FAILED

This works for me

  1. Uninstall the app from your phone
  2. cd android
  3. gradlew clean
  4. cd ..
  5. react-native run-android

How to convert UTF-8 byte[] to string?

Alternatively:

 var byteStr = Convert.ToBase64String(bytes);

Disable/enable an input with jQuery?

<html>
<body>

Name: <input type="text" id="myText">



<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>

<script>
function disable() {
    document.getElementById("myText").disabled = true;
}
function enable() {
    document.getElementById("myText").disabled = false;
}
</script>

</body>
</html>

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

Calculate MD5 checksum for a file

It's very simple using System.Security.Cryptography.MD5:

using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
        return md5.ComputeHash(stream);
    }
}

(I believe that actually the MD5 implementation used doesn't need to be disposed, but I'd probably still do so anyway.)

How you compare the results afterwards is up to you; you can convert the byte array to base64 for example, or compare the bytes directly. (Just be aware that arrays don't override Equals. Using base64 is simpler to get right, but slightly less efficient if you're really only interested in comparing the hashes.)

If you need to represent the hash as a string, you could convert it to hex using BitConverter:

static string CalculateMD5(string filename)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            var hash = md5.ComputeHash(stream);
            return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
        }
    }
}

How to call javascript function from code-behind

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);

How can I loop through a List<T> and grab each item?

foreach:

foreach (var money in myMoney) {
    Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}

MSDN Link

Alternatively, because it is a List<T>.. which implements an indexer method [], you can use a normal for loop as well.. although its less readble (IMO):

for (var i = 0; i < myMoney.Count; i++) {
    Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}

CSS3 transition events

Just for fun, don't do this!

$.fn.transitiondone = function () {
  return this.each(function () {
    var $this = $(this);
    setTimeout(function () {
      $this.trigger('transitiondone');
    }, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
  });
};


$('div').on('mousedown', function (e) {
  $(this).addClass('bounce').transitiondone();
});

$('div').on('transitiondone', function () {
  $(this).removeClass('bounce');
});

Unable to open project... cannot be opened because the project file cannot be parsed

And once you get things working again you should look into using something like subversion or mercurial for backup and revision control. Remember that he electrons don't always go where they are supposed to, backup early and often!

Eclipse error ... cannot be resolved to a type

I was importing the source into the wrong folder. I'm so used to using Visual Studio, that I expect all IDE's to be so accommodating.

Notice: Undefined offset: 0 in

I encountered this as well and the solution is simple, dont hardcode the array index position in your code.
Instead of $data[0]['somekey'] do foreach($data as $data_item) { echo $data_item['somekey']; }
If there is an array or more you can perform your desired action inside the loop, but if it's undefined it will not bring an error. you can also add other checks on top of that. You could also add a variable and increment it in a for in loop to limit your looping if you want only the first positions or something.

jQuery - Call ajax every 10 seconds

setInterval(function()
{ 
    $.ajax({
      type:"post",
      url:"myurl.html",
      datatype:"html",
      success:function(data)
      {
          //do something with response data
      }
    });
}, 10000);//time in milliseconds 

Test process.env with Jest

Another option is to add it to the jest.config.js file after the module.exports definition:

process.env = Object.assign(process.env, {
  VAR_NAME: 'varValue',
  VAR_NAME_2: 'varValue2'
});

This way it's not necessary to define the environment variables in each .spec file and they can be adjusted globally.

Getting "Cannot call a class as a function" in my React Project

Hi in my case solutions here won't work My code:

index.js

import App from './App';

let store = createStore(App);

render(
    <Provider store={store}>
        <Router history={browserHistory}>
            <Route path="/" name='Strona glówna' component={App}>
                <IndexRoute name='' component={Welcome}/>
                <Route name='Dashboard' path="dashboard" component={ReatEstateList}/>

Error apeares in App.js after import

Uncaught TypeError: Cannot call a class as a function

How to convert uint8 Array to base64 Encoded String?

function Uint8ToBase64(u8Arr){
  var CHUNK_SIZE = 0x8000; //arbitrary number
  var index = 0;
  var length = u8Arr.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  }
  return btoa(result);
}

You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.

How to fix "unable to write 'random state' " in openssl

The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:

set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024

More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:

  1. Path taken from RANDFILE environment variable
  2. If HOME environment variable is set then : ${HOME}\.rnd
  3. C:\.rnd

I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.

Open Popup window using javascript

Change the window name in your two different calls:

function popitup(url,windowName) {
       newwindow=window.open(url,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;
     }

windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

They are both correct. Personally I prefer your approach better for its verbosity but it's really down to personal preference.

Off hand, running if($_POST) would not throw an error - the $_POST array exists regardless if the request was sent with POST headers. An empty array is cast to false in a boolean check.

Laravel Eloquent groupBy() AND also return count of each group

Works that way as well, a bit more tidy. getQuery() just returns the underlying builder, which already contains the table reference.

$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
                     ->select('browser', $browser_total_raw)
                     ->groupBy('browser')
                     ->pluck('total','browser');

How do I list the symbols in a .so file

For Android .so files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf, objdump and nm.

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

Truncating all tables in a Postgres database

For removing the data and preserving the table-structures in pgAdmin you can do:

  • Right-click database -> backup, select "Schema only"
  • Drop the database
  • Create a new database and name it like the former
  • Right-click the new database -> restore -> select the backup, select "Schema only"

The import org.apache.commons cannot be resolved in eclipse juno

You could just add one needed external jar file to the project. Go to your project-->java build path-->libraries, add external JARS.Then add your downloaded file from the formal website. My default name is commons-codec-1.10.jar

How do I write a Windows batch script to copy the newest file from a directory?

@Chris Noe

Note that the space in front of the & becomes part of the previous command. That has bitten me with SET, which happily puts trailing blanks into the value.

To get around the trailing-space being added to an environment variable, wrap the set command in parens.

E.g. FOR /F %%I IN ('DIR "*.*" /B /O:D') DO (SET NewestFile=%%I)

how do I give a div a responsive height

I know this is a little late to the party but you could use viewport units

From caniuse.com:

Viewport units: vw, vh, vmin, vmax - CR Length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).

Support: http://caniuse.com/#feat=viewport-units

_x000D_
_x000D_
div {_x000D_
/* 25% of viewport */_x000D_
  height: 25vh;_x000D_
  width: 15rem;_x000D_
  background-color: #222;_x000D_
  color: #eee;_x000D_
  font-family: monospace;_x000D_
  padding: 2rem;_x000D_
}
_x000D_
<div>responsive height</div>
_x000D_
_x000D_
_x000D_

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

How do you specify the Java compiler version in a pom.xml file?

Generally you don't want to value only the source version (javac -source 1.8 for example) but you want to value both the source and the target version (javac -source 1.8 -target 1.8 for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9).
Maven that wraps the javac command provides multiple ways to convey all these JVM standard options.

How to specify the JDK version?

Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties to specify the source and the target are equivalent.

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

and

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

are equivalent according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

<release> tag — new way to specify Java version in maven-compiler-plugin 3.6

You can use the release argument :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>9</release>
    </configuration>
</plugin>

You could also declare just the user property maven.compiler.release:

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time the last one will not be enough as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.

Which is the best way to specify the JDK version?

Java 8 and below

Neither maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin is better. It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Java 9 and later

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

How to check if running as root in a bash script

The problem using: id -u, $EUID and whoami is all of them give false positive when I fake the root, for example:

$ fakeroot

id:

$ id -u
0

EUID:

$ echo $EUID
0

whoami:

$ whoami
root

then a reliable and hacking way is verify if the user has access to the /root directory:

 $ ls /root/ &>/dev/null && is_root=true || is_root=false; echo $is_root

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

You pretty much can't set the value of found. Debugging optimized programs is rarely worth the trouble, the compiler can rearrange the code in ways that it'll in no way correspond to the source code (other than producing the same result), thus confusing debuggers to no end.

How to assign more memory to docker container

If you want to change the default container and you are using Virtualbox, you can do it via the commandline / CLI:

docker-machine stop
VBoxManage modifyvm default --cpus 2
VBoxManage modifyvm default --memory 4096
docker-machine start

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.