Programs & Examples On #Distinct on

PostgreSQL DISTINCT ON with different ORDER BY

Documentation says:

DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).

Official documentation

So you'll have to add the address_id to the order by.

Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id and that result sorted by purchased_at then you're trying to solve a greatest N per group problem which can be solved by the following approaches:

The general solution that should work in most DBMSs:

SELECT t1.* FROM purchases t1
JOIN (
    SELECT address_id, max(purchased_at) max_purchased_at
    FROM purchases
    WHERE product_id = 1
    GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC

A more PostgreSQL-oriented solution based on @hkf's answer:

SELECT * FROM (
  SELECT DISTINCT ON (address_id) *
  FROM purchases 
  WHERE product_id = 1
  ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC

Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another

PHP refresh window? equivalent to F5 page reload?

with php you can use two redirections. It works same as refresh in some issues.

you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.

like this: your page:

<?php
header("location:redirec.php?ref=".$your_url);
?>

redirect.php:

<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>

that worked for me good.

Find position of a node using xpath

You can do this with XSLT but I'm not sure about straight XPath.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="yes" 
              omit-xml-declaration="yes"/>
  <xsl:template match="a/*[text()='tsr']">
    <xsl:number value-of="position()"/>
  </xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

subtract two times in python

datetime.time does not support this, because it's nigh meaningless to subtract times in this manner. Use a full datetime.datetime if you want to do this.

How to prune local tracking branches that do not exist on remote anymore

Using a variant on @wisbucky's answer, I added the following as an alias to my ~/.gitconfig file:

pruneitgood = "!f() { \
    git remote prune origin; \
    git branch -vv | perl -nae 'system(qw(git branch -d), $F[0]) if $F[3] eq q{gone]}'; \
}; f"

With this, a simple git pruneitgood will clean up both local & remote branches that are no longer needed after merges.

Shrinking navigation bar when scrolling down (bootstrap3)

If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/

You can do this so nice like this :

HTML:

<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
    <div class="container-fluid top-header">
        <!--- Rest of code --->
    </div>
</nav>

CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)

nav.navbar {
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;

  background-color: white;
  margin-bottom: 0;
  padding: 25px;
}

.navbar-fixed-top {
  padding: 0;
}

And then add your directive

Directive: (Note you may need to change this.pageYOffset >= 50 from 50 to more or less to fulfill your needs)

angular.module('app')
.directive('scrollNav', function ($window) {
  return function(scope, element, attrs) {
    angular.element($window).bind("scroll", function() {
      if (this.pageYOffset >= 50) {
        scope.scrollDown = true;
      } else {
        scope.scrollDown = false;
      }
      scope.$apply();
    });
  };
});

This will do the job nicely, animated and cool way.

catch forEach last iteration

The 2018 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

initializing a boolean array in java

Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.

It should probably be something like freq[Global.iParameter[2]-1]=false;

You would need to loop through the array to initialize all of it, this line only initializes the last element.

Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.

Best Regards

What are the best PHP input sanitizing functions?

Database Input - How to prevent SQL Injection

  1. Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
    • In the case of non-strings you need to ensure that the data actually is the correct type
    • In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
  2. Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
  3. When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)

You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).

$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);

Output from database - How to prevent XSS (Cross Site Scripting)

Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:

$html['username'] = htmlspecialchars($clean['username'])

And Finally... what you requested

I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.

function filterThis($string) {
    return mysql_real_escape_string($string);
}

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

Quick fix that works for me. Navigate to the root directory of your folder from command line (cmd). then once you are on your root directory, type:

code . 

Then, press enter. Note the ".", don't forget it. Now try to debug and see if you get the same error.

Imitating a blink tag with CSS3 animations

Let me show you a little trick.

As Arkanciscan said, you can use CSS3 transitions. But his solution looks different from the original tag.

What you really need to do is this:

_x000D_
_x000D_
@keyframes blink {_x000D_
  50% {_x000D_
    opacity: 0.0;_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes blink {_x000D_
  50% {_x000D_
    opacity: 0.0;_x000D_
  }_x000D_
}_x000D_
.blink {_x000D_
  animation: blink 1s step-start 0s infinite;_x000D_
  -webkit-animation: blink 1s step-start 0s infinite;_x000D_
}
_x000D_
<span class="blink">Blink</span>
_x000D_
_x000D_
_x000D_

JSfiddle Demo

Secondary axis with twinx(): how to add to legend?

I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                    axes=par2,
                                    offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

plt.draw()
plt.show()

Display array values in PHP

You can use implode to return your array with a string separator.

$withComma = implode(",", $array);

echo $withComma;
// Will display apple,banana,orange

XML Serialize generic list of serializable objects

The easiest way to do it, that I have found.. Apply the System.Xml.Serialization.XmlArray attribute to it.

[System.Xml.Serialization.XmlArray] //This is the part that makes it work
List<object> serializableList = new List<object>();

XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());

serializableList.Add(PersonList);

using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xmlSerializer.Serialize(streamWriter, serializableList);
}

The serializer will pick up on it being an array and serialize the list's items as child nodes.

Excel column number from column name

You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.

Example code:

Activesheet.Range("TableName[ColumnName]").Copy

You can also use :

activesheet.listobjects("TableName[ColumnName]").Copy

You can even use this reference system in worksheet formulas as well. Its very dynamic.

Hope this helps!

How to detect page zoom level in all modern browsers?

My coworker and I used the script from https://github.com/tombigel/detect-zoom. In addition, we also dynamically created a svg element and check its currentScale property. It works great on Chrome and likely most browsers too. On FF the "zoom text only" feature has to be turned off though. SVG is supported on most browsers. At the time of this writing, tested on IE10, FF19 and Chrome28.

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('version', '1.1');
document.body.appendChild(svg);
var z = svg.currentScale;
... more code ...
document.body.removeChild(svg);

How do you create vectors with specific intervals in R?

Use the code

x = seq(0,100,5) #this means (starting number, ending number, interval)

the output will be

[1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75
[17]  80  85  90  95 100

How to store(bitmap image) and retrieve image from sqlite database in android?

Setting Up the database

public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database_name";

    // Table Names
    private static final String DB_TABLE = "table_image";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }
}

Insert in the Database:

public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieving data:

 byte[] image = cursor.getBlob(1);

Note:

  1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
  2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

Below is an Utility class which I hope could help you:

public class DbBitmapUtility {

    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}


Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.

How to check whether an object has certain method/property?

You could write something like that :

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Edit : you can even do an extension method and use it like this

myObject.HasMethod("SomeMethod");

String.equals() with multiple conditions (and one action on result)

if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
  • This is not as fast as using a prepared Set, but it performs no worse than using OR.
  • This doesn't crash when name is NULL (same with Set).
  • I like it because it looks clean

Why is this HTTP request not working on AWS Lambda?

Yes, there's in fact many reasons why you can access AWS Lambda like and HTTP Endpoint.

The architecture of AWS Lambda

It's a microservice. Running inside EC2 with Amazon Linux AMI (Version 3.14.26–24.46.amzn1.x86_64) and runs with Node.js. The memory can be beetwen 128mb and 1gb. When the data source triggers the event, the details are passed to a Lambda function as parameter's.

What happen?

AWS Lambda run's inside a container, and the code is directly uploaded to this container with packages or modules. For example, we NEVER can do SSH for the linux machine running your lambda function. The only things that we can monitor are the logs, with CloudWatchLogs and the exception that came from the runtime.

AWS take care of launch and terminate the containers for us, and just run the code. So, even that you use require('http'), it's not going to work, because the place where this code runs, wasn't made for this.

I have filtered my Excel data and now I want to number the rows. How do I do that?

Try this function:

=SUBTOTAL(3, B$2:B2)

You can find more details in this blog entry.

Removing viewcontrollers from navigation stack

Details

  • Swift 5.1, Xcode 11.3.1

Solution

extension UIViewController {
    func removeFromNavigationController() { navigationController?.removeController(.last) { self == $0 } }
}

extension UINavigationController {
    enum ViewControllerPosition { case first, last }
    enum ViewControllersGroupPosition { case first, last, all }

    func removeController(_ position: ViewControllerPosition, animated: Bool = true,
                          where closure: (UIViewController) -> Bool) {
        var index: Int?
        switch position {
            case .first: index = viewControllers.firstIndex(where: closure)
            case .last: index = viewControllers.lastIndex(where: closure)
        }
        if let index = index { removeControllers(animated: animated, in: Range(index...index)) }
    }

    func removeControllers(_ position: ViewControllersGroupPosition, animated: Bool = true,
                           where closure: (UIViewController) -> Bool) {
        var range: Range<Int>?
        switch position {
            case .first: range = viewControllers.firstRange(where: closure)
            case .last:
                guard let _range = viewControllers.reversed().firstRange(where: closure) else { return }
                let count = viewControllers.count - 1
                range = .init(uncheckedBounds: (lower: count - _range.min()!, upper: count - _range.max()!))
            case .all:
                let viewControllers = self.viewControllers.filter { !closure($0) }
                setViewControllers(viewControllers, animated: animated)
                return
        }
        if let range = range { removeControllers(animated: animated, in: range) }
    }

    func removeControllers(animated: Bool = true, in range: Range<Int>) {
        var viewControllers = self.viewControllers
        viewControllers.removeSubrange(range)
        setViewControllers(viewControllers, animated: animated)
    }

    func removeControllers(animated: Bool = true, in range: ClosedRange<Int>) {
        removeControllers(animated: animated, in: Range(range))
    }
}

private extension Array {
    func firstRange(where closure: (Element) -> Bool) -> Range<Int>? {
        guard var index = firstIndex(where: closure) else { return nil }
        var indexes = [Int]()
        while index < count && closure(self[index]) {
            indexes.append(index)
            index += 1
        }
        if indexes.isEmpty { return nil }
        return Range<Int>(indexes.min()!...indexes.max()!)
    }
}

Usage

removeFromParent()

navigationController?.removeControllers(in: 1...3)

navigationController?.removeController(.first) { $0 != self }

navigationController?.removeController(.last) { $0 != self }

navigationController?.removeControllers(.all) { $0.isKind(of: ViewController.self) }

navigationController?.removeControllers(.first) { !$0.isKind(of: ViewController.self) }

navigationController?.removeControllers(.last) { $0 != self }

Full Sample

Do not forget to paste here the solution code

import UIKit

class ViewController2: ViewController {}

class ViewController: UIViewController {

    private var tag: Int = 0
    deinit { print("____ DEINITED: \(self), tag: \(tag)" ) }

    override func viewDidLoad() {
        super.viewDidLoad()
        print("____ INITED: \(self)")
        let stackView = UIStackView()
        stackView.axis = .vertical
        view.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        stackView.addArrangedSubview(createButton(text: "Push ViewController() white", selector: #selector(pushWhiteViewController)))
        stackView.addArrangedSubview(createButton(text: "Push ViewController() gray", selector: #selector(pushGrayViewController)))
        stackView.addArrangedSubview(createButton(text: "Push ViewController2() green", selector: #selector(pushController2)))
        stackView.addArrangedSubview(createButton(text: "Push & remove previous VC", selector: #selector(pushViewControllerAndRemovePrevious)))
        stackView.addArrangedSubview(createButton(text: "Remove first gray VC", selector: #selector(dropFirstGrayViewController)))
        stackView.addArrangedSubview(createButton(text: "Remove last gray VC", selector: #selector(dropLastGrayViewController)))
        stackView.addArrangedSubview(createButton(text: "Remove all gray VCs", selector: #selector(removeAllGrayViewControllers)))
        stackView.addArrangedSubview(createButton(text: "Remove all VCs exept Last", selector: #selector(removeAllViewControllersExeptLast)))
        stackView.addArrangedSubview(createButton(text: "Remove all exept first and last VCs", selector: #selector(removeAllViewControllersExeptFirstAndLast)))
        stackView.addArrangedSubview(createButton(text: "Remove all ViewController2()", selector: #selector(removeAllViewControllers2)))
        stackView.addArrangedSubview(createButton(text: "Remove first VCs where bg != .gray", selector: #selector(dropFirstViewControllers)))
        stackView.addArrangedSubview(createButton(text: "Remove last VCs where bg == .gray", selector: #selector(dropLastViewControllers)))
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if title?.isEmpty ?? true { title = "First" }
    }

    private func createButton(text: String, selector: Selector) -> UIButton {
        let button = UIButton()
        button.setTitle(text, for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: selector, for: .touchUpInside)
        return button
    }
}

extension ViewController {

    private func createViewController<VC: ViewController>(backgroundColor: UIColor = .white) -> VC {
        let viewController = VC()
        let counter = (navigationController?.viewControllers.count ?? -1 ) + 1
        viewController.tag = counter
        viewController.title = "Controller \(counter)"
        viewController.view.backgroundColor = backgroundColor
        return viewController
    }

    @objc func pushWhiteViewController() {
        navigationController?.pushViewController(createViewController(), animated: true)
    }

    @objc func pushGrayViewController() {
        navigationController?.pushViewController(createViewController(backgroundColor: .lightGray), animated: true)
    }

    @objc func pushController2() {
        navigationController?.pushViewController(createViewController(backgroundColor: .green) as ViewController2, animated: true)
    }

    @objc func pushViewControllerAndRemovePrevious() {
        navigationController?.pushViewController(createViewController(), animated: true)
        removeFromNavigationController()
    }

    @objc func removeAllGrayViewControllers() {
        navigationController?.removeControllers(.all) { $0.view.backgroundColor == .lightGray }
    }

    @objc func removeAllViewControllersExeptLast() {
        navigationController?.removeControllers(.all) { $0 != self }
    }

    @objc func removeAllViewControllersExeptFirstAndLast() {
        guard let navigationController = navigationController, navigationController.viewControllers.count > 1 else { return }
        let lastIndex = navigationController.viewControllers.count - 1
        navigationController.removeControllers(in: 1..<lastIndex)
    }

    @objc func removeAllViewControllers2() {
        navigationController?.removeControllers(.all) { $0.isKind(of: ViewController2.self) }
    }

    @objc func dropFirstViewControllers() {
        navigationController?.removeControllers(.first) { $0.view.backgroundColor != .lightGray }
    }

    @objc func dropLastViewControllers() {
        navigationController?.removeControllers(.last) { $0.view.backgroundColor == .lightGray }
    }

    @objc func dropFirstGrayViewController() {
        navigationController?.removeController(.first) { $0.view.backgroundColor == .lightGray }
    }

    @objc func dropLastGrayViewController() {
        navigationController?.removeController(.last) { $0.view.backgroundColor == .lightGray }
    }
}

Result

enter image description here

typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

Android: Reverse geocoding - getFromLocation

First get Latitude and Longitude using Location and LocationManager class. Now try the code below for Get the city,address info

double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
    List<Address> addresses = gc.getFromLocation(lat, lng, 1);
    StringBuilder sb = new StringBuilder();
    if (addresses.size() > 0) {
        Address address = addresses.get(0);
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
            sb.append(address.getAddressLine(i)).append("\n");
            sb.append(address.getLocality()).append("\n");
            sb.append(address.getPostalCode()).append("\n");
            sb.append(address.getCountryName());
    }

City info is now in sb. Now convert the sb to String (using sb.toString() ).

LINQ with groupby and count

userInfos.GroupBy(userInfo => userInfo.metric)
        .OrderBy(group => group.Key)
        .Select(group => Tuple.Create(group.Key, group.Count()));

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

Finding element in XDocument?

The Elements() method returns an IEnumerable<XElement> containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:

var query = from c in xmlFile.Root.Elements("Band")
            select c;

How to solve "The specified service has been marked for deletion" error

Closing the services console as suggested by a few of the answers here did allow me to remove the service. In my scenario this was only a short term fix since all subsequent reinstalls and removal of the service would require me to take these additional steps. Reviewing my web.config file, it was discovered that there was an error that once fixed, allowed me to easily remove the service without the additional closing of the services console step.

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

Waiting for another flutter command to release the startup lock

I use a Mac with Visual Studio Code and this is what worked:

Shutdown your PC and switch it on again. Don't use the restart function. I restarted 2 times and it didn't work. Only shutdown worked.

PS: I tried out the following:

  1. Delete lockfile;
  2. Run killall -9 dart;
  3. Restart my PC.

But they all didn't work.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns refers to the XML namespace

When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

Note: The namespace URI is not used by the parser to look up information.

The purpose is to give the namespace a unique name. However, often companies use the namespace as a pointer to a web page containing namespace information.

Conversion between UTF-8 ArrayBuffer and String

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}

I have done, with some help from the internet, these little functions, they should solve your problems! Here is the working JSFiddle.

EDIT:

Since the source of the Uint8Array is external and you can't use atob you just need to remove it(working fiddle):

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(encodedString));
    return decodedString;
}

Warning: escape and unescape is removed from web standards. See this.

PKIX path building failed in Java application

On Windows you can try these steps:

  1. Download a root CA certificate from the website.
  2. Find a file jssecacerts in the directory /lib/security with JRE (you can use a comand System.out.println(System.getProperty("java.home"); to find the folder with the current JRE). Make a backup of the file.
  3. Download a program portecle.
  4. Open the jssecacerts file in portecle.
  5. Enter the password: changeit.
  6. Import the downloaded certificate with porticle (Tools > Import Trusted Certificate).
  7. Click Save.
  8. Replace the original file jssecacerts.

How do I redirect with JavaScript?

Compared to window.location="url"; it is much easyer to do just location="url"; I always use that

Output to the same line overwriting previous output?

I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

This is shorter than other non-python 3 solutions, but also more difficult to maintain.

Scheduling Python Script to run every hour accurately

Maybe this can help: Advanced Python Scheduler

Here's a small piece of code from their documentation:

from apscheduler.schedulers.blocking import BlockingScheduler

def some_job():
    print "Decorated job"

scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()

What Regex would capture everything from ' mark to the end of a line?

The appropriate regex would be the ' char followed by any number of any chars [including zero chars] ending with an end of string/line token:

'.*$

And if you wanted to capture everything after the ' char but not include it in the output, you would use:

(?<=').*$

This basically says give me all characters that follow the ' char until the end of the line.

Edit: It has been noted that $ is implicit when using .* and therefore not strictly required, therefore the pattern:

'.* 

is technically correct, however it is clearer to be specific and avoid confusion for later code maintenance, hence my use of the $. It is my belief that it is always better to declare explicit behaviour than rely on implicit behaviour in situations where clarity could be questioned.

Google Map API - Removing Markers

According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/

   function setMapOnAll(map1) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map1);
    }
  }

Next create another function to take away all these markers

 function clearMarker(){
setMapOnAll(null);
}

Then create this final function to erase all the markers when ever this function is called upon.

 function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to

}

Hope that helped good luck

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

Aside from the ternary operator, you can also use Builder widget if you have operation needs to be performed before the condition statement.

Container(
  child: Builder(builder: (context) {
     /// some operation here ...
     if(someCondition) {
       return Text('A');
     }
     else return Text('B');
    })
 )

How can I create an executable JAR with dependencies using Maven?

You can use maven-shade plugin to build a uber jar like below

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

How to get file_get_contents() to work with HTTPS?

HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL. Also, make sure the target server has a valid certificate, the firewall allows outbound connections and allow_url_fopen in php.ini is set to true.

How to cut first n and last n columns?

Cut can take several ranges in -f:

Columns up to 4 and from 7 onwards:

cut -f -4,7-

or for fields 1,2,5,6 and from 10 onwards:

cut -f 1,2,5,6,10-

etc

Fastest way to add an Item to an Array

For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.

Module ArrayExtension
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        If arr IsNot Nothing Then
            Array.Resize(arr, arr.Length + 1)
            arr(arr.Length - 1) = item
        Else
            ReDim arr(0)
            arr(0) = item
        End If

    End Sub
End Module

"SyntaxError: Unexpected token < in JSON at position 0"

In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

Using Composer's Autoload

In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

I was looking to autoload my package files using composer which I have under the dir structure given below.

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4 autoloading specification.

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

"autoload": {
        "psr-4": {
            "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

Bootstrap: how do I change the width of the container?

You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.

Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.

In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.

// Container sizes
// --------------------------------------------------

// Small screen / tablet
@container-tablet:            ((720px + @grid-gutter-width));

// Medium screen / desktop
@container-desktop:           ((940px + @grid-gutter-width));

// Large screen / wide desktop
@container-lg-desktop:        ((1020px + @grid-gutter-width));

Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.

What is difference between Errors and Exceptions?

Error is something that most of the time you cannot handle it.

Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.

try{
  //connect to database 1
}
catch(DatabaseConnctionException err){
  //connect to database 2
  //write the err to log
}

How to select date from datetime column?

Well, using LIKE in statement is the best option WHERE datetime LIKE '2009-10-20%' it should work in this case

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

input type="submit" Vs button tag are they interchangeable?

Use <button> tag instead of <input type="button"..>. It is the advised practice in bootstrap 3.

http://getbootstrap.com/css/#buttons-tags

"Cross-browser rendering

As a best practice, we highly recommend using the <button> element whenever possible to ensure matching cross-browser rendering.

Among other things, there's a Firefox bug that prevents us from setting the line-height of <input>-based buttons, causing them to not exactly match the height of other buttons on Firefox."

whitespaces in the path of windows filepath

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
 Volume in drive C has no label.
 Volume Serial Number is 46A0-BB64

 Directory of c:\ABC\SEM 2\testfiles

13/02/2013  10:20 PM    <DIR>          .
13/02/2013  10:20 PM    <DIR>          ..
13/02/2013  10:20 PM                 0 all.txt
               1 File(s)              0 bytes
               2 Dir(s)  78,929,309,696 bytes free

C:\Users\Gnibbler>

How can I convert an Integer to localized month name in Java?

import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I live in uk was keep on trying for 'us-west-2'region. So redirected to 'eu-west-2'. The correct region for S3 is 'eu-west-2'

Test if numpy array contains only zeros

If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.

try: # removes output noise for empty slice 
    mean = np.mean(array)
except:
    mean = 0

How to vertically center a container in Bootstrap?

Give the container class

.container{
    height: 100vh;
    width: 100vw;
    display: flex;
}

Give the div that's inside the container:

align-content: center;

All the content inside this div will show up in the middle of the page.

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

How to get the first element of the List or Set?

See the javadoc

of List

list.get(0);

or Set

set.iterator().next();

and check the size before using the above methods by invoking isEmpty()

!list_or_set.isEmpty()

JavaScript function in href vs. onclick

First, having the url in href is best because it allows users to copy links, open in another tab, etc.

In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.

Typical Bind Method

Normal link:

<a href="https://www.google.com/">Google<a/>

And something like this for JS:

$("a").click(function (e) {
    e.preventDefault();
    var href = $(this).attr("href");
    window.open(href);
    return false;
});

The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.

No Bind Method

If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:

<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>

And this for JS:

function Handler(self, e) {
    e.preventDefault();
    var href = $(self).attr("href");
    window.open(href);
    return false;
}

The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.

Relative URLs in WordPress

Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.

I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.

Failed to execute 'createObjectURL' on 'URL':

I had the same error for the MediaStream. The solution is set a stream to the srcObject.

From the docs:

Important: If you still have code that relies on createObjectURL() to attach streams to media elements, you need to update your code to simply set srcObject to the MediaStream directly.

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

How to generate UML diagrams (especially sequence diagrams) from Java code?

You could also give the netbeans UML modeller a try. I have used it to generate javacode that I used in my eclipse projects. You can even import eclipse projects in netbeans and keep the eclipse settings synced with the netbeans project settings.

I tried several UML modellers for eclipse and wasn't satisfied with them. They were either unstable, complicated or just plain ugly. ;-)

Git commit date

The show command may be what you want. Try

git show -s --format=%ci <commit>

Other formats for the date string are available as well. Check the manual page for details.

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

How to run mvim (MacVim) from Terminal?

I'd seriously recommend installing MacVim via MacPorts (sudo port install MacVim).

When installed, MacPorts automatically updates your profile to include /opt/local/bin in your path, and so when mvim is installed as /opt/local/bin/mvim during the install of MacVim you'll find it ready to use straight away.

When you install the MacVim port the MacVim.app bundle is installed in /Applications/MacPorts for you too.

A good thing about going the MacPorts route is that you'll also be able to install git too (sudo port install git-core) and many many other ports. Highly recommended.

How to make an ImageView with rounded corners?

Answer for the question that is redirected here: "How to create a circular ImageView in Android?"

public static Bitmap getRoundBitmap(Bitmap bitmap) {

    int min = Math.min(bitmap.getWidth(), bitmap.getHeight());

    Bitmap bitmapRounded = Bitmap.createBitmap(min, min, bitmap.getConfig());

    Canvas canvas = new Canvas(bitmapRounded);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min/2, min/2, paint);

    return bitmapRounded;
}

Rounding a double value to x number of decimal places in swift

A handy way can be the use of extension of type Double

extension Double {
    var roundTo2f: Double {return Double(round(100 *self)/100)  }
    var roundTo3f: Double {return Double(round(1000*self)/1000) }
}

Usage:

let regularPie:  Double = 3.14159
var smallerPie:  Double = regularPie.roundTo3f  // results 3.142
var smallestPie: Double = regularPie.roundTo2f  // results 3.14

Converting an int into a 4 byte char array (C)

An int is equivalent to uint32_t and char to uint8_t.

I'll show how I resolved client-server communication, sending the actual time (4 bytes, formatted in Unix epoch) in a 1-bit array, and then re-built it in the other side. (Note: the protocol was to send 1024 bytes)

  • Client side

    uint8_t message[1024];
    uint32_t t = time(NULL);
    
    uint8_t watch[4] = { t & 255, (t >> 8) & 255, (t >> 16) & 255, (t >> 
    24) & 255 };
    
    message[0] = watch[0];
    message[1] = watch[1];
    message[2] = watch[2];
    message[3] = watch[3];
    send(socket, message, 1024, 0);
    
  • Server side

    uint8_t res[1024];
    uint32_t date;
    
    recv(socket, res, 1024, 0);
    
    date = res[0] + (res[1] << 8) + (res[2] << 16) + (res[3] << 24);
    
    printf("Received message from client %d sent at %d\n", socket, date);
    

Hope it helps.

How to compress an image via Javascript in the browser?

I find that there's simpler solution compared to the accepted answer.

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

As per your question:

Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it

My solution:

  1. Create a blob with the file directly with URL.createObjectURL(inputFileElement.files[0]).

  2. Same as accepted answer.

  3. Same as accepted answer. Worth mentioning that, canvas size is necessary and use img.width and img.height to set canvas.width and canvas.height. Not img.clientWidth.

  4. Get the scale-down image by canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5). Setting 'image/jpg' has no effect. image/png is also supported. Make a new File object inside the callbackfunction body with let compressedImageBlob = new File([blob]).

  5. Add new hidden inputs or send via javascript . Server doesn't have to decode anything.

Check https://javascript.info/binary for all information. I came up the solution after reading this chapter.


Code:

    <!DOCTYPE html>
    <html>
    <body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" multiple>
      <input type="submit" value="Upload Image" name="submit">
    </form>
    </body>
    </html>

This code looks far less scary than the other answers..

Update:

One has to put everything inside img.onload. Otherwise canvas will not be able to get the image's width and height correctly as the time canvas is assigned.

    function upload(){
        var f = fileToUpload.files[0];
        var fileName = f.name.split('.')[0];
        var img = new Image();
        img.src = URL.createObjectURL(f);
        img.onload = function(){
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(function(blob){
                    console.info(blob.size);
                    var f2 = new File([blob], fileName + ".jpeg");
                    var xhr = new XMLHttpRequest();
                    var form = new FormData();
                    form.append("fileToUpload", f2);
                    xhr.open("POST", "upload.php");
                    xhr.send(form);
            }, 'image/jpeg', 0.5);
        }
    }

3.4MB .png file compression test with image/jpeg argument set.

    |0.9| 777KB |
    |0.8| 383KB |
    |0.7| 301KB |
    |0.6| 251KB |
    |0.5| 219kB |

jQuery removeClass wildcard

A generic function that remove any class starting with begin:

function removeClassStartingWith(node, begin) {
    node.removeClass (function (index, className) {
        return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');
    });
}

http://jsfiddle.net/xa9xS/2900/

_x000D_
_x000D_
var begin = 'color-';_x000D_
_x000D_
function removeClassStartingWith(node, begin) {_x000D_
    node.removeClass (function (index, className) {_x000D_
        return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');_x000D_
    });_x000D_
}_x000D_
_x000D_
removeClassStartingWith($('#hello'), 'color-');_x000D_
_x000D_
console.log($("#hello")[0].className);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="hello" class="color-red color-brown foo bar"></div>
_x000D_
_x000D_
_x000D_

How to split a single column values to multiple column values?

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
      FROM somenames
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

Java Program to test if a character is uppercase/lowercase/number/vowel

You don't need a for loop in your code.

Here is how you can re implement your method

  • If input is between 'A' and 'Z' its uppercase
  • If input is between 'a' and 'z' its lowercase
  • If input is one of 'a,e,i,o,u,A,E,I,O,U' its Vowel
  • Else Consonant

Edit:

Here is hint for you to proceed, Following code snippet gives int values for chars

System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');

Output

a=97
z=122
A=65
Z=90

Here is how you can check if a number x exists between two numbers say a and b

// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b ) 

During comparisons chars can be treated as numbers

If you can combine these hints, you should be able to find what you want ;)

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

How do I add an element to array in reducer of React native redux?

I have a sample

import * as types from '../../helpers/ActionTypes';

var initialState = {
  changedValues: {}
};
const quickEdit = (state = initialState, action) => {

  switch (action.type) {

    case types.PRODUCT_QUICKEDIT:
      {
        const item = action.item;
        const changedValues = {
          ...state.changedValues,
          [item.id]: item,
        };

        return {
          ...state,
          loading: true,
          changedValues: changedValues,
        };
      }
    default:
      {
        return state;
      }
  }
};

export default quickEdit;

How to refresh app upon shaking the device?

You should subscribe as a SensorEventListener, and get the accelerometer data. Once you have it, you should monitor for sudden change in direction (sign) of acceleration on a certain axis. It would be a good indication for the 'shake' movement of device.

How to save and load cookies using Python + Selenium WebDriver

Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:

$ cat work-auth.py
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

CocoaPods Errors on Project Build

update: a podfile.lock is necessary and should not be ignored by version control, it keeps track of the versions of libraries installed at a certain pod install. (It's similar to gemfile.lock and composer.lock for rails and php dependency management, respectively). To learn more please read the docs. Credit goes to cbowns.


In my case, what I did was that I was doing some house cleaning for my project (ie branching out the integration tests as a git submodule.. removing duplicate files etc).. and pushed the final result to a git remote repo.. all the clients who cloned my repo suffered from the above error. Inspired by Hlung's comment above, I realized that there were some dangling pod scripts that were attempting to run against some non-existent files. So I went to my target build phase, and deleted all the remaining phases that had anything to do with cocoa pods (and Hlung's comment he suggests deleting Copy Pods Manifest.lock and copy pod resources.. mine were named different maybe b/c I'm using Xcode 5.. the point being is to delete those dangling build phases)..

Automatically resize images with browser size using CSS

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

for example :

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

and then any images you add simply using the img tag will be flexible

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

Setting a PHP $_SESSION['var'] using jQuery

It works on firefox, if you change onClick() to click() in javascript part.

_x000D_
_x000D_
$("img.foo").click(function()_x000D_
{_x000D_
    // Get the src of the image_x000D_
    var src = $(this).attr("src");_x000D_
_x000D_
    // Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
    $.post("/backend.php", {"img": src});_x000D_
});
_x000D_
_x000D_
_x000D_

Changing image size in Markdown

Combining two answers I came out with a solution, that might not look that pretty,
but It works!

It creates a thumbnail with a specific size that might be clicked to brings you to the max resolutions image.

[<img src="image.png" width="250"/>](image.png)

Here's an example! I tested it on Visual Code and Github. Example markdown

"FATAL: Module not found error" using modprobe

i think there should be entry of your your_module.ko in /lib/modules/uname -r/modules.dep and in /lib/modules/uname -r/modules.dep.bin for "modprobe your_module" command to work

How do I loop through items in a list box and then remove those item?

Everyone else has posted "going backwards" answer, so I'll give the alternative: create a list of items you want to remove, then remove them at the end:

List<string> removals = new List<string>();
foreach (string s in listBox1.Items)
{
    MessageBox.Show(s);
    //do stuff with (s);
    removals.Add(s);
}

foreach (string s in removals)
{
    listBox1.Items.Remove(s);
}

Sometimes the "work backwards" method is better, sometimes the above is better - particularly if you're dealing with a type which has a RemoveAll(collection) method. Worth knowing both though.

How do I implement interfaces in python?

As mentioned by other here:

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

React Native: How to select the next TextInput after pressing the "next" keyboard button?

There is a way to capture tabs in a TextInput. It's hacky, but better than nothing.

Define an onChangeText handler that compares the new input value with the old, checking for a \t. If one is found, advance the field as shown by @boredgames

Assuming the variable username contains the value for the username and setUsername dispatches an action to change it in the store (component state, redux store, etc), do something like this:

function tabGuard (newValue, oldValue, callback, nextCallback) {
  if (newValue.indexOf('\t') >= 0 && oldValue.indexOf('\t') === -1) {
    callback(oldValue)
    nextCallback()
  } else {
    callback(newValue)
  }
}

class LoginScene {
  focusNextField = (nextField) => {
    this.refs[nextField].focus()
  }

  focusOnPassword = () => {
    this.focusNextField('password')
  }

  handleUsernameChange = (newValue) => {
    const { username } = this.props            // or from wherever
    const { setUsername } = this.props.actions // or from wherever

    tabGuard(newValue, username, setUsername, this.focusOnPassword)
  }

  render () {
    const { username } = this.props

    return (
      <TextInput ref='username'
                 placeholder='Username'
                 autoCapitalize='none'
                 autoCorrect={false}
                 autoFocus
                 keyboardType='email-address'
                 onChangeText={handleUsernameChange}
                 blurOnSubmit={false}
                 onSubmitEditing={focusOnPassword}
                 value={username} />
    )
  }
}

Download a div in a HTML page as pdf using javascript

Yes, it's possible to To capture div as PDFs in JS. You can can check the solution provided by https://grabz.it. They have nice and clean JavaScript API which will allow you to capture the content of a single HTML element such as a div or a span.

So, yo use it you will need and app+key and the free SDK. The usage of it is as following:

Let's say you have a HTML:

<div id="features">
    <h4>Acme Camera</h4>
    <label>Price</label>$399<br />
    <label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>

To capture what is under the features id you will need to:

//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret. 
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>

You need to replace the http://www.example.com/my-page.html with your target url and #feature per your CSS selector.

That's all. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.

The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here

Rounded Corners Image in Flutter

Use this Way in this circle image is also working + you have preloader also for network image:

new ClipRRect(
     borderRadius: new BorderRadius.circular(30.0),
     child: FadeInImage.assetNetwork(
          placeholder:'asset/loader.gif',
          image: 'Your Image Path',
      ),
    )

Convert Float to Int in Swift

Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])

  1> Int(3.4)
$R1: Int = 3

php - get numeric index of associative array

All solutions based on array_keys don't work for mixed arrays. Solution is simple:

echo array_search($needle,array_keys($haystack), true);

From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

Android: how to handle button click

I prefer option 4, but it makes intuitive sense to me because I do far too much work in Grails, Groovy, and JavaFX. "Magic" connections between the view and the controller are common in all. It is important to name the method well:

In the view,add the onClick method to the button or other widget:

    android:clickable="true"
    android:onClick="onButtonClickCancel"

Then in the class, handle the method:

public void onButtonClickCancel(View view) {
    Toast.makeText(this, "Cancel pressed", Toast.LENGTH_LONG).show();
}

Again, name the method clearly, something you should do anyway, and the maintenance becomes second-nature.

One big advantage is that you can write unit tests now for the method. Option 1 can do this, but 2 and 3 are more difficult.

Where can I find Android source code online?

You can browse Android SDK samples from your smartphone using "Code Search": https://market.android.com/details?id=sqwady.codesearch

Jquery Ajax Posting json to webservice

Please follow this to by ajax call to webservice of java var param = { feildName: feildValue }; JSON.stringify({data : param})

$.ajax({
            dataType    : 'json',
            type        : 'POST',
            contentType : 'application/json',
            url         : '<%=request.getContextPath()%>/rest/priceGroups',
            data        : JSON.stringify({data : param}),
            success     : function(res) {
                if(res.success == true){
                    $('#alertMessage').html('Successfully price group created.').addClass('alert alert-success fade in');
                    $('#alertMessage').removeClass('alert-danger alert-info');
                    initPriceGroupsList();
                    priceGroupId = 0;
                    resetForm();                                                                    
                }else{                          
                    $('#alertMessage').html(res.message).addClass('alert alert-danger fade in');
                }
                $('#alertMessage').alert();         
                window.setTimeout(function() { 
                    $('#alertMessage').removeClass('in');
                    document.getElementById('message').style.display = 'none';
                }, 5000);
            }
        });

mysql_config not found when installing mysqldb python interface

On my Fedora 23 machine I had to run the following:

sudo dnf install mysql-devel

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

How do I run Selenium in Xvfb?

The easiest way is probably to use xvfb-run:

DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar

xvfb-run does the whole X authority dance for you, give it a try!

Detect if a NumPy array contains at least one non-numeric value?

(np.where(np.isnan(A)))[0].shape[0] will be greater than 0 if A contains at least one element of nan, A could be an n x m matrix.

Example:

import numpy as np

A = np.array([1,2,4,np.nan])

if (np.where(np.isnan(A)))[0].shape[0]: 
    print "A contains nan"
else:
    print "A does not contain nan"

Axios having CORS issue

This work out for me :

in javascript :

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order
          }).then(function (response) {
            console.log(response.data);
          });

and in the backend (.net core) : in startup:

 #region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

and in controller before action

[EnableCors("AllowOrigin")]

Convert Month Number to Month Name Function in SQL

You can use the inbuilt CONVERT function

select CONVERT(varchar(3), Date, 100)  as Month from MyTable.

This will display first 3 characters of month (JAN,FEB etc..)

Convert the values in a column into row names in an existing data frame

This should do:

samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]

So in short, no there is no alternative to reassigning.

Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:

R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
   b c
a  1 A
b  2 B
c  3 C
d  4 D
e  5 E
f  6 F
g  7 G
h  8 H
i  9 I
j 10 J
R> 

Count records for every month in a year

select count(*) 
from table_emp 
 where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'

adb not finding my device / phone (MacOS X)

Tried all the above, the last piece missing was to enable USB Debugging within Developer Options which was hidden on my 4.4 Galaxy Note 10.1.

See item 5.2 from this link.

C# Macro definitions in Preprocessor

I use this to avoid Console.WriteLine(...):

public static void Cout(this string str, params object[] args) { 
    Console.WriteLine(str, args);
}

and then you can use the following:

"line 1".Cout();
"This {0} is an {1}".Cout("sentence", "example");

it's concise and kindof funky.

How to get ID of the last updated row in MySQL?

I've found an answer to this problem :)

SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1; 
SELECT @update_id;

EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;

This will return a string with all the IDs concatenated by a comma.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Issue with background color in JavaFX 8

Both these work for me. Maybe post a complete example?

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneBackgroundTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        VBox vbox = new VBox();
        root.setCenter(vbox);

        ToggleButton toggle = new ToggleButton("Toggle color");
        HBox controls = new HBox(5, toggle);
        controls.setAlignment(Pos.CENTER);
        root.setBottom(controls);

//        vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
//                .then("-fx-background-color: cornflowerblue;")
//                .otherwise("-fx-background-color: white;"));

        vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
                .then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
                .otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Redraw datatables after using ajax to refresh the table content?

check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

Check if value already exists within list of dictionaries?

Perhaps a function along these lines is what you're after:

 def add_unique_to_dict_list(dict_list, key, value):
  for d in dict_list:
     if key in d:
        return d[key]

  dict_list.append({ key: value })
  return value

What is the difference between decodeURIComponent and decodeURI?

encodeURIComponent/decodeURIComponent() is almost always the pair you want to use, for concatenating together and splitting apart text strings in URI parts.

encodeURI in less common, and misleadingly named: it should really be called fixBrokenURI. It takes something that's nearly a URI, but has invalid characters such as spaces in it, and turns it into a real URI. It has a valid use in fixing up invalid URIs from user input, and it can also be used to turn an IRI (URI with bare Unicode characters in) into a plain URI (using %-escaped UTF-8 to encode the non-ASCII).

decodeURI decodes the same characters as decodeURIComponent except for a few special ones. It is provided to be an inverse of encodeURI, but you still can't count on it to return the same as you originally put in — see eg. decodeURI(encodeURI('%20 '));.

Where encodeURI should really be named fixBrokenURI(), decodeURI() could equally be called potentiallyBreakMyPreviouslyWorkingURI(). I can think of no valid use for it anywhere; avoid.

java.util.Date and getYear()

This behavior is documented in the java.util.Date -class documentation:

Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

It is also marked as deprecated. Use java.util.Calendar instead.

Swift - Remove " character from string

If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])

Throw HttpResponseException or return Request.CreateErrorResponse?

The approach I have taken is to just throw exceptions from the api controller actions and have an exception filter registered that processes the exception and sets an appropriate response on the action execution context.

The filter exposes a fluent interface that provides a means of registering handlers for specific types of exceptions prior to registering the filter with global configuration.

The use of this filter enables centralized exception handling instead of spreading it across the controller actions. There are however cases where I will catch exceptions within the controller action and return a specific response if it does not make sense to centralize the handling of that particular exception.

Example registration of filter:

GlobalConfiguration.Configuration.Filters.Add(
    new UnhandledExceptionFilterAttribute()
    .Register<KeyNotFoundException>(HttpStatusCode.NotFound)

    .Register<SecurityException>(HttpStatusCode.Forbidden)

    .Register<SqlException>(
        (exception, request) =>
        {
            var sqlException = exception as SqlException;

            if (sqlException.Number > 50000)
            {
                var response            = request.CreateResponse(HttpStatusCode.BadRequest);
                response.ReasonPhrase   = sqlException.Message.Replace(Environment.NewLine, String.Empty);

                return response;
            }
            else
            {
                return request.CreateResponse(HttpStatusCode.InternalServerError);
            }
        }
    )
);

UnhandledExceptionFilterAttribute class:

using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;

namespace Sample
{
    /// <summary>
    /// Represents the an attribute that provides a filter for unhandled exceptions.
    /// </summary>
    public class UnhandledExceptionFilterAttribute : ExceptionFilterAttribute
    {
        #region UnhandledExceptionFilterAttribute()
        /// <summary>
        /// Initializes a new instance of the <see cref="UnhandledExceptionFilterAttribute"/> class.
        /// </summary>
        public UnhandledExceptionFilterAttribute() : base()
        {

        }
        #endregion

        #region DefaultHandler
        /// <summary>
        /// Gets a delegate method that returns an <see cref="HttpResponseMessage"/> 
        /// that describes the supplied exception.
        /// </summary>
        /// <value>
        /// A <see cref="Func{Exception, HttpRequestMessage, HttpResponseMessage}"/> delegate method that returns 
        /// an <see cref="HttpResponseMessage"/> that describes the supplied exception.
        /// </value>
        private static Func<Exception, HttpRequestMessage, HttpResponseMessage> DefaultHandler = (exception, request) =>
        {
            if(exception == null)
            {
                return null;
            }

            var response            = request.CreateResponse<string>(
                HttpStatusCode.InternalServerError, GetContentOf(exception)
            );
            response.ReasonPhrase   = exception.Message.Replace(Environment.NewLine, String.Empty);

            return response;
        };
        #endregion

        #region GetContentOf
        /// <summary>
        /// Gets a delegate method that extracts information from the specified exception.
        /// </summary>
        /// <value>
        /// A <see cref="Func{Exception, String}"/> delegate method that extracts information 
        /// from the specified exception.
        /// </value>
        private static Func<Exception, string> GetContentOf = (exception) =>
        {
            if (exception == null)
            {
                return String.Empty;
            }

            var result  = new StringBuilder();

            result.AppendLine(exception.Message);
            result.AppendLine();

            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                result.AppendLine(innerException.Message);
                result.AppendLine();
                innerException = innerException.InnerException;
            }

            #if DEBUG
            result.AppendLine(exception.StackTrace);
            #endif

            return result.ToString();
        };
        #endregion

        #region Handlers
        /// <summary>
        /// Gets the exception handlers registered with this filter.
        /// </summary>
        /// <value>
        /// A <see cref="ConcurrentDictionary{Type, Tuple}"/> collection that contains 
        /// the exception handlers registered with this filter.
        /// </value>
        protected ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> Handlers
        {
            get
            {
                return _filterHandlers;
            }
        }
        private readonly ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> _filterHandlers = new ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>>();
        #endregion

        #region OnException(HttpActionExecutedContext actionExecutedContext)
        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="actionExecutedContext">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if(actionExecutedContext == null || actionExecutedContext.Exception == null)
            {
                return;
            }

            var type    = actionExecutedContext.Exception.GetType();

            Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;

            if (this.Handlers.TryGetValue(type, out registration))
            {
                var statusCode  = registration.Item1;
                var handler     = registration.Item2;

                var response    = handler(
                    actionExecutedContext.Exception.GetBaseException(), 
                    actionExecutedContext.Request
                );

                // Use registered status code if available
                if (statusCode.HasValue)
                {
                    response.StatusCode = statusCode.Value;
                }

                actionExecutedContext.Response  = response;
            }
            else
            {
                // If no exception handler registered for the exception type, fallback to default handler
                actionExecutedContext.Response  = DefaultHandler(
                    actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
                );
            }
        }
        #endregion

        #region Register<TException>(HttpStatusCode statusCode)
        /// <summary>
        /// Registers an exception handler that returns the specified status code for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to register a handler for.</typeparam>
        /// <param name="statusCode">The HTTP status code to return for exceptions of type <typeparamref name="TException"/>.</param>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler has been added.
        /// </returns>
        public UnhandledExceptionFilterAttribute Register<TException>(HttpStatusCode statusCode) 
            where TException : Exception
        {

            var type    = typeof(TException);
            var item    = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
                statusCode, DefaultHandler
            );

            if (!this.Handlers.TryAdd(type, item))
            {
                Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;

                if (this.Handlers.TryRemove(type, out oldItem))
                {
                    this.Handlers.TryAdd(type, item);
                }
            }

            return this;
        }
        #endregion

        #region Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
        /// <summary>
        /// Registers the specified exception <paramref name="handler"/> for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to register the <paramref name="handler"/> for.</typeparam>
        /// <param name="handler">The exception handler responsible for exceptions of type <typeparamref name="TException"/>.</param>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception <paramref name="handler"/> 
        /// has been added.
        /// </returns>
        /// <exception cref="ArgumentNullException">The <paramref name="handler"/> is <see langword="null"/>.</exception>
        public UnhandledExceptionFilterAttribute Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler) 
            where TException : Exception
        {
            if(handler == null)
            {
              throw new ArgumentNullException("handler");
            }

            var type    = typeof(TException);
            var item    = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
                null, handler
            );

            if (!this.Handlers.TryAdd(type, item))
            {
                Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;

                if (this.Handlers.TryRemove(type, out oldItem))
                {
                    this.Handlers.TryAdd(type, item);
                }
            }

            return this;
        }
        #endregion

        #region Unregister<TException>()
        /// <summary>
        /// Unregisters the exception handler for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to unregister handlers for.</typeparam>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler 
        /// for exceptions of type <typeparamref name="TException"/> has been removed.
        /// </returns>
        public UnhandledExceptionFilterAttribute Unregister<TException>()
            where TException : Exception
        {
            Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> item = null;

            this.Handlers.TryRemove(typeof(TException), out item);

            return this;
        }
        #endregion
    }
}

Source code can also be found here.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

(more of a functional note)

There are cases when you have to use GROUP BY, for example if you wanted to get the number of employees per employer:

SELECT u.employer, COUNT(u.id) AS "total employees" FROM users u GROUP BY u.employer

In such a scenario DISTINCT u.employer doesn't work right. Perhaps there is a way, but I just do not know it. (If someone knows how to make such a query with DISTINCT please add a note!)

height style property doesn't work in div elements

This worked for me:

min-height: 14px;
height: 14px;

JS how to cache a variable

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

Open a Web Page in a Windows Batch FIle

Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,

start "iexplore.exe" http://www.website.com

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

If statement with String comparison fails

To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:

In Java there are many string comparisons.

String s = "something", t = "maybe something else";
if (s == t)      // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

Check if a process is running or not on Windows with Python

Would you be happy with your Python command running another program to get the info?

If so, I'd suggest you have a look at PsList and all its options. For example, The following would tell you about any running iTunes process

PsList itunes

If you can work out how to interpret the results, this should hopefully get you going.

Edit:

When I'm not running iTunes, I get the following:

pslist v1.29 - Sysinternals PsList
Copyright (C) 2000-2009 Mark Russinovich
Sysinternals

Process information for CLARESPC:

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
iTunesHelper       3784   8  10  229   3164     0:00:00.046     3:41:05.053

With itunes running, I get this one extra line:

iTunes              928   8  24  813 106168     0:00:08.734     0:02:08.672

However, the following command prints out info only about the iTunes program itself, i.e. with the -e argument:

pslist -e itunes

Apply .gitignore on an existing repository already tracking large number of files

Use git clean
Get help on this running

git clean -h

If you want to see what would happen first, make sure to pass the -n switch for a dry run:

git clean -xn

To remove gitingnored garbage

git clean -xdf

Careful: You may be ignoring local config files like database.yml which would also be removed. Use at your own risk.

Then

git add .
git commit -m ".gitignore is now working"
git push

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

expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.

if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish

shell init issue when click tab, what's wrong with getcwd?

Yes, cd; and cd - would work. The reason It can see is that, directory is being deleted from any other terminal or any other program and recreate it. So i-node entry is modified so program can not access old i-node entry.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

It means you don't have privileges to create the trigger with root@localhost user..

try removing definer from the trigger command:

CREATE DEFINER = root@localhost FUNCTION fnc_calcWalkedDistance

How to run Maven from another directory (without cd to project dir)?

I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:

user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$

As a bash function (which you could add to your ~/.bashrc):

function mvn-there() {
  DIR="$1"
  shift
  (cd $DIR; mvn "$@")     
} 

user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$

I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.

Regards

How can I find the maximum value and its index in array in MATLAB?

3D case

Modifying Mohsen's answer for 3D array:

[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)

how to assign a block of html code to a javascript variable

Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.

First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:

var code = '<div class="my-class"> \
        <h1>The Header</h1> \
        <p>The paragraph of text</p> \
        <div class="my-quote"> \
            <p>The quote I\'d like to put in a div</p> \
        </div> \
    </div>';

Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)

Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!

How to find an available port?

Starting from Java 1.7 you can use try-with-resources like this:

  private Integer findRandomOpenPortOnAllLocalInterfaces() throws IOException {
    try (
        ServerSocket socket = new ServerSocket(0);
    ) {
      return socket.getLocalPort();

    }
  }

If you need to find an open port on a specific interface check ServerSocket documentation for alternative constructors.

Warning: Any code using the port number returned by this method is subject to a race condition - a different process / thread may bind to the same port immediately after we close the ServerSocket instance.

How to calculate the time interval between two time strings

Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration):

#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta

def time_diff(start, end):
    if isinstance(start, datetime_time): # convert to datetime
        assert isinstance(end, datetime_time)
        start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
    if start <= end: # e.g., 10:33:26-11:15:49
        return end - start
    else: # end < start e.g., 23:55:00-00:25:00
        end += timedelta(1) # +day
        assert end > start
        return end - start

for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
    s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
    print(time_diff(s, e))
    assert time_diff(s, e) == time_diff(s.time(), e.time())

Output

0:42:23
0:30:00

time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.:

#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
    """Find arithmetic average."""
    return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
        timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds

The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.

Using textures in THREE.js

Without Error Handeling

//Load background texture
 new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
            {
             scene.background = texture;  
            });

With Error Handling

// Function called when download progresses
var onProgress = function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};

// Function called when download errors
var onError = function (error) {
  console.log('An error happened'+error);
};

//Function  called when load completes.
var onLoad = function (texture) {
  var objGeometry = new THREE.BoxGeometry(30, 30, 30);
  var objMaterial = new THREE.MeshPhongMaterial({
    map: texture,
    shading: THREE.FlatShading
  });

  var boxMesh = new THREE.Mesh(objGeometry, objMaterial);
  scene.add(boxMesh);

  var render = function () {
    requestAnimationFrame(render);
    boxMesh.rotation.x += 0.010;
    boxMesh.rotation.y += 0.010;
      sphereMesh.rotation.y += 0.1;
    renderer.render(scene, camera);
  };

  render();
}


//LOAD TEXTURE and on completion apply it on box
var loader = new THREE.TextureLoader();
    loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/1920px-The_Earth_seen_from_Apollo_17.jpg', 
                onLoad, 
                onProgress, 
                onError);

Result:

enter image description here

https://codepen.io/hiteshsahu/pen/jpGLpq/

How do you load custom UITableViewCells from Xib files?

I've decided to post since I don't like any of these answers -- things can always be more simple and this is by far the most concise way I've found.

1. Build your Xib in Interface Builder as you like it

  • Set File's Owner to class NSObject
  • Add a UITableViewCell and set its class to MyTableViewCellSubclass -- if your IB crashes (happens in Xcode > 4 as of this writing), just use a UIView of do the interface in Xcode 4 if you still have it laying around
  • Layout your subviews inside this cell and attach your IBOutlet connections to your @interface in the .h or .m (.m is my preference)

2. In your UIViewController or UITableViewController subclass

@implementation ViewController

static NSString *cellIdentifier = @"MyCellIdentier";

- (void) viewDidLoad {

    ...
    [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCellSubclass" bundle:nil] forCellReuseIdentifier:cellIdentifier];
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCellSubclass *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    ...

    return cell;
}

3. In your MyTableViewCellSubclass

- (id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        ...
    }

    return self;
}

How to convert a string to lower or upper case in Ruby

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

"hello James!".downcase    #=> "hello james!"

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!"
string.downcase!
string   #=> "hello james!"

Refer to the documentation for String for more information.

Count number of occurrences of a pattern in a file (even on same line)

Try this:

grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c

Sample:

grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
  6  SMTP connect from unknown [188.190.118.90]
 54  SMTP connect from unknown [62.193.131.114]
  3  SMTP connect from unknown [91.222.51.253]

Get parent of current directory from Python script

You can simply use../your_script_name.py For example suppose the path to your python script is trading system/trading strategies/ts1.py. To refer to volume.csv located in trading system/data/. You simply need to refer to it as ../data/volume.csv

Looping over elements in jQuery

This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.

EDIT JSFIDDLE

The below will work

$('form[name=formName]').find('input, textarea, select').each(function() {
    alert($(this).attr('name'));
});

Hashing a file in Python

import hashlib
user = input("Enter ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
with open("encrypted.txt","w") as e:
    print(h2,file=e)


with open("encrypted.txt","r") as e:
    p = e.readline().strip()
    print(p)

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to uninstall Jenkins?

My Jenkins version: 1.5.39

Execute steps:

Step 1. Go to folder /Library/Application Support/Jenkins

Step 2. Run Uninstall.command jenkins-runner.sh file.

Step 3. Check result.

It work for me.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

How to find substring inside a string (or how to grep a variable)?

expr match "$LIST" '$SOURCE'

don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:

expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"

The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also

expr "$LIST" : ".*\($SOURCE\)"

This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

How to pass objects to functions in C++?

There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.

Pass by reference

Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.

Pass by value (and pass-by-pointer)

The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.

An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).

This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.

Adding const to the equation

In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).

This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.

Rules of thumb

This are some basic rules to follow:

  • Prefer pass-by-value for primitive types
  • Prefer pass-by-reference with references to constant for other types
  • If the function needs to modify the argument use pass-by-reference
  • If the argument is optional, use pass-by-pointer (to constant if the optional value should not be modified)

There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.

Side note

It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:

// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {
   Type tmp = a;
   a = b;
   b = tmp;
}
int main() {
   Type a, b;
   Type old_a = a, old_b = b;
   swap( a, b );
   assert( a == old_b );
   assert( b == old_a ); 
}

The swap function above changes both its arguments through the use of references. The closest code in Java:

public class C {
   // ...
   public static void swap( C a, C b ) {
      C tmp = a;
      a = b;
      b = tmp;
   }
   public static void main( String args[] ) {
      C a = new C();
      C b = new C();
      C old_a = a;
      C old_b = b;
      swap( a, b ); 
      // a and b remain unchanged a==old_a, and b==old_b
   }
}

The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.

Get the client's IP address in socket.io

I have found that within the socket.handshake.headers there is a forwarded for address which doesn't appear on my local machine. And I was able to get the remote address using:

socket.handshake.headers['x-forwarded-for']

This is in the server side and not client side.

Refresh Page C# ASP.NET

I think this should do the trick (untested):

Page.Response.Redirect(Page.Request.Url.ToString(), true);

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

If you use android studio, this might be useful for you.

I had a similar problem and i solved it by changing the skd path from the default C:\Program Files (x86)\Android\android-studio\sdk to C:\Program Files (x86)\Android\android-sdk .

It seems the problem came from the compiler version (gradle sets it automatically to the highest one available in the sdk folder) which doesn't support this theme, and since android studio had only the api 7 in its sdk folder, it gave me this error.

For more information on how to change Android sdk path in Android Studio: Android Studio - How to Change Android SDK Path

How to make a Div appear on top of everything else on the screen?

Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position other than static set on it, too.

CSS:

#someDiv {
    z-index:9; 
}

Read more here: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/

Difference between RUN and CMD in a Dockerfile

Note: Don’t confuse RUN with CMD. RUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.

from docker file reference

https://docs.docker.com/engine/reference/builder/#cmd

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

How to do case insensitive string comparison?

Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).

function compareStrings (string1, string2, ignoreCase, useLocale) {
    if (ignoreCase) {
        if (useLocale) {
            string1 = string1.toLocaleLowerCase();
            string2 = string2.toLocaleLowerCase();
        }
        else {
            string1 = string1.toLowerCase();
            string2 = string2.toLowerCase();
        }
    }

    return string1 === string2;
}

How do I change file permissions in Ubuntu

Add -R for recursive:

sudo chmod -R 666 /var/www

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Getting title and meta tags from external website

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

Issue pushing new code in Github

A simpler answer is to manually upload the README.MD file from your computer to GitHub. Worked very well for me.

Fail during installation of Pillow (Python module) in Linux

There is a bug reported for Pillow here, which indicates that libjpeg and zlib are now required as of Pillow 3.0.0.

The installation instructions for Pillow on Linux give advice of how to install these packages. Note that not all of the following packages may be missing on your machine (comments suggest that only libjpeg8-dev is actually missing).

pip / PyPi (Pillow>3.4.2)

The latest releases of Pillow are available on PyPi as wheels — the new standard packaging mechanism for Python. These prebuilt packages include all neccessary binary dependencies to allow Pillow to run and should be used if you want to install Pillow using PyPi

To use wheels, you need to have a version of pip>=1.4. If you are using an earlier version (pip --version) upgrade pip using the following:

pip install --upgrade pip 

Once pip is upgraded, pip install will use platform-specific wheel files by default if they are available. Use the following command to upgrade Pillow to the latest version available on PyPi:

pip install --upgrade pillow

Ubuntu 12.04 LTS or Raspian Wheezy 7.0

sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk

Ubuntu 14.04

sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

Ubuntu 18.04

sudo apt install libjpeg8-dev zlib1g-dev

Fedora 20

The Fedora 20 equivalent of libjpeg8-dev is libjpeg-devel.

sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel

Mac OS X (via Homebrew)

On Mac OS X with Homebrew this can be fixed using:

brew install libjpeg zlib

You may also need to force-link zlib using the following:

brew link zlib --force

Update April 2019: In Mojave the above will not work and you need to run the following as taken from this bug report on Pillow

sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /

Update July 2016: There is no longer a formula for zlib available in the main repository (Homebrew will prompt you to install lzlib which is a different library and will not solve this problem).

There is a formula available in the dupes repository. You can either tap this repository, and install as normal:

brew tap homebrew/dupes
brew install zlib

Or you can install zlib via xcode instead, as follows:

xcode-select --install

Thanks to phoenix, Panos Angelopoulou, nelsonvarela, benjaminz and Kal in the comments

After these are installed the pip installation of Pillow should work normally.

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

CSS3 Rotate Animation

try this easy

_x000D_
_x000D_
 _x000D_
 .btn-circle span {_x000D_
     top: 0;_x000D_
   _x000D_
      position: absolute;_x000D_
     font-size: 18px;_x000D_
       text-align: center;_x000D_
    text-decoration: none;_x000D_
      -webkit-animation:spin 4s linear infinite;_x000D_
    -moz-animation:spin 4s linear infinite;_x000D_
    animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
 color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } } 
_x000D_
 <button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">&#x21bb;</span></button>
_x000D_
_x000D_
_x000D_

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I'd like to add another solution since I didn't see it here. My problem was that heroku was linking to the wrong url (since I kept playing around with url names). Editing the remote url solved my problem:

git remote set-url heroku <heroku-url-here>

Difference between TCP and UDP?

TLDR;

  • TCP - stream-oriented, requires a connection, reliable, slow
  • UDP - message-oriented, connectionless, unreliable, fast

Before we start, remember that all disadvantages of something are a continuation of its advantages. There only a right tool for a job, no panacea. TCP/UDP coexist for decades, and for a reason.

TCP

It was designed to be extremely reliable and it does its job very well. It's so complex because it accomplishes a hard task: providing a reliable transport over the unreliable IP protocol.

Since all TCP's complex logic is encapsulated into the network stack, you are free from doing lots of laborious, error-prone low-level stuff in the application layer.

When you send data over TCP, you write a stream of bytes to the socket at the sender side where it gets broken into packets, passed down the stack and sent over the wire. On the receiver side packets get reassembled again into a continous stream of bytes.

Maintaining this nice abstraction has a cost in terms of complexity and performance. If the 1st packet from the byte stream is lost, the receiver will delay processing of subsequent packets even those have already arrived (the so-called "head of line blocking").

In addition, in order to be reliable, TCP implements this:

  • TCP requires an established connection, which requires 3 round-trips ("infamous" 3-way handshake)
  • TCP has a feature called "slow start" when it gradually ramps up the transmission rate after establishing a connection to allow a receiver to keep up with data rate
  • Every sent packet has to be acknowledged or else a sender will stop sending more data
  • And on and on and on...

All this is exacerbated in slow unreliable wireless networks because TCP was designed for wired networks where delays are predictable and packet loss is not so common. In addition, like many people already mentioned, for some things TCP just doesn't work at all (DHCP). However, where relevant, TCP still does its work exceptionally well.

Using a mail analogy a TCP session is similar to telling a story to your secretary who breaks it into mails and sends over a crappy mail service to a publisher. On the other side another secretary assembles mails into a single piece of text. Some mails get lost, some get corrupted, so a very complex procedure is required for reliable delivery and your 10-page story can take a long time to reach your publisher.

UDP

UDP, on the other hand, is message-oriented, so a receiver writes a message (packet) to the socket and then it gets transmitted to a receiver as-is, without any splitting/assembling in the transport layer.

Compared to TCP, its specification is very straightforward. Essentially, all it does for you is adding a checksum to the packet so a receiver can detect its corruption. Everything else must be implemented by you, a software developer. Now read the voluminous TCP spec and try thinking of re-implementing even a small subset of it.

Some people went this way and got very decent results, to the point that HTTP/3 uses QUIC - a protocol based on UDP. However, this is more of an exception. Common applications of UDP are audio/video streaming and conferencing applications like Skype, Zoom or Google Hangout where loosing packets is not so important compared to a delay introduced by TCP.

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

Download a file from HTTPS using download.file()

Here's an update as of Nov 2014. I find that setting method='curl' did the trick for me (while method='auto', does not).

For example:

# does not work
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
              destfile='localfile.zip')

# does not work. this appears to be the default anyway
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
              destfile='localfile.zip', method='auto')

# works!
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
              destfile='localfile.zip', method='curl')

Subdomain on different host

sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g

mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain

anothersite.mydomain.com

of which the site is actually on another server then

login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11

And that's it.

JAVA_HOME is set to an invalid directory:

After isntalling jdk please restart your system this works for me

How to change collation of database, table, column?

Generates query to update each table and column of each table.

I have used this to some of my projects before and was able to solved most of my COLLATION problems. (especially on JOINS XD) Hope some of you find it useful.

To use, just export results to delimited text (probably new line '\n')

-- EACH TABLE
SELECT CONCAT('ALTER TABLE ', TABLE_NAME,' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;') AS 'USE DATABASE_NAME;' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DATABASE_NAME' AND TABLE_TYPE LIKE 'BASE TABLE'

-- EACH COLUMN
SELECT CONCAT('ALTER TABLE ', TABLE_NAME,' MODIFY COLUMN ', COLUMN_NAME,' ', DATA_TYPE, IF(CHARACTER_MAXIMUM_LENGTH IS NULL OR DATA_TYPE LIKE 'longtext', '', CONCAT('(',CHARACTER_MAXIMUM_LENGTH,')')),' COLLATE utf8mb4_unicode_ci;') AS 'USE DATABASE_NAME;' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'DATABASE_NAME' AND (SELECT INFORMATION_SCHEMA.TABLES.TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA = INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA AND INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME LIMIT 1) LIKE 'BASE TABLE' AND DATA_TYPE IN ('char','varchar') /* include other types if necessary */

how to toggle attr() in jquery

$(".list-toggle").click(function() {
    $(this).attr('colspan') ? 
    $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

jQuery DatePicker with today as maxDate

If you're using bootstrap 3 date time picker, try this:

$('.selector').datetimepicker({ maxDate: $.now() });

Xcode 7.2 no matching provisioning profiles found

Using Xcode 7.3, I spent way too much time trying to figure this out -- none of the answers here or elsewhere did the trick -- and ultimately stumbled into a ridiculously easy solution.

  1. In the Xcode preferences team settings, delete all provisioning profiles as mentioned in several other answers. I do this with right click, "Show in Finder," Command+A, delete -- it seems these details have changed over different Xcode versions.
  2. Do not re-download any profiles. Instead, exit your preferences and rebuild your project (I built it for my connected iPhone). A little while into the build sequence there will be an alert informing you no provisioning profiles were found, and it will ask if you want this to be fixed automatically. Choose to fix it automatically.
  3. After Xcode does some stuff, you will magically have a new provisioning profile providing what your app needs. I have since uploaded my app for TestFlight and it works great.

Hope this helps someone.

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

I had a similar problem when deploying one of my portlets. The portlet has been developed for Liferay 6.2 on Windows. My runtime environment is Tomcat 7 running on JRE 1.6 (JRockit 1.6). I have recently migrated to Eclipse 2019-3. I checked my Java Build Path (Project->Properties, Libraries tab). I noticed that the Apache Tomcat that is specified in the list of JARs and class folders on the build path was unbound. I selected that item. I clicked on the Edit button. Server Libary dialog was opened. I selected the correct Apache Tomcat. After applying the change, I redeployed the portlet and the problem was resolved.

Sometimes you may need to delete the problematic portlet from the [Tomcat]/webapps directory before deploying the corrected portlet. Also, sometimes I have experienced that deployment of a portlet takes more than usual, and redeploying it resolves the issue.

How to change the integrated terminal in visual studio code or VSCode

To change the integrated terminal on Windows, you just need to change the terminal.integrated.shell.windows line:

  1. Open VS User Settings (Preferences > User Settings). This will open two side-by-side documents.
  2. Add a new "terminal.integrated.shell.windows": "C:\\Bin\\Cmder\\Cmder.exe" setting to the User Settings document on the right if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.
  3. Save the User Settings file.

You can then access it with keys Ctrl+backtick by default.

Git Bash is extremely slow on Windows 7 x64

While your problem might be network-based, I've personally sped up my local git status calls tenfold (7+ seconds down to 700 ms) by doing two modifications. This is on a 700 MB repository with 21,000 files and excessive numbers of large binary files.

One is enabling parallel index preloads. From a command prompt:

git config core.preloadindex true
This changed time git status from 7 seconds to 2.5 seconds.

Update!

The following is no longer necessary. A patch has fixed this as of mysysgit 1.9.4
https://github.com/msysgit/git/commit/64d63240762df22e92b287b145d75a0d68a66988
However, you must enable the fix by typing
git config core.fscache true

I also disabled the UAC and the "luafv" driver (reboot required). This disables a driver in Windows Vista, 7 and 8 that redirects programs trying to write to system locations and instead redirects those accesses to a user directory.

To see a discussion on how this affects Git performance, read here: https://code.google.com/p/msysgit/issues/detail?id=320

To disable this driver, in regedit, change the "start" key at HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/luafv to 4 to disable the driver. Then, put UAC to its lowest setting, "never notify".

If the disabling of this driver makes you wary (it should), an alternative is running on a drive (or partition) different than your system partition. Apparently the driver only runs on file access on the system partition. I have a second hard drive and see identical results when run with this registry modification on my C drive as I do without it on the D drive.

This change takes time git status from 2.5 seconds down to 0.7 seconds.

You also might want to follow https://github.com/msysgit/git/pull/94 and https://github.com/git/git/commit/d637d1b9a8fb765a8542e69bd2e04b3e229f663b to check out what additional work is underway for speed issues in Windows.

Count the number of commits on a Git branch

If you are using a UNIX system, you could do

git log|grep "Author"|wc -l

Jquery Date picker Default Date

interesting, datepicker default date is current date as I found,

but you can set date by

$("#yourinput").datepicker( "setDate" , "7/11/2011" );

don't forget to check you system date :)

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Then NumPy sum function takes an optional axis argument that specifies along which axis you would like the sum performed:

>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])

Or, equivalently:

>>> numpy.sum(a, 0)
array([18, 22, 26])

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

How do I retrieve an HTML element's actual width and height?

Flex

In case that you want to display in your <div> some kind of popUp message on screen center - then you don't need to read size of <div> but you can use flex

_x000D_
_x000D_
.box {
  width: 50px;
  height: 20px;
  background: red;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
}
_x000D_
<div class="container">
  <div class="box">My div</div>
</div>
_x000D_
_x000D_
_x000D_

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

How to delete a cookie using jQuery?

What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.

Pytorch tensor to numpy array

You can use this syntax if some grads are attached with your variables.

y=torch.Tensor.cpu(x).detach().numpy()[:,:,:,-1]

Selecting a Linux I/O Scheduler

The Linux Kernel does not automatically change the IO Scheduler at run-time. By this I mean, the Linux kernel, as of today, is not able to automatically choose an "optimal" scheduler depending on the type of secondary storage devise. During start-up, or during run-time, it is possible to change the IO scheduler manually.

The default scheduler is chosen at start-up based on the contents in the file located at /linux-2.6 /block/Kconfig.iosched. However, it is possible to change the IO scheduler during run-time by echoing a valid scheduler name into the file located at /sys/block/[DEV]/queue/scheduler. For example, echo deadline > /sys/block/hda/queue/scheduler

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to compile multiple java source files in command line

Try the following:

javac file1.java file2.java

Get the generated SQL statement from a SqlCommand object?

I wrote this method for me. I use some part of Bruno Ratnieks's code. Maybe it is useful to someone.

 public static string getQueryFromCommand(SqlCommand cmd)
    {
        StringBuilder CommandTxt = new StringBuilder();
        CommandTxt.Append("DECLARE ");
        List<string> paramlst = new List<string>();
        foreach (SqlParameter parms in cmd.Parameters)
        {
            paramlst.Add(parms.ParameterName);
            CommandTxt.Append(parms.ParameterName + " AS ");
            CommandTxt.Append(parms.SqlDbType.ToString());
            CommandTxt.Append(",");
        }

        if (CommandTxt.ToString().Substring(CommandTxt.Length-1, 1) == ",")
            CommandTxt.Remove(CommandTxt.Length-1, 1);
        CommandTxt.AppendLine();
        int rownr = 0;
        foreach (SqlParameter parms in cmd.Parameters)
        {
            string val = String.Empty;
            if (parms.DbType.Equals(DbType.String) || parms.DbType.Equals(DbType.DateTime))
                val = "'" + Convert.ToString(parms.Value).Replace(@"\", @"\\").Replace("'", @"\'") + "'";
            if (parms.DbType.Equals(DbType.Int16) || parms.DbType.Equals(DbType.Int32) || parms.DbType.Equals(DbType.Int64) || parms.DbType.Equals(DbType.Decimal) || parms.DbType.Equals(DbType.Double))
                val = Convert.ToString(parms.Value);

            CommandTxt.AppendLine();
            CommandTxt.Append("SET " + paramlst[rownr].ToString() + " = " + val.ToString());
            rownr += 1;
        }
        CommandTxt.AppendLine();
        CommandTxt.AppendLine();
        CommandTxt.Append(cmd.CommandText);
        return CommandTxt.ToString();
    }

expand/collapse table rows with JQuery

using jQuery it's easy...

 $('YOUR CLASS SELECTOR').click(function(){

            $(this).toggle();
});

How to urlencode data for curl command?

url=$(echo "$1" | sed -e 's/%/%25/g' -e 's/ /%20/g' -e 's/!/%21/g' -e 's/"/%22/g' -e 's/#/%23/g' -e 's/\$/%24/g' -e 's/\&/%26/g' -e 's/'\''/%27/g' -e 's/(/%28/g' -e 's/)/%29/g' -e 's/\*/%2a/g' -e 's/+/%2b/g' -e 's/,/%2c/g' -e 's/-/%2d/g' -e 's/\./%2e/g' -e 's/\//%2f/g' -e 's/:/%3a/g' -e 's/;/%3b/g' -e 's//%3e/g' -e 's/?/%3f/g' -e 's/@/%40/g' -e 's/\[/%5b/g' -e 's/\\/%5c/g' -e 's/\]/%5d/g' -e 's/\^/%5e/g' -e 's/_/%5f/g' -e 's/`/%60/g' -e 's/{/%7b/g' -e 's/|/%7c/g' -e 's/}/%7d/g' -e 's/~/%7e/g')

this will encode the string inside of $1 and output it in $url. although you don't have to put it in a var if you want. BTW didn't include the sed for tab thought it would turn it into spaces

Array definition in XML?

In XML values in text() nodes.

If we write this

<numbers>1,2,3</numbers>

in element "numbers" will be one text() node with value "1,2,3".

Native way to get many text() nodes in element is insert nodes of other types in text.

Other available types is element or comment() node.

Split with element node:

<numbers>3<_/>2<_/>1</numbers>

Split with comment() node:

<numbers>3<!---->2<!---->1</numbers>

We can select this values by this XPath

//numbers/text()

Select value by index

//numbers/text()[3]

Will return text() node with value "1"

How to produce an csv output file from stored procedure in SQL Server

I have tried this and it is working fine for me:

sqlcmd -S servername -E -s~ -W -k1 -Q  "sql query here" > "\\file_path\file_name.csv"

How to join multiple lines of file names into one with custom delimiter?

If you version of xargs supports the -d flag then this should work

ls  | xargs -d, -L 1 echo

-d is the delimiter flag

If you do not have -d, then you can try the following

ls | xargs -I {} echo {}, | xargs echo

The first xargs allows you to specify your delimiter which is a comma in this example.

How to encode a URL in Swift

Swift 4.1

Create a "Character Set" based on the option you want (urlQueryAllowed). Then remove the additional characters you do not want (+&). Then pass that character set to "addingPercentEncoding".

var address = "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India"
var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&")
let escapedAddress = address.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
let urlpath = String(format: "http://maps.googleapis.com/maps/api/geocode/json?address=\(escapedAddress)")

HorizontalScrollView within ScrollView Touch Handling

Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.

Here is the code for my Scroll View class that contains the HorizontalScrollView:

public class CustomScrollView extends ScrollView {
    private GestureDetector mGestureDetector;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }

    // Return false if we're scrolling in the x direction  
    class YScrollDetector extends SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
            return Math.abs(distanceY) > Math.abs(distanceX);
        }
    }
}

How to output git log with the first line only?

Have you tried this?

git log --pretty=oneline --abbrev-commit

The problem is probably that you are missing an empty line after the first line. The command above usually works for me, but I just tested on a commit without empty second line. I got the same result as you: the whole message on one line.

Empty second line is a standard in git commit messages. The behaviour you see was probably implemented on purpose.

The first line of a commit message is meant to be a short description. If you cannot make it in a single line you can use several, but git considers everything before the first empty line to be the "short description". oneline prints the whole short description, so all your 3 rows.

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

Because it's not actually a dictionary; it's another mapping type that looks like a dictionary. Use type() to verify. Pass it to dict() to get a real dictionary from it.

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().