Programs & Examples On #Hamcrest

Hamcrest is an open source library of constraint classes used to match objects and values, typically by other frameworks such as unit testing, mocking, or collections.

How do I assert an Iterable contains elements with a certain property?

Assertj is good at this.

import static org.assertj.core.api.Assertions.assertThat;

    assertThat(myClass.getMyItems()).extracting("name").contains("foo", "bar");

Big plus for assertj compared to hamcrest is easy use of code completion.

Hamcrest compare collections

Make sure that the Objects in your list have equals() defined on them. Then

assertThat(generatedList, is(equalTo(expectedList)));

works.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

Despite the fact that this is a very old question and probably many of the beforementioned ideas solved many problems, I still want to share the solution with the community that fixed my problem.

I found that the problem was a function called "hasItem" which I was using to check whether or not a JSON-Array contains a specific item. In my case I checked for a value of type Long.

And this led to the problem.

Somehow, the Matchers have problems with values of type Long. (I do not use JUnit or Rest-Assured so much so idk. exactly why, but I guess that the returned JSON-data does just contain Integers.)

So what I did to actually fix the problem was the following. Instead of using:

long ID = ...;

...
.then().assertThat()
  .body("myArray", hasItem(ID));

you just have to cast to Integer. So the working code looked like this:

long ID = ...;

...
.then().assertThat()
  .body("myArray", hasItem((int) ID));

That's probably not the best solution, but I just wanted to mention that the exception can also be thrown because of wrong/unknown data types.

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

This happens when you run Ant via command line. The implicit user dependencies are added in the classpath at the end and take precedence over the project-added classpath. Run Ant with -nouserlib flag. The implicit dependencies would be excluded from the classpath.

Checking that a List is not empty in Hamcrest

This works:

assertThat(list,IsEmptyCollection.empty())

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

Get current date, given a timezone in PHP?

I have created some simple function you can use to convert time to any timezone :

function convertTimeToLocal($datetime,$timezone='Europe/Dublin') {
        $given = new DateTime($datetime, new DateTimeZone("UTC"));
        $given->setTimezone(new DateTimeZone($timezone));
        $output = $given->format("Y-m-d"); //can change as per your requirement
        return $output;
}

How to embed small icon in UILabel

In Swift 5, By using UILabel extensions to embed icon in leading as well as trailing side of the text as follows:-

extension UILabel {
    
    func addTrailing(image: UIImage, text:String) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: text, attributes: [:])

        string.append(attachmentString)
        self.attributedText = string
    }
    
    func addLeading(image: UIImage, text:String) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let mutableAttributedString = NSMutableAttributedString()
        mutableAttributedString.append(attachmentString)
        
        let string = NSMutableAttributedString(string: text, attributes: [:])
        mutableAttributedString.append(string)
        self.attributedText = mutableAttributedString
    }
}

To use above mentioned code in your desired label as:-

Image in right of text then:-

statusLabel.addTrailing(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")

Image in left of text then:-

statusLabel.addLeading(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")

Output:-

enter image description here

enter image description here

How to get just the parent directory name of a specific file

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"

if you need to append folder "ddd" by another path use;

String currentFolder= "/" + currentPath.getName().toString();

Retrieve the commit log for a specific line in a file?

Try using below command implemented in Git 1.8.4.

git log -u -L <upperLimit>,<lowerLimit>:<path_to_filename>

So, in your case upperLimit & lowerLimit is the touched line_number

More info - https://www.techpurohit.com/list-some-useful-git-commands

Python Socket Receive Large Amount of Data

Disclaimer: There are very rare cases in which you really need to do this. If possible use an existing application layer protocol or define your own eg. precede each message with a fixed length integer indicating the length of data that follows or terminate each message with a '\n' character. (Adam Rosenfield's answer does a really good job at explaining that)

With that said, there is a way to read all of the data available on a socket. However, it is a bad idea to rely on this kind of communication as it introduces the risk of loosing data. Use this solution with extreme caution and only after reading the explanation below.

def recvall(sock):
    BUFF_SIZE = 4096
    data = bytearray()
    while True:
        packet = sock.recv(BUFF_SIZE)
        if not packet:  # Important!!
            break
        data.extend(packet)
    return data

Now the if not packet: line is absolutely critical! Many answers here suggested using a condition like if len(packet) < BUFF_SIZE: which is broken and will most likely cause you to close your connection prematurely and loose data. It wrongly assumes that one send on one end of a TCP socket corresponds to one receive of sent number of bytes on the other end. It does not. There is a very good chance that sock.recv(BUFF_SIZE) will return a chunk smaller than BUFF_SIZE even if there's still data waiting to be received. There is a good explanation of the issue here and here.

By using the above solution you are still risking data loss if the other end of the connection is writing data slower than you are reading. You may just simply consume all data on your end and exit when more is on the way. There are ways around it that require the use of concurrent programming, but that's another topic of its own.

CSS Font Border?

There's an experimental CSS property called text-stroke, supported on some browsers behind a -webkit prefix.

_x000D_
_x000D_
h1 {_x000D_
    -webkit-text-stroke: 2px black; /* width and color */_x000D_
_x000D_
    font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
_x000D_
_x000D_

Another possible trick would be to use four shadows, one pixel each on all directions, using property text-shadow:

_x000D_
_x000D_
h1 {_x000D_
    /* 1 pixel black shadow to left, top, right and bottom */_x000D_
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;_x000D_
_x000D_
    font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
_x000D_
_x000D_

But it would get blurred for more than 1 pixel thickness.

Is it possible to get only the first character of a String?

Java strings are simply an array of char. So, char c = s[0] where s is string.

Identifying country by IP address

You could use ipdata.co to perform the lookup

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

curl https://api.ipdata.co/23.221.76.66?api-key=test

Ipdata has 10 endpoints globally each able to handle >10,000 requests per second!

Gives

{
    "ip": "23.221.76.66",
    "city": "Cambridge",
    "region": "Massachusetts",
    "region_code": "MA",
    "country_name": "United States",
    "country_code": "US",
    "continent_name": "North America",
    "continent_code": "NA",
    "latitude": 42.3626,
    "longitude": -71.0843,
    "asn": "AS20940",
    "organisation": "Akamai International B.V.",
    "postal": "02142",
    "calling_code": "1",
    "flag": "https://ipdata.co/flags/us.png",
    "emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
    "emoji_unicode": "U+1F1FA U+1F1F8",
    "is_eu": false,
    "languages": [
        {
            "name": "English",
            "native": "English"
        }
    ],
    "currency": {
        "name": "US Dollar",
        "code": "USD",
        "symbol": "$",
        "native": "$",
        "plural": "US dollars"
    },
    "time_zone": {
        "name": "America/New_York",
        "abbr": "EDT",
        "offset": "-0400",
        "is_dst": true,
        "current_time": "2018-04-19T06:32:30.690963-04:00"
    },
    "threat": {
        "is_tor": false,
        "is_proxy": false,
        "is_anonymous": false,
        "is_known_attacker": false,
        "is_known_abuser": false,
        "is_threat": false,
        "is_bogon": false
    }
}? 

laravel foreach loop in controller

Is sku just a property of the Product model? If so:

$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();

foreach ($products as $product ) {
  // Access $product->sku here...
}

Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.

Application_Start not firing?

After trying as many of the other answers as were applicable in my situation and having no luck with any of them, I went into the properties for the Web project (the server-side project for a Silverlight app using RIA Services), clicked on the "Web" tab and changed the selected Server from "Local IIS" to "IIS Express". (Note I'm using VS2013.) This solved the problem. Application_Start executes under "IIS Express" but not under "Local IIS". Interesting...

Cannot use Server.MapPath

Your project needs to reference assembly System.Web.dll. Server is an object of type HttpServerUtility. Example:

HttpContext.Current.Server.MapPath(path);

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

If you use cell.imageView?.translatesAutoresizingMaskIntoConstraints = false you can set constraints on the imageView. Here's a working example I used in a project. I avoided subclassing and didn't need to create storyboard with prototype cells but did take me quite a while to get running, so probably best to only use if there isn't a simpler or more concise way available to you.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80
}



    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: String(describing: ChangesRequiringApprovalTableViewController.self))

    let record = records[indexPath.row]

    cell.textLabel?.text = "Title text"

    if let thumb = record["thumbnail"] as? CKAsset, let image = UIImage(contentsOfFile: thumb.fileURL.path) {
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.image = image
        cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
        cell.imageView?.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
        cell.imageView?.widthAnchor.constraint(equalToConstant: 80).rowHeight).isActive = true
        cell.imageView?.heightAnchor.constraint(equalToConstant: 80).isActive = true
        if let textLabel = cell.textLabel {
            let margins = cell.contentView.layoutMarginsGuide
            textLabel.translatesAutoresizingMaskIntoConstraints = false
            cell.imageView?.trailingAnchor.constraint(equalTo: textLabel.leadingAnchor, constant: -8).isActive = true
            textLabel.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
            textLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
            let bottomConstraint = textLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor)
            bottomConstraint.priority = UILayoutPriorityDefaultHigh
            bottomConstraint.isActive = true
            if let description = cell.detailTextLabel {
                description.translatesAutoresizingMaskIntoConstraints = false
                description.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
                description.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
                cell.imageView?.trailingAnchor.constraint(equalTo: description.leadingAnchor, constant: -8).isActive = true
                textLabel.bottomAnchor.constraint(equalTo: description.topAnchor).isActive = true
            }
        }
        cell.imageView?.clipsToBounds = true
    }

    cell.detailTextLabel?.text = "Detail Text"

    return cell
}

How can I ssh directly to a particular directory?

You could add

cd /some/directory/somewhere/named/Foo

to your .bashrc file (or .profile or whatever you call it) at the other host. That way, no matter what you do or where you ssh from, whenever you log onto that server, it will cd to the proper directory for you, and all you have to do is use ssh like normal.

Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".

Installing Node.js (and npm) on Windows 10

Everything should be installed in %appdata% (C:\Users\\AppData\Roaming), not 'program files'.

Here's why...

The default MSI installer puts Node and the NPM that comes with it in 'program files' and adds this to the system path, but it sets the user path for NPM to %appdata% (c:\users[username]\appdata\roaming) since the user doesn't have sufficient priveleges to write to 'program files'.

This creates a mess as all modules go into %appdata%, and when you upgrade NPM itself - which NPM themselves recommend you do right away - you end up with two copies: the original still in 'program files' since NPM can't erase that, and the new one inn %appdata%.

Even worse, if you mistakenly perform NPM operations as admin (much easier on Windows then on *nix) then it will operate on the 'program files' copy of NPM node_modules. Potentially a real mess.

So, when you run the installer simply point it to %appdata% and avoid all this.

And note that this isn't anything wierd - it’s what would happen if you ran the installer with just user priveleges.

How to read existing text files without defining path

As your project is a console project you can pass the path to the text files that you want to read via the string[] args

static void Main(string[] args)
{
}

Within Main you can check if arguments are passed

if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}

Extract an argument

string fileToRead = args[0];

Nearly all languages support the concept of argument passing and follow similar patterns to C#.

For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx

X-Frame-Options on apache

What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80> and https <VirtualHost *:443> virtual host blocks:

ServerName your-app.com
ServerAlias www.your-app.com

Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"

The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options header so we need to first always remove the default value, in my case it was DENY, and then with the next rule we set it to the desired value, in my case SAMEORIGIN. Of course you can use the Header set X-Frame-Options ALLOW-FROM ... rule as well.

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

Calculate AUC in R?

Without any additional packages:

true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)

getROC_AUC = function(probs, true_Y){
    probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
    val = unlist(probsSort$x)
    idx = unlist(probsSort$ix)  

    roc_y = true_Y[idx];
    stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
    stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)    

    auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
    return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}

aList = getROC_AUC(probs, true_Y) 

stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)

plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")

enter image description here

Copy a variable's value into another

It's important to understand what the = operator in JavaScript does and does not do.

The = operator does not make a copy of the data.

The = operator creates a new reference to the same data.

After you run your original code:

var a = $('#some_hidden_var').val(),
    b = a;

a and b are now two different names for the same object.

Any change you make to the contents of this object will be seen identically whether you reference it through the a variable or the b variable. They are the same object.

So, when you later try to "revert" b to the original a object with this code:

b = a;

The code actually does nothing at all, because a and b are the exact same thing. The code is the same as if you'd written:

b = b;

which obviously won't do anything.

Why does your new code work?

b = { key1: a.key1, key2: a.key2 };

Here you are creating a brand new object with the {...} object literal. This new object is not the same as your old object. So you are now setting b as a reference to this new object, which does what you want.

To handle any arbitrary object, you can use an object cloning function such as the one listed in Armand's answer, or since you're using jQuery just use the $.extend() function. This function will make either a shallow copy or a deep copy of an object. (Don't confuse this with the $().clone() method which is for copying DOM elements, not objects.)

For a shallow copy:

b = $.extend( {}, a );

Or a deep copy:

b = $.extend( true, {}, a );

What's the difference between a shallow copy and a deep copy? A shallow copy is similar to your code that creates a new object with an object literal. It creates a new top-level object containing references to the same properties as the original object.

If your object contains only primitive types like numbers and strings, a deep copy and shallow copy will do exactly the same thing. But if your object contains other objects or arrays nested inside it, then a shallow copy doesn't copy those nested objects, it merely creates references to them. So you could have the same problem with nested objects that you had with your top-level object. For example, given this object:

var obj = {
    w: 123,
    x: {
        y: 456,
        z: 789
    }
};

If you do a shallow copy of that object, then the x property of your new object is the same x object from the original:

var copy = $.extend( {}, obj );
copy.w = 321;
copy.x.y = 654;

Now your objects will look like this:

// copy looks as expected
var copy = {
    w: 321,
    x: {
        y: 654,
        z: 789
    }
};

// But changing copy.x.y also changed obj.x.y!
var obj = {
    w: 123,  // changing copy.w didn't affect obj.w
    x: {
        y: 654,  // changing copy.x.y also changed obj.x.y
        z: 789
    }
};

You can avoid this with a deep copy. The deep copy recurses into every nested object and array (and Date in Armand's code) to make copies of those objects in the same way it made a copy of the top-level object. So changing copy.x.y wouldn't affect obj.x.y.

Short answer: If in doubt, you probably want a deep copy.

Android Material and appcompat Manifest merger failed

I'm also facing the same issue, for your android studio, you just change the android Gradle plugin version 3.3.2 and Gradle version is 5.1.1

Bootstrap Dropdown with Hover

This is what I use to make it dropdown on hover with some jQuery

$(document).ready(function () {
    $('.navbar-default .navbar-nav > li.dropdown').hover(function () {
        $('ul.dropdown-menu', this).stop(true, true).slideDown('fast');
        $(this).addClass('open');
    }, function () {
        $('ul.dropdown-menu', this).stop(true, true).slideUp('fast');
        $(this).removeClass('open');
    });
});

Could not resolve placeholder in string value

My solution was to add a space between the $ and the {.

For example:

@Value("${project.ftp.adresse}")

becomes

@Value("$ {project.ftp.adresse}")

Find a file in python

In Python 3.4 or newer you can use pathlib to do recursive globbing:

>>> import pathlib
>>> sorted(pathlib.Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

Reference: https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob

In Python 3.5 or newer you can also do recursive globbing like this:

>>> import glob
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']

Reference: https://docs.python.org/3/library/glob.html#glob.glob

How to execute Table valued function

You can execute it just as you select a table using SELECT clause. In addition you can provide parameters within parentheses.

Try with below syntax:

SELECT * FROM yourFunctionName(parameter1, parameter2)

Java method to sum any number of ints

You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:

int sum = 0;
for (int i = 0; i < arrayLength; i++) {
    sum += arrayVal[i];
}

System.out.println("the sum is" + sum);

I hope this helps.

Get specific objects from ArrayList when objects were added anonymously?

I would suggest overriding the equals(Object) of your Party class. It might look something like this:

public boolean equals(Object o){
    if(o == null)
        return false;
    if(o instanceof String)
        return name.equalsIgnoreCase((String)o);
    else if(o instanceof Party)
        return equals(((Party)o).name);
    return false;
}

After you do that, you could use the indexOf(Object) method to retrieve the index of the party specified by its name, as shown below:

int index = cave.parties.indexOf("SecondParty");

Would return the index of the Party with the name SecondParty.

Note: This only works because you are overriding the equals(Object) method.

How to select a single field for all documents in a MongoDB collection?

I think mattingly890 has the correct answer , here is another example along with the pattern/commmand

db.collection.find( {}, {your_key:1, _id:0})

enter image description here

Creating an Array from a Range in VBA

If we do it just like this:

Dim myArr as Variant
myArr = Range("A1:A10")

the new array will be with two dimensions. Which is not always somehow comfortable to work with:

enter image description here

To get away of the two dimensions, when getting a single column to array, we may use the built-in Excel function “Transpose”. With it, the data becomes in one dimension:

enter image description here

If we have the data in a row, a single transpose will not do the job. We need to use the Transpose function twice:

enter image description here

Note: As you see from the screenshots, when generated this way, arrays start with 1, not with 0. Just be a bit careful.

Is there a simple, elegant way to define singletons?

You can override the __new__ method like this:

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance


if __name__ == '__main__':
    s1 = Singleton()
    s2 = Singleton()
    if (id(s1) == id(s2)):
        print "Same"
    else:
        print "Different"

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

Build tree array from flat array in javascript

This is a proposal for unordered items. This function works with a single loop and with a hash table and collects all items with their id. If a root node is found, then the object is added to the result array.

_x000D_
_x000D_
function getTree(data, root) {_x000D_
    var o = {};_x000D_
    data.forEach(function (a) {_x000D_
        if (o[a.id] && o[a.id].children) {_x000D_
            a.children = o[a.id].children;_x000D_
        }_x000D_
        o[a.id] = a;_x000D_
        o[a.parentId] = o[a.parentId] || {};_x000D_
        o[a.parentId].children = o[a.parentId].children || [];_x000D_
        o[a.parentId].children.push(a);_x000D_
    });_x000D_
    return o[root].children;_x000D_
}_x000D_
_x000D_
var data = { People: [{ id: "12", parentId: "0", text: "Man", level: "1", children: null }, { id: "6", parentId: "12", text: "Boy", level: "2", children: null }, { id: "7", parentId: "12", text: "Other", level: "2", children: null }, { id: "9", parentId: "0", text: "Woman", level: "1", children: null }, { id: "11", parentId: "9", text: "Girl", level: "2", children: null }], Animals: [{ id: "5", parentId: "0", text: "Dog", level: "1", children: null }, { id: "8", parentId: "5", text: "Puppy", level: "2", children: null }, { id: "10", parentId: "13", text: "Cat", level: "1", children: null }, { id: "14", parentId: "13", text: "Kitten", level: "2", children: null }] },_x000D_
    tree = Object.keys(data).reduce(function (r, k) {_x000D_
        r[k] = getTree(data[k], '0');_x000D_
        return r;_x000D_
    }, {});_x000D_
_x000D_
console.log(tree);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_

Proper MIME type for .woff2 fonts

Apache

In Apache, you can add the woff2 mime type via your .htaccess file as stated by this link.

AddType  application/font-woff2  .woff2

IIS

In IIS, simply add the following mimeMap tag into your web.config file inside the staticContent tag.

<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

MySQL Query GROUP BY day / month / year

Complete and simple solution with similarly performing yet shorter and more flexible alternative currently active:

SELECT COUNT(*) FROM stats
-- GROUP BY YEAR(record_date), MONTH(record_date), DAYOFMONTH(record_date)
GROUP BY DATE_FORMAT(record_date, '%Y-%m-%d')

Generate Json schema from XML schema (XSD)

JSON Schema is not intended to be feature equivalent with XML Schema. There are features in one but not in the other.

In general you can create a mapping from XML to JSON and back again, but that is not the case for XML schema and JSON schema.

That said, if you have mapped a XML file to JSON, it is quite possible to craft an JSON Schema that validates that JSON in nearly the same way that the XSD validates the XML. But it isn't a direct mapping. And it is not possible to guarantee that it will validate the JSON exactly the same as the XSD validates the XML.

For this reason, and unless the two specs are made to be 100% feature compatible, migrating a validation system from XML/XSD to JSON/JSON Schema will require human intervention.

Phone number formatting an EditText in Android

There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...

EditText text = (EditText) findViewById(R.id.editTextId);
PhoneNumberUtils.formatNumber(text.getText().toString())

... to format your number in a standard format.

PhoneNumberUtils.compare(String a, String b);

... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.

p.s. setting the the EditText to phone is already a good choice; eventually it might be helpful to add digits e.g. in your layout it looks as ...

<EditText
    android:id="@+id/editTextId"
    android:inputType="phone"
    android:digits="0123456789+" 
/> 

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

PHP multidimensional array search by value

Try this

<?php
 function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && 
            recursive_array_search($needle,$value) !== false)) {
             return $current_key;
        }
    }
    return false;
 }
 ?>

Please add a @Pipe/@Directive/@Component annotation. Error

I had a component declared without the styleUrls property, like this:

@Component({
    selector: 'app-server',
    templateUrl: './server.component.html'
})

instead of:

@Component({
    selector: 'app-server',
    templateUrl: './server.component.html',
    styleUrls: ['./server.component.css']
})

Adding in the styleUrls property solved the issue.

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

How to programmatically send SMS on the iPhone?

You can present MFMessageComposeViewController, which can send SMS, but with user prompt(he taps send button). No way to do that without user permission. On iOS 11, you can make extension, that can be like filter for incoming messages , telling iOS either its spam or not. Nothing more with SMS cannot be done

How to select a range of the second row to the last row

Try this:

Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("A2:L" & Lastrow).Select

Let's pretend that the value of Lastrow is 50. When you use the following:

Range("A2:L2" & Lastrow).Select

Then it is selecting a range from A2 to L250.

Insert node at a certain position in a linked list C++

Node* InsertNth(int data, int position)
{
  struct Node *n=new struct Node;
  n->data=data;  
  if(position==0)
  {// this will also cover insertion at head (if there is no problem with the input)

      n->next=head;
      head=n;
  }

  else
  {
      struct Node *c=new struct Node;
      int count=1;
      c=head;
      while(count!=position)
      {
          c=c->next;
          count++;
      }
      n->next=c->next;
      c->next=n;

  }
    return ;
}

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

Another "Up Tick" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting: http://www.clearoffice.com/ and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) SpreadSheetGear is also excellent but pricey.

my two cents.

Echo newline in Bash prints literal \n

It works for me in CentOS:

echo -e ""hello\nworld""

Blur the edges of an image or background image with CSS

If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.

Working example: http://jsfiddle.net/d9Q5H/1/

Screenshot

HTML:

<div class="image-blurred-edge"></div>

CSS

.image-blurred-edge {
    background-image: url('http://lorempixel.com/200/200/city/9');
    width: 200px;
    height: 200px;
    /* you need to match the shadow color to your background or image border for the desired effect*/
    box-shadow: 0 0 8px 8px white inset;
}

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

If you need a recursive search, you have a variety of options. You should consider ack.

Failing that, if you have GNU find and xargs:

find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null

The use of /dev/null ensures you get file names printed; the -print0 and -0 deals with file names containing spaces (newlines, etc).

If you don't have obstreperous names (with spaces etc), you can use:

find . -name '*.*[ch]' -print | xargs grep hello /dev/null

This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find and xargs.

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

How to tell which row number is clicked in a table?

A better approach would be to delegate the event, which means catching it as it bubbles to the parent node.

delegation - overview

This solution is both more robust and efficient.

It allows the event to be handled even if more rows are dynamically added to the table later, and also results in attaching a single event handler to the parent node (table element), instead of one for each child node (tr element).

Assuming that the OP's example is a simplified one, the table's structure can be more complex, for example:

<table id="indexedTable">
    ...
    <tr>
        <td><p>1</p></td>
        <td>2</td>
        <td><p>3</p></td>
    </tr>
</table>

Therefore, a simplistic approach such as getting e.target.parentElement will not work, as clicking the internal <p> and clicking the center <td> will produce different results.

Using delegation normalizes the event handling, only assuming that there are no nested tables.

implementation

Both of the following snippets are equivalent:

$("#indexedTable").delegate("tr", "click", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

$("#indexedTable").on("click", "tr", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

They attach a listener to table element and handle any event that bubbles from the table rows. The current API is the on method and the delegate method is legacy API (and actually calls on behind the scenes).

Note that the order of parameters to both functions is different.

example

A comparison between direct handler attachment and delegation is available below or on jsFiddle:

_x000D_
_x000D_
$("#table-delegate").on("click", "tr", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#delegation-idx").text(idx);  _x000D_
  console.log('delegated', idx);_x000D_
});_x000D_
_x000D_
$("#table-direct tr").on("click", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#direct-idx").text(idx);_x000D_
  console.log('direct', idx);_x000D_
});_x000D_
_x000D_
$('[data-action=add-row]').click(function(e) {_x000D_
  var id = e.target.dataset.table;_x000D_
  $('#' + id + ' tbody')_x000D_
    .append($('<tr><td>extra</td><td>extra</td><td>extra</td></tr>')[0])_x000D_
});
_x000D_
tr:hover{_x000D_
    background:#ddd;_x000D_
}_x000D_
_x000D_
button.add-row {_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<h1>Event handling test</h1>_x000D_
<p>Add rows to both tables and see the difference in handling.</p>_x000D_
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>_x000D_
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>_x000D_
<h2>Delegation</h2>_x000D_
<p><span>row index: </span><span id="delegation-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-delegate">Add row to delegation</button>_x000D_
<table id="table-delegate" class="table">_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
_x000D_
</table>_x000D_
_x000D_
<h2>Direct attachment</h2>_x000D_
<p><span>row index: </span><span id="direct-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-direct">Add row to direct</button>_x000D_
<table id="table-direct" class="table">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    _x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the demo on jsFiddle.

P.S:

If you do have nested tables (or, in the general case, wish to delegate to elements with specific depth), you can use this suggestion from the jQuery bug report.

Set cookie and get cookie with JavaScript

Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.

Just use the setCookie and getCookie methods mentioned there.

So, the code will look something like:

<script>
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    <option value="select">--Select--</option>
    <option value="style-1.css">CSS1</option>
    <option value="style-2.css">CSS2</option>
    <option value="style-3.css">CSS3</option>
    <option value="style-4.css">CSS4</option>
</select>

Resolve Git merge conflicts in favor of their changes during a pull

VS Code (integrated Git) IDE Users:

If you want to accept all the incoming changes in the conflict file then do the following steps.

1. Go to command palette - Ctrl + Shift + P
2. Select the option - Merge Conflict: Accept All Incoming

Similarly you can do for other options like Accept All Both, Accept All Current etc.,

Java, How to implement a Shift Cipher (Caesar Cipher)

Below code handles upper and lower cases as well and leaves other character as it is.

import java.util.Scanner;

public class CaesarCipher
{
    public static void main(String[] args)
    {
    Scanner in = new Scanner(System.in);
    int length = Integer.parseInt(in.nextLine());
    String str = in.nextLine();
    int k = Integer.parseInt(in.nextLine());

    k = k % 26;

    System.out.println(encrypt(str, length, k));

    in.close();
    }

    private static String encrypt(String str, int length, int shift)
    {
    StringBuilder strBuilder = new StringBuilder();
    char c;
    for (int i = 0; i < length; i++)
    {
        c = str.charAt(i);
        // if c is letter ONLY then shift them, else directly add it
        if (Character.isLetter(c))
        {
        c = (char) (str.charAt(i) + shift);
        // System.out.println(c);

        // checking case or range check is important, just if (c > 'z'
        // || c > 'Z')
        // will not work
        if ((Character.isLowerCase(str.charAt(i)) && c > 'z')
            || (Character.isUpperCase(str.charAt(i)) && c > 'Z'))

            c = (char) (str.charAt(i) - (26 - shift));
        }
        strBuilder.append(c);
    }
    return strBuilder.toString();
    }
}

What is the difference between Integer and int in Java?

This is taken from Java: The Complete Reference, Ninth Edition

Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not inherit Object.

Despite the performance benefit offered by the primitive types, there are times when you will need an object representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java operate on objects, which means that you can’t use these (object specific) data structures to store primitive types. To handle these (and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an object.

Wrapper classes relate directly to Java’s autoboxing feature. The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.

Does "display:none" prevent an image from loading?

Quirks Mode: images and display: none

When image has display: none or is inside an element with display:none, the browser may opt not to download the image until the display is set to another value.

Only Opera downloads the image when you switch the display to block. All other browsers download it immediately.

Change input text border color without changing its height

Try this

<input type="text"/>

It will display same in all cross browser like mozilla , chrome and internet explorer.

<style>
    input{
       border:2px solid #FF0000;
    }
</style>

Dont add style inline because its not good practise, use class to add style for your input box.

How can I remount my Android/system as read-write in a bash script using adb?

Get "adbd insecure" from google play store, it helps give write access to custom roms that have it secured my the manufacturers.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

This happened to me recently when I close one Android Studio project and imported another Eclipse project. It seemed to be some bug in Android Studio where it preserves some gradle settings from previously open project and then get confused in the new project.

The solution was extremely simple: Close the project and shut down Android Studio completely, before re-opening it and then import/open the new project. Everything goes smoothly from then on.

What is object slicing?

"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.

For example,

class A {
   int foo;
};

class B : public A {
   int bar;
};

So an object of type B has two data members, foo and bar.

Then if you were to write this:

B b;

A a = b;

Then the information in b about member bar is lost in a.

How to perform keystroke inside powershell?

Also the $wshell = New-Object -ComObject wscript.shell; helped a script that was running in the background, it worked fine with just but adding $wshell. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")

How to copy data to clipboard in C#

There are two classes that lives in different assemblies and different namespaces.

  • WinForms: use following namespace declaration, make sure Main is marked with [STAThread] attribute:

    using System.Windows.Forms;
    
  • WPF: use following namespace declaration

    using System.Windows;
    
  • console: add reference to System.Windows.Forms, use following namespace declaration, make sure Main is marked with [STAThread] attribute. Step-by-step guide in another answer

    using System.Windows.Forms;
    

To copy an exact string (literal in this case):

Clipboard.SetText("Hello, clipboard");

To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:

Clipboard.SetText(txtClipboard.Text);

See here for an example. Or... Official MSDN documentation or Here for WPF.


Remarks:

How to find char in string and get all the indexes?

As the rule of thumb, NumPy arrays often outperform other solutions while working with POD, Plain Old Data. A string is an example of POD and a character too. To find all the indices of only one char in a string, NumPy ndarrays may be the fastest way:

def find1(str, ch):
  # 0.100 seconds for 1MB str 
  npbuf = np.frombuffer(str, dtype=np.uint8) # Reinterpret str as a char buffer
  return np.where(npbuf == ord(ch))          # Find indices with numpy

def find2(str, ch):
  # 0.920 seconds for 1MB str 
  return [i for i, c in enumerate(str) if c == ch] # Find indices with python

Comparing Dates in Oracle SQL

You can use trunc and to_date as follows:

select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.* 
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56 
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;

Drop all data in a pandas dataframe

Overwrite the dataframe with something like that

import pandas as pd

df = pd.DataFrame(None)

or if you want to keep columns in place

df = pd.DataFrame(columns=df.columns)

Custom seekbar (thumb size, color and background)

You can try progress bar instead of seek bar

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_marginBottom="35dp"
    />

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

RegEx for matching "A-Z, a-z, 0-9, _" and "."

^[A-Za-z0-9_.]+$

From beginning until the end of the string, match one or more of these characters.

Edit:

Note that ^ and $ match the beginning and the end of a line. When multiline is enabled, this can mean that one line matches, but not the complete string.

Use \A for the beginning of the string, and \z for the end.

See for example: http://msdn.microsoft.com/en-us/library/h5181w5w(v=vs.110).aspx

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

How to get the background color code of an element in hex?

My beautiful non-standard solution

HTML

<div style="background-color:#f5b405"></div>

jQuery

$(this).attr("style").replace("background-color:", "");

Result

#f5b405

How to Maximize a firefox browser window using Selenium WebDriver with node.js

The statement :: driver.manage().window.maximize(); Works perfectly, but the window maximizes only after loading the page on browser, it does not maximizes at the time of initializing the browser.

here : (driver) is called object of Firefox driver, it may be any thing depending on the initializing of Firefox object by you only.

Run a task every x-minutes with Windows Task Scheduler

After you select the minimum repeat option (5 minutes or 10 minutes) you can highlight the number and write whatever number you want

Convert Java Date to UTC String

java.time.Instant

Just use Instant of java.time.

    System.out.println(Instant.now());

This just printed:

2018-01-27T09:35:23.179612Z

Instant.toString always gives UTC time.

The output is usually sortable, but there are unfortunate exceptions. toString gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of Instant.now() seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).

Instant is one of the classes in java.time, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date class. java.time is built into Java 8 and later and has also been backported to Java 6 and 7.

PHP filesize MB/KB conversion

This would be a cleaner implementation:

function size2Byte($size) {
    $units = array('KB', 'MB', 'GB', 'TB');
    $currUnit = '';
    while (count($units) > 0  &&  $size > 1024) {
        $currUnit = array_shift($units);
        $size /= 1024;
    }
    return ($size | 0) . $currUnit;
}

Is it possible to preview stash contents in git?

To view all the changes in an un-popped stash:

git stash show -p stash@{0}

To view the changes of one particular file in an un-popped stash:

git diff HEAD stash@{0} -- path/to/filename.php

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

img tag displays wrong orientation

It's the EXIF data that your Samsung phone incorporates.

Where is database .bak file saved from SQL Server Management Studio?

Should be in

Program Files>Microsoft SQL Server>MSSQL 1.0>MSSQL>BACKUP>

In my case it is

C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup

If you use the gui or T-SQL you can specify where you want it T-SQL example

BACKUP DATABASE [YourDB] TO  DISK = N'SomePath\YourDB.bak' 
WITH NOFORMAT, NOINIT,  NAME = N'YourDB Full Database Backup', 
SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

With T-SQL you can also get the location of the backup, see here Getting the physical device name and backup time for a SQL Server database

SELECT          physical_device_name,
                backup_start_date,
                backup_finish_date,
                backup_size/1024.0 AS BackupSizeKB
FROM msdb.dbo.backupset b
JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id
WHERE database_name = 'YourDB'
ORDER BY backup_finish_date DESC

How to retrieve unique count of a field using Kibana + Elastic Search

Unique counts of field values are achieved by using facets. See ES documentation for the full story, but the gist is that you will create a query and then ask ES to prepare facets on the results for counting values found in fields. It's up to you to customize the fields used and even describe how you want the values returned. The most basic of facet types is just to group by terms, which would be like an IP address above. You can get pretty complex with these, even requiring a query within your facet!

{
    "query": {
        "match_all": {}
    },
    "facets": {
        "terms": {
            "field": "ip_address"
        }
    }
}

How to exclude property from Json Serialization

Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.

If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json

//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
    private readonly HashSet<string> ignoreProps;
    public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
    {
        this.ignoreProps = new HashSet<string>(propNamesToIgnore);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (this.ignoreProps.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}

Usage

JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
        { ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) };);

Note: make sure you cache the ContractResolver object if you decide to use this answer, otherwise performance may suffer.

I've published the code here in case anyone wants to add anything

https://github.com/jitbit/JsonIgnoreProps

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

In your comment on @Kenneth's answer you're saying that ReadAsStringAsync() is returning empty string.

That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.

What you can do is this:

public static string GetRequestBody()
{
    var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
    bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
    var bodyText = bodyStream.ReadToEnd();
    return bodyText;
}

Which type of folder structure should be used with Angular 2?

Maybe something like this structure:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- pages
              |-- home
              |-- home.component.ts|html|scss|spec
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- authentication
           |-- authentication.service.ts|spec.ts
       |-- footer
           |-- footer.component.ts|html|scss|spec.ts
       |-- guards
           |-- auth.guard.ts
           |-- no-auth-guard.ts
           |-- admin-guard.ts 
       |-- http
           |-- user
               |-- user.service.ts|spec.ts
           |-- api.service.ts|spec.ts
       |-- interceptors
           |-- api-prefix.interceptor.ts
           |-- error-handler.interceptor.ts
           |-- http.token.interceptor.ts
       |-- mocks
           |-- user.mock.ts
       |-- services
           |-- srv1.service.ts|spec.ts
           |-- srv2.service.ts|spec.ts
       |-- header
           |-- header.component.ts|html|scss|spec.ts
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |-- shared
          |-- components
              |-- loader
                  |-- loader.component.ts|html|scss|spec.ts
          |-- buttons
              |-- favorite-button
                  |-- favorite-button.component.ts|html|scss|spec.ts
              |-- collapse-button
                  |-- collapse-button.component.ts|html|scss|spec.ts
          |-- directives
              |-- auth.directive.ts|spec.ts
          |-- pipes
              |-- capitalize.pipe.ts
              |-- safe.pipe.ts
     |-- configs
         |-- app-settings.config.ts
         |-- dt-norwegian.config.ts
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
     |-- assets

How to parse a string to an int in C++?

I like Dan's answer, esp because of the avoidance of exceptions. For embedded systems development and other low level system development, there may not be a proper Exception framework available.

Added a check for white-space after a valid string...these three lines

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


Added a check for parsing errors too.

    if ((errno != 0) || (s == end)) {
        return INCONVERTIBLE;
    }


Here is the complete function..

#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>

enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };

STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
{
    char *end = (char *)s;
    errno = 0;

    l = strtol(s, &end, base);

    if ((errno == ERANGE) && (l == LONG_MAX)) {
        return OVERFLOW;
    }
    if ((errno == ERANGE) && (l == LONG_MIN)) {
        return UNDERFLOW;
    }
    if ((errno != 0) || (s == end)) {
        return INCONVERTIBLE;
    }    
    while (isspace((unsigned char)*end)) {
        end++;
    }

    if (*s == '\0' || *end != '\0') {
        return INCONVERTIBLE;
    }

    return SUCCESS;
}

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

No appenders could be found for logger(log4j)?

Most of the answers here suggested that log4j.properties file be placed in the right location(for maven project, it should be located in src/main/resources)

But for me, the problem is that my log4j.properties is not correctly configured. Here's a sample that works for me, you can try it out first.

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Apache Prefork vs Worker MPM

Take a look at this for more detail. It refers to how Apache handles multiple requests. Preforking, which is the default, starts a number of Apache processes (2 by default here, though I believe one can configure this through httpd.conf). Worker MPM will start a new thread per request, which I would guess, is more memory efficient. Historically, Apache has used prefork, so it's a better-tested model. Threading was only added in 2.0.

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

How is the java memory pool divided?

Java Heap Memory is part of memory allocated to JVM by Operating System.

Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.

enter image description here

You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:

Young , Tenured and Perm generation

PermGen has been replaced with Metaspace since Java 8 release.

Regarding your queries:

  1. Eden Space, Survivor Space, Tenured Space are part of heap memory
  2. Metaspace and Code Cache are part of non-heap memory.

Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.

setting JAVA_HOME & CLASSPATH in CentOS 6

Do the following steps:

  1. sudo -s
  2. yum install java-1.8.0-openjdk-devel
  3. vi .bash_profile , and add below line into .bash_profile file and save the file.

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/

Note - I am using CentOS7 as OS.

Official reasons for "Software caused connection abort: socket write error"

Closed connection in another client

In my case, the error was:

java.net.SocketException: Software caused connection abort: recv failed

It was received in eclipse while debugging a java application accessing a H2 database. The source of the error was that I had initially opened the database with SQuirreL to check manually for integrity. I did use the flag to enable multiple connections to the same DB (i.e. AUTO_SERVER=TRUE), so there was no problem connecting to the DB from java.

The error appeared when, after a while --it is a long java process-- I decided to close SQuirreL to free resources. It appears as if SQuirreL were the one "owning" the DB server instance and that it was shut down with the SQuirreL connection.

Restarting the Java application did not yield the error again.

config

  • Windows 7
  • Eclipse Kepler
  • SQuirreL 3.6
  • org.h2.Driver ver 1.4.192

JPA getSingleResult() or null

Thats works to me:

Optional<Object> opt = Optional.ofNullable(nativeQuery.getSingleResult());
return opt.isPresent() ? opt.get() : null;

What is the keyguard in Android?

Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.

you can find more info it you look in android/app or com\android\internal\policy\impl

Good Luck !

How to set a cell to NaN in a pandas dataframe

While using replace seems to solve the problem, I would like to propose an alternative. Problem with mix of numeric and some string values in the column not to have strings replaced with np.nan, but to make whole column proper. I would bet that original column most likely is of an object type

Name: y, dtype: object

What you really need is to make it a numeric column (it will have proper type and would be quite faster), with all non-numeric values replaced by NaN.

Thus, good conversion code would be

pd.to_numeric(df['y'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be

Name: y, dtype: float64

Run two async tasks in parallel and collect results in .NET 4.5

You should use Task.Delay instead of Sleep for async programming and then use Task.WhenAll to combine the task results. The tasks would run in parallel.

public class Program
    {
        static void Main(string[] args)
        {
            Go();
        }
        public static void Go()
        {
            GoAsync();
            Console.ReadLine();
        }
        public static async void GoAsync()
        {

            Console.WriteLine("Starting");

            var task1 = Sleep(5000);
            var task2 = Sleep(3000);

            int[] result = await Task.WhenAll(task1, task2);

            Console.WriteLine("Slept for a total of " + result.Sum() + " ms");

        }

        private async static Task<int> Sleep(int ms)
        {
            Console.WriteLine("Sleeping for {0} at {1}", ms, Environment.TickCount);
            await Task.Delay(ms);
            Console.WriteLine("Sleeping for {0} finished at {1}", ms, Environment.TickCount);
            return ms;
        }
    }

Pan & Zoom Image

Yet another version of the same kind of control. It has similar functionality as the others, but it adds:

  1. Touch support (drag/pinch)
  2. The image can be deleted (normally, the Image control locks the image on disk, so you cannot delete it).
  3. An inner border child, so the panned image doesn't overlap the border. In case of borders with rounded rectangles, look for ClippedBorder classes.

Usage is simple:

<Controls:ImageViewControl ImagePath="{Binding ...}" />

And the code:

public class ImageViewControl : Border
{
    private Point origin;
    private Point start;
    private Image image;

    public ImageViewControl()
    {
        ClipToBounds = true;
        Loaded += OnLoaded;
    }

    #region ImagePath

    /// <summary>
    ///     ImagePath Dependency Property
    /// </summary>
    public static readonly DependencyProperty ImagePathProperty = DependencyProperty.Register("ImagePath", typeof (string), typeof (ImageViewControl), new FrameworkPropertyMetadata(string.Empty, OnImagePathChanged));

    /// <summary>
    ///     Gets or sets the ImagePath property. This dependency property 
    ///     indicates the path to the image file.
    /// </summary>
    public string ImagePath
    {
        get { return (string) GetValue(ImagePathProperty); }
        set { SetValue(ImagePathProperty, value); }
    }

    /// <summary>
    ///     Handles changes to the ImagePath property.
    /// </summary>
    private static void OnImagePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = (ImageViewControl) d;
        var oldImagePath = (string) e.OldValue;
        var newImagePath = target.ImagePath;
        target.ReloadImage(newImagePath);
        target.OnImagePathChanged(oldImagePath, newImagePath);
    }

    /// <summary>
    ///     Provides derived classes an opportunity to handle changes to the ImagePath property.
    /// </summary>
    protected virtual void OnImagePathChanged(string oldImagePath, string newImagePath)
    {
    }

    #endregion

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        image = new Image {
                              //IsManipulationEnabled = true,
                              RenderTransformOrigin = new Point(0.5, 0.5),
                              RenderTransform = new TransformGroup {
                                                                       Children = new TransformCollection {
                                                                                                              new ScaleTransform(),
                                                                                                              new TranslateTransform()
                                                                                                          }
                                                                   }
                          };
        // NOTE I use a border as the first child, to which I add the image. I do this so the panned image doesn't partly obscure the control's border.
        // In case you are going to use rounder corner's on this control, you may to update your clipping, as in this example:
        // http://wpfspark.wordpress.com/2011/06/08/clipborder-a-wpf-border-that-clips/
        var border = new Border {
                                    IsManipulationEnabled = true,
                                    ClipToBounds = true,
                                    Child = image
                                };
        Child = border;

        image.MouseWheel += (s, e) =>
                                {
                                    var zoom = e.Delta > 0
                                                   ? .2
                                                   : -.2;
                                    var position = e.GetPosition(image);
                                    image.RenderTransformOrigin = new Point(position.X / image.ActualWidth, position.Y / image.ActualHeight);
                                    var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
                                    st.ScaleX += zoom;
                                    st.ScaleY += zoom;
                                    e.Handled = true;
                                };

        image.MouseLeftButtonDown += (s, e) =>
                                         {
                                             if (e.ClickCount == 2)
                                                 ResetPanZoom();
                                             else
                                             {
                                                 image.CaptureMouse();
                                                 var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
                                                 start = e.GetPosition(this);
                                                 origin = new Point(tt.X, tt.Y);
                                             }
                                             e.Handled = true;
                                         };

        image.MouseMove += (s, e) =>
                               {
                                   if (!image.IsMouseCaptured) return;
                                   var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
                                   var v = start - e.GetPosition(this);
                                   tt.X = origin.X - v.X;
                                   tt.Y = origin.Y - v.Y;
                                   e.Handled = true;
                               };

        image.MouseLeftButtonUp += (s, e) => image.ReleaseMouseCapture();

        //NOTE I apply the manipulation to the border, and not to the image itself (which caused stability issues when translating)!
        border.ManipulationDelta += (o, e) =>
                                       {
                                           var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
                                           var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);

                                           st.ScaleX *= e.DeltaManipulation.Scale.X;
                                           st.ScaleY *= e.DeltaManipulation.Scale.X;
                                           tt.X += e.DeltaManipulation.Translation.X;
                                           tt.Y += e.DeltaManipulation.Translation.Y;

                                           e.Handled = true;
                                       };
    }

    private void ResetPanZoom()
    {
        var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
        st.ScaleX = st.ScaleY = 1;
        tt.X = tt.Y = 0;
        image.RenderTransformOrigin = new Point(0.5, 0.5);
    }

    /// <summary>
    /// Load the image (and do not keep a hold on it, so we can delete the image without problems)
    /// </summary>
    /// <see cref="http://blogs.vertigo.com/personal/ralph/Blog/Lists/Posts/Post.aspx?ID=18"/>
    /// <param name="path"></param>
    private void ReloadImage(string path)
    {
        try
        {
            ResetPanZoom();
            // load the image, specify CacheOption so the file is not locked
            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
            bitmapImage.EndInit();
            image.Source = bitmapImage;
        }
        catch (SystemException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

SCRIPT5: Access is denied in IE9 on xmlhttprequest

I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

How to delete cookies on an ASP.NET website

No, Cookies can be cleaned only by setting the Expiry date for each of them.

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}

At the moment of Session.Clear():

  • All the key-value pairs from Session collection are removed. Session_End event is not happen.

If you use this method during logout, you should also use the Session.Abandon method to Session_End event:

  • Cookie with Session ID (if your application uses cookies for session id store, which is by default) is deleted

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

Why is a div with "display: table-cell;" not affected by margin?

Cause

From the MDN documentation:

[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

In other words, the margin property is not applicable to display:table-cell elements.

Solution

Consider using the border-spacing property instead.

Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

For example:

HTML

<div class="table">
    <div class="row">
        <div class="cell">123</div>
        <div class="cell">456</div>
        <div class="cell">879</div>
    </div>
</div>

CSS

.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}

See jsFiddle demo


Different margin horizontally and vertically

As mentioned by Diego Quirós, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

For example

.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

How can I know if a branch has been already merged into master?

On the topic of cleaning up remote branches

git branch -r | xargs -t -n 1 git branch -r --contains

This lists each remote branch followed by which remote branches their latest SHAs are within.

This is useful to discern which remote branches have been merged but not deleted, and which haven't been merged and thus are decaying.

If you're using 'tig' (its like gitk but terminal based) then you can

tig origin/feature/someones-decaying-feature

to see a branch's commit history without having to git checkout

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

Correct way to remove plugin from Eclipse

For some 'Eclipse Marketplace' plugins Uninstall may not work. (Ex: SonarLint v5)

So Try,

Help -> About Eclipse -> Installation details
  • search the plugin name in 'Installed Software'

  • Select plugin name and Uninstall it

Additional Detail

To fix plugin errors, after the uninstall revert back older version of plugin,

Help -> install new software..
  • Get plugin url from Google search and Add it (Example: https://eclipse-uc.sonarlint.org)

  • Select and install older versions of the Plugin. This will fix most of the plugin problems.

When do you use POST and when do you use GET?

Well one major thing is anything you submit over GET is going to be exposed via the URL. Secondly as Ceejayoz says, there is a limit on characters for a URL.

How do I 'foreach' through a two-dimensional array?

I'm not a big fan of this method because of the memory usage involved, but if you use the arrays it produces, it isn't such a waste.

public static void ForEachRow<T>(this T[,] list, Action<int, T[]> action)
{
    var len = list.GetLength(0);
    var sub = list.GetLength(1);

    T[] e;
    int i, j;

    for (i = 0; i < len; i++)
    {
        e = new T[sub];

        for (j = 0; j < sub; j++)
        {
            e[j] = list[i, j];
        }

        action(i, e);
    }
}

Implementation:

var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};

list.ForEachRow((i, row) =>
{
    for (var j = 0; j < row.Length; j++)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, row[j]);
    }
});

The other solution I found is less memory intensive, but will use more CPU, especially when the dimensions of the arrays' entries are larger.

public static void ForEachRow<T>(this T[,] list, Action<int, IEnumerable<T>> action)
{
    var len = list.GetLength(0);
    var sub = list.GetLength(1);

    int i, j;
    IEnumerable<T> e;

    for (i = 0; i < len; i++)
    {
        e = Enumerable.Empty<T>();

        for (j = 0; j < sub; j++)
        {
            e = e.Concat(AsEnumerable(list[i, j]));
        }

        action(i, e);
    }
}

private static IEnumerable<T> AsEnumerable<T>(T add)
{
    yield return add;
}

Implementation:

var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};

list.ForEachRow((i, row) =>
{
    var j = 0;

    forrach (var o in row)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, o);

        ++j;
    }
});

As a whole, I find the first option to be more intuitive, especially if you want to access the produced array by its indexer.

At the end of the day, this is all just eye candy, neither methods should really be used in favour of directly accessing the source array;

for (var i = 0; i < list.GetLength(0); i++)
{
    foreach (var j = 0; j < list.GetLength(1); j++)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, list[i, j]);
    }
}

CSS center content inside div

Try using flexbox. As an example, the following code shows the CSS for the container div inside which the contents needs to be centered aligned:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;

}

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

Setting size for icon in CSS

Funnily enough, adjusting the padding seems to do it.

_x000D_
_x000D_
.arrow {
  border: solid rgb(2, 0, 0);
  border-width: 0 3px 3px 0;
  display: inline-block;
}

.first{
  padding: 2vh;
}

.second{
  padding: 4vh;
}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
 }
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
_x000D_
_x000D_

Random integer in VB.NET

Dim rnd As Random = New Random
rnd.Next(n)

Displaying a vector of strings in C++

Because userString is empty. You only declare it

vector<string> userString;     

but never add anything, so the for loop won't even run.

Changing button color programmatically

Here is an example using HTML:

<input type="button" value="click me" onclick="this.style.color='#000000';
this.style.backgroundColor = '#ffffff'" />

And here is an example using JavaScript:

document.getElementById("button").bgcolor="#Insert Color Here";

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

How and where to use ::ng-deep?

I would emphasize the importance of limiting the ::ng-deep to only children of a component by requiring the parent to be an encapsulated css class.

For this to work it's important to use the ::ng-deep after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.

Using the :host keyword before ::ng-deep will handle this automatically:

:host ::ng-deep .mat-checkbox-layout

Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep keyword:

.my-component ::ng-deep .mat-checkbox-layout {
    background-color: aqua;
}

Component template:

<h1 class="my-component">
    <mat-checkbox ....></mat-checkbox>
</h1>

Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:

.my-component[_ngcontent-c1] .mat-checkbox-layout {
    background-color: aqua;
}

What Java FTP client library should I use?

Check out Apache commons-net, which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!

How to unstage large number of files without deleting the content

If HEAD isn't set (i.e., you have no commits yet, but you don't want to just blow away .git because you've already set up other repo config you want to keep), you can also do

git rm -rf --cached .

to unstage everything. This is effectively the same as sehe's solution, but avoids mucking with Git internals.

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

How to use absolute path in twig functions

I've used the following advice from the docs https://symfony.com/doc/current/console/request_context.html to get absolute urls in emails:

# config/services.yaml
parameters:
    router.request_context.host: 'example.org'
    router.request_context.scheme: 'https'

How to implement a ViewPager with different Fragments / Layouts

Basic ViewPager Example

This answer is a simplification of the documentation, this tutorial, and the accepted answer. It's purpose is to get a working ViewPager up and running as quickly as possible. Further edits can be made after that.

enter image description here

XML

Add the xml layouts for the main activity and for each page (fragment). In our case we are only using one fragment layout, but if you have different layouts on the different pages then just make one for each of them.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.verticalviewpager.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textview"
        android:textSize="30sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

Code

This is the code for the main activity. It includes the PagerAdapter and FragmentOne as inner classes. If these get too large or you are reusing them in other places, then you can move them to their own separate classes.

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends AppCompatActivity {

    static final int NUMBER_OF_PAGES = 2;

    MyAdapter mAdapter;
    ViewPager mPager;

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

        mAdapter = new MyAdapter(getSupportFragmentManager());
        mPager = findViewById(R.id.viewpager);
        mPager.setAdapter(mAdapter);
    }

    public static class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return NUMBER_OF_PAGES;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return FragmentOne.newInstance(0, Color.WHITE);
                case 1:
                    // return a different Fragment class here
                    // if you want want a completely different layout
                    return FragmentOne.newInstance(1, Color.CYAN);
                default:
                    return null;
            }
        }
    }

    public static class FragmentOne extends Fragment {

        private static final String MY_NUM_KEY = "num";
        private static final String MY_COLOR_KEY = "color";

        private int mNum;
        private int mColor;

        // You can modify the parameters to pass in whatever you want
        static FragmentOne newInstance(int num, int color) {
            FragmentOne f = new FragmentOne();
            Bundle args = new Bundle();
            args.putInt(MY_NUM_KEY, num);
            args.putInt(MY_COLOR_KEY, color);
            f.setArguments(args);
            return f;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt(MY_NUM_KEY) : 0;
            mColor = getArguments() != null ? getArguments().getInt(MY_COLOR_KEY) : Color.BLACK;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_one, container, false);
            v.setBackgroundColor(mColor);
            TextView textView = v.findViewById(R.id.textview);
            textView.setText("Page " + mNum);
            return v;
        }
    }
}

Finished

If you copied and pasted the three files above to your project, you should be able to run the app and see the result in the animation above.

Going on

There are quite a few things you can do with ViewPagers. See the following links to get started:

How to properly stop the Thread in Java?

I didn't get the interrupt to work in Android, so I used this method, works perfectly:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    threadCheckChat = new Thread(new CheckUpdates());
    threadCheckChat.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }

How to run console application from Windows Service?

I've done this before successfully - I have some code at home. When I get home tonight, I'll update this answer with the working code of a service launching a console app.

I thought I'd try this from scratch. Here's some code I wrote that launches a console app. I installed it as a service and ran it and it worked properly: cmd.exe launches (as seen in Task Manager) and lives for 10 seconds until I send it the exit command. I hope this helps your situation as it does work properly as expected here.

    using (System.Diagnostics.Process process = new System.Diagnostics.Process())
    {
        process.StartInfo = new System.Diagnostics.ProcessStartInfo(@"c:\windows\system32\cmd.exe");
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.ErrorDialog = false;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        process.Start();
        //// do some other things while you wait...
        System.Threading.Thread.Sleep(10000); // simulate doing other things...
        process.StandardInput.WriteLine("exit"); // tell console to exit
        if (!process.HasExited)
        {
            process.WaitForExit(120000); // give 2 minutes for process to finish
            if (!process.HasExited)
            {
                process.Kill(); // took too long, kill it off
            }
        }
    }

How to add two strings as if they were numbers?

Here, you have two options to do this :-

1.You can use the unary plus to convert string number into integer.

2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc

.

Now I am going to show you here with the help of examples(Find the sum of two numbers).

Using unary plus operator

<!DOCTYPE html>
<html>
<body>

<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;    
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>

Using parsing approach-

<!DOCTYPE html>
<html>
<body>

<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");   
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>

.NET Core vs Mono

In a nutshell:

Mono = Compiler for C#

Mono Develop = Compiler+IDE

.Net Core = ASP Compiler

Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

Steps to upload an iPhone application to the AppStore

Xcode 9

If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:

However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:

Step 1: Create a new app in iTunes Connect

Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.

enter image description here

Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.

enter image description here

Click Create and then go on to Step 2.

Step 2: Archive your app in Xcode

Choose the Generic iOS Device from the active scheme menu.

enter image description here

Then go to Product > Archive.

enter image description here

You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.

I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.

Step 3: Finish filling out the iTunes Connect info

Back in iTunes Connect you will need to complete all the required information and resources.

enter image description here

Just go through all the menu options and make sure that you have everything entered that needs to be.

Step 4: Submit

In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.

enable cors in .htaccess

Will be work 100%, Apply in .htaccess:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

How to use jQuery to call an ASP.NET web service?

Here is an example to call your webservice using jQuery.get:

$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.

How to put a symbol above another in LaTeX?

If you're using # as an operator, consider defining a new operator for it:

\newcommand{\pound}{\operatornamewithlimits{\#}}

You can then write things like \pound_{n = 1}^N and get:

alt text

How to make the window full screen with Javascript (stretching all over the screen)

Try this script

<script language="JavaScript">
function fullScreen(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto' );
}
</script>

For calling from script use this code,

window.fullScreen('fullscreen.jsp');

or with hyperlink use this

<a href="javascript:void(0);" onclick="fullScreen('fullscreen.jsp');"> 
Open in Full Screen Window</a>

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to exclude a directory in find . command

Better use the exec action than the for loop:

find . -path "./dirtoexclude" -prune \
    -o -exec java -jar config/yuicompressor-2.4.2.jar --type js '{}' -o '{}' \;

The exec ... '{}' ... '{}' \; will be executed once for every matching file, replacing the braces '{}' with the current file name.

Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation*.


Notes

* From the EXAMPLES section of the find (GNU findutils) 4.4.2 man page

The project description file (.project) for my project is missing

I created a new workspace and imported old projects. I just didn’t open this workspace for a long time, I don’t know why this problem happened

Which maven dependencies to include for spring 3.0?

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

MySQL DAYOFWEEK() - my week begins with monday

How about subtracting one and changing Sunday

IF(DAYOFWEEK() = 1, 7, DAYOFWEEK() - 1)

Of course you would have to do this for every query.

"Fatal error: Unable to find local grunt." when running "grunt" command

if you are a exists project, maybe should execute npm install.

guntjs getting started step 2.

Outlets cannot be connected to repeating content iOS

For collectionView :

solution:

From viewcontroller, kindly remove the IBoutlet of colllectionviewcell

. the issue mentions the invalid of your IBOutlet. so remove all subclass which has multi-outlet(invalids) and reconnect it.

The answer is already mentioned in another question for collectionviewcell

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

mysql - move rows from one table to another

To move and delete specific records by selecting using WHERE query,

BEGIN TRANSACTION;
Insert Into A SELECT * FROM B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count=""  And contact_person= "" limit 0,2000;
delete from B where Id In (select Id from B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000);
commit;

Trim whitespace from a String

Here is how you can do it:

std::string & trim(std::string & str)
{
   return ltrim(rtrim(str));
}

And the supportive functions are implemeted as:

std::string & ltrim(std::string & str)
{
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   
}

std::string & rtrim(std::string & str)
{
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   
}

And once you've all these in place, you can write this as well:

std::string trim_copy(std::string const & str)
{
   auto s = str;
   return ltrim(rtrim(s));
}

Try this

Priority queue in .Net

Use a Java to C# translator on the Java implementation (java.util.PriorityQueue) in the Java Collections framework, or more intelligently use the algorithm and core code and plug it into a C# class of your own making that adheres to the C# Collections framework API for Queues, or at least Collections.

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

ip address validation in python using regex

The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:

[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Example:

your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Output:

>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>

Display Two <div>s Side-by-Side

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}??

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

On my Mac OS, Text Wrangler identified a CSV file created with Excel as having "Western" encoding.

After some googling I have made this small script (I am not sure about Windows availability, maybe with Cygwin?):

$ cat /usr/local/bin/utf8.sh

#!/bin/bash

INPUTFILE="$1"

iconv -f macroman -c -t UTF-8 $INPUTFILE |tr '\r' '\n' >/tmp/file.$$.csv

mv $INPUTFILE ms_trash
mv /tmp/file.$$.csv $INPUTFILE

Killing a process created with Python's subprocess.Popen()

In your code it should be

proc1.kill()

Both kill or terminate are methods of the Popen object which sends the signal signal.SIGKILL to the process.

Terminating a script in PowerShell

Terminates this process and gives the underlying operating system the specified exit code.

https://msdn.microsoft.com/en-us/library/system.environment.exit%28v=vs.110%29.aspx

[Environment]::Exit(1)

This will allow you to exit with a specific exit code, that can be picked up from the caller.

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

Android Color Picker

Here's another library:

https://github.com/eltos/SimpleDialogFragments

Features color wheel and pallet picker dialogs

What is "pom" packaging in maven?

POM(Project Object Model) is nothing but the automation script for building the project,we can write the automation script in XML, the building script files are named diffrenetly in different Automation tools

like we call build.xml in ANT,pom.xml in MAVEN

MAVEN can packages jars,wars, ears and POM which new thing to all of us

if you want check WHAT IS POM.XML

Should black box or white box testing be the emphasis for testers?

In my experience most developers naturally migrate towards white box testing. Since we need to ensure that the underlying algorithm is "correct", we tend to focus more on the internals. But, as has been pointed out, both white and black box testing is important.

Therefore, I prefer to have testers focus more on the Black Box tests, to cover for the fact that most developers don't really do it, and frequently aren't very good at it.

That isn't to say that testers should be kept in the dark about how the system works, just that I prefer them to focus more on the problem domain and how actual users interact with the system, not whether the function SomeMethod(int x) will correctly throw an exception if x is equal to 5.

Creating an array from a text file in Bash

Use the mapfile command:

mapfile -t myArray < file.txt

The error is using for -- the idiomatic way to loop over lines of a file is:

while IFS= read -r line; do echo ">>$line<<"; done < file.txt

See BashFAQ/005 for more details.

How do I add a newline to command output in PowerShell?

The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.

Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append

Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Use a loop to plot n charts Python

We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.

import pandas as pd
import seaborn as sns
import numpy as np

numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.

for i in data[numeric_features].columns:
    plt.figure(figsize=(12,5))
    plt.title(i)
    sns.boxplot(data=data[i])

In Javascript, how to conditionally add a member to an object?

This is probably the shortest solution with ES6

console.log({
   ...true && {foo: 'bar'}
})
// Output: {foo:'bar'}
console.log({
   ...false && {foo: 'bar'}
})
// Output: {}

find without recursion

I believe you are looking for -maxdepth 1.

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

How to center form in bootstrap 3

I tried this and it worked

_x000D_
_x000D_
<div class="container">_x000D_
 <div class="row justify-content-center">_x000D_
  <div class="form-group col-md-4 col-md-offset-5 align-center ">_x000D_
       <input type="text" name="username" placeholder="Username" >_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I use multiple versions of jQuery on the same page?

After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script>var $j = jQuery.noConflict(true);</script>
    <script>
      $(document).ready(function(){
       console.log($().jquery); // This prints v1.4.2
       console.log($j().jquery); // This prints v1.9.1
      });
   </script>

So then adding the "j" after the "$" was all I needed to do.

$j(function () {
        $j('.button-pro').on('click', function () {
            var el = $('#cnt' + this.id.replace('btn', ''));
            $j('#contentnew > div').not(el).animate({
                height: "toggle",
                opacity: "toggle"
            }, 100).hide();
            el.toggle();
        });
    });

Sort columns of a dataframe by column name

So to have a specific column come first, then the rest alphabetically, I'd propose this solution:

test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]

onclick open window and specific size

<a style="cursor:pointer"
  onclick=" window.open('http://YOUR.URL.TARGET','',' scrollbars=yes,menubar=no,width=500, resizable=yes,toolbar=no,location=no,status=no')">Your text</a>

How do I invert BooleanToVisibilityConverter?

I just did a post on this. I used a similar idea as Michael Hohlios did. Only, I used Properties instead of using the "object parameter".

Binding Visibility to a bool value in WPF

Using Properties makes it more readable, in my opinion.

<local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True" Reverse="True" />

How to increase font size in NeatBeans IDE?

To increase the font size of netbeans 7.3.1 and 7.3 , you go from menu Tools>>Options>>"Fonts & Colors" (is an inner menu in the dialog window of Options)

At the "Syntax" tab ,every entry in the "Category:" list-box ,you will notice that the font has the value "Inherited". If you find in the "Category" list-box the entry with the name "Default" and change the font value of that, you will affect the font size of your editor, because everything is inherited from "Default" entry .

Another method is to increase temporary the font of the editor by a combination of keys. To find what are the keys go to the "Options" dialog window by Tools>> Options and then choose the "Keymap" menu entry and then in the "Search" textbox type "zoom text" and it will show you what combinations of keys for zooming in /out.

for example mine is the combination of "alt" key + mouse wheel up/down

In Perl, how do I create a hash whose keys come from a given array?

@hash{@keys} = undef;

The syntax here where you are referring to the hash with an @ is a hash slice. We're basically saying $hash{$keys[0]} AND $hash{$keys[1]} AND $hash{$keys[2]} ... is a list on the left hand side of the =, an lvalue, and we're assigning to that list, which actually goes into the hash and sets the values for all the named keys. In this case, I only specified one value, so that value goes into $hash{$keys[0]}, and the other hash entries all auto-vivify (come to life) with undefined values. [My original suggestion here was set the expression = 1, which would've set that one key to 1 and the others to undef. I changed it for consistency, but as we'll see below, the exact values do not matter.]

When you realize that the lvalue, the expression on the left hand side of the =, is a list built out of the hash, then it'll start to make some sense why we're using that @. [Except I think this will change in Perl 6.]

The idea here is that you are using the hash as a set. What matters is not the value I am assigning; it's just the existence of the keys. So what you want to do is not something like:

if ($hash{$key} == 1) # then key is in the hash

instead:

if (exists $hash{$key}) # then key is in the set

It's actually more efficient to just run an exists check than to bother with the value in the hash, although to me the important thing here is just the concept that you are representing a set just with the keys of the hash. Also, somebody pointed out that by using undef as the value here, we will consume less storage space than we would assigning a value. (And also generate less confusion, as the value does not matter, and my solution would assign a value only to the first element in the hash and leave the others undef, and some other solutions are turning cartwheels to build an array of values to go into the hash; completely wasted effort).

How to revert the last migration?

If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake migrations.

./manage.py migrate <name> --ignore-ghost-migrations --merge --fake

For django version < 1.7 this will create entry in south_migrationhistory table, you need to delete that entry.

Now you'll be able to revert back the migration easily.

PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.

Array slices in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace data_seniens
{
    class Program
    {
        static void Main(string[] args)
        {
            //new list
            float [] x=new float[]{11.25f,18.0f,20.0f,10.75f,9.50f, 11.25f, 18.0f, 20.0f, 10.75f, 9.50f };

            //variable
            float eat_sleep_area=x[1]+x[3];
            //print
            foreach (var VARIABLE in x)
            {
                if (VARIABLE < x[7])
                {
                    Console.WriteLine(VARIABLE);
                }
            }



            //keep app run
        Console.ReadLine();
        }
    }
}

Upload folder with subfolders using S3 and the AWS console

You can upload files by dragging and dropping or by pointing and clicking. To upload folders, you must drag and drop them. Drag and drop functionality is supported only for the Chrome and Firefox browsers

How to use a dot "." to access members of dictionary?

Fabric has a really nice, minimal implementation. Extending that to allow for nested access, we can use a defaultdict, and the result looks something like this:

from collections import defaultdict

class AttributeDict(defaultdict):
    def __init__(self):
        super(AttributeDict, self).__init__(AttributeDict)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(key)

    def __setattr__(self, key, value):
        self[key] = value

Make use of it as follows:

keys = AttributeDict()
keys.abc.xyz.x = 123
keys.abc.xyz.a.b.c = 234

That elaborates a bit on Kugel's answer of "Derive from dict and and implement __getattr__ and __setattr__". Now you know how!

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

Validating email addresses using jQuery and regex

Javascript:

var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);


The regex is not allowed for:

[email protected]
[email protected]..


Allowed for:

[email protected]
[email protected]

Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/

Save the console.log in Chrome to a file

On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.

export CHROME_LOG_FILE=chrome.log

sql try/catch rollback/commit - preventing erroneous commit after rollback

I used below ms sql script pattern several times successfully which uses Try-Catch,Commit Transaction- Rollback Transaction,Error Tracking.

Your TRY block will be as follows

 BEGIN TRY
 BEGIN TRANSACTION T
 ----
 //your script block
 ----
 COMMIT TRANSACTION T 
 END TRY

Your CATCH block will be as follows

BEGIN CATCH
DECLARE @ErrMsg NVarChar(4000), 
        @ErrNum Int, 
        @ErrSeverity Int, 
        @ErrState Int, 
        @ErrLine Int, 
        @ErrProc NVarChar(200)
 SELECT @ErrNum = Error_Number(), 
       @ErrSeverity = Error_Severity(), 
       @ErrState = Error_State(), 
       @ErrLine = Error_Line(), 
       @ErrProc = IsNull(Error_Procedure(), '-')
 SET @ErrMsg = N'ErrLine: ' + rtrim(@ErrLine) + ', proc: ' + RTRIM(@ErrProc) + ', 
       Message: '+ Error_Message()

Your ROLLBACK script will be part of CATCH block as follows

IF (@@TRANCOUNT) > 0 
BEGIN
PRINT 'ROLLBACK: ' + SUBSTRING(@ErrMsg,1,4000)
ROLLBACK TRANSACTION T
END
ELSE
BEGIN
PRINT SUBSTRING(@ErrMsg,1,4000);   
END

END CATCH

Above different script blocks you need to use as one block. If any error happens in the TRY block it will go the the CATCH block. There it is setting various details about the error number,error severity,error line ..etc. At last all these details will get append to @ErrMsg parameter. Then it will check for the count of transaction (@@TRANCOUNT >0) , ie if anything is there in the transaction for rollback. If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message.

We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction(final change in the database) only after all the code in the TRY block has run successfully.

Reset textbox value in javascript

First, select the element. You can usually use the ID like this:

$("#searchField"); // select element by using "#someid"

Then, to set the value, use .val("something") as in:

$("#searchField").val("something"); // set the value

Note that you should only run this code when the element is available. The usual way to do this is:

$(document).ready(function() { // execute when everything is loaded
    $("#searchField").val("something"); // set the value
});

How do you append an int to a string in C++?

If using Windows/MFC, and need the string for more than immediate output try:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);

How to update std::map after using the find method?

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

How do I use FileSystemObject in VBA?

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...
Loop

fsoStream.Close
Set FSO = Nothing

Hope it help!

Best regards

Fabio

Eclipse/Maven error: "No compiler is provided in this environment"

Maven requires JDK to compile. In Eclipse you need to CHANGE/ REPLACE your JRE to the JDK path that your JAVA_HOME points to. Navigate to Window > Preferences > Java > Installed JREs.

Make sure that the maven-compiler-plugin in you pom.xml has the source and target of the java version in your JAVA_HOME

http://learn-automation.com/maven-no-compiler-is-provided-in-this-environment-selenium/

Can I pass a JavaScript variable to another browser window?

One can pass a message from the 'parent' window to the 'child' window:

in the 'parent window' open the child

    var win = window.open(<window.location.href>, '_blank');    
       setTimeout(function(){
                    win.postMessage(SRFBfromEBNF,"*")
                  },1000);
    win.focus();

the to be replaced according to the context

In the 'child'

    window.addEventListener('message', function(event) {
        if(event.srcElement.location.href==window.location.href){
        /* do what you want with event.data */
        }
    }); 

The if test must be changed according to the context

What are the benefits of learning Vim?

It's definitely worth learning either vim or emacs. It's also worth learning to touch-type. In both cases the reasons are the same: your thinking is no longer interrupted by the mechanical process of getting your code onto the screen.

As to how to start, just dive in and start using vim for everything.

P.S. The emacs-vs-vi debate is endless. I've been using emacs for 26 years. If I started again today I'd learn vim because (a) it's gotten better and (b) there are many fewer modifier keys (Ctl-Alt-V, anyone) and vim users seem to get much less typing injury.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

How to remove leading and trailing spaces from a string

Or you can split your string to string array, splitting by space and then add every item of string array to empty string.
May be this is not the best and fastest method, but you can try, if other answer aren't what you whant.

How can I run an EXE program from a Windows Service using C#?

I think You are copying the .exe to different location. This might be the problem I guess. When you copy the exe, you are not copying its dependencies.

So, what you can do is, put all dependent dlls in GAC so that any .net exe can access it

Else, do not copy the exe to new location. Just create a environment variable and call the exe in your c#. Since the path is defined in environment variables, the exe is can be accessed by your c# program.

Update:

previously I had some kind of same issue in my c#.net 3.5 project in which I was trying to run a .exe file from c#.net code and that exe was nothing but the another project exe(where i added few supporting dlls for my functionality) and those dlls methods I was using in my exe application. At last I resolved this by creating that application as a separate project to the same solution and i added that project output to my deployment project. According to this scenario I answered, If its not what he wants then I am extremely sorry.

What is a good regular expression to match a URL?

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

Will match the following cases

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co
  • http://t.co
  • http://www.t.co
  • https://www.t.co
  • www.aa.com
  • http://aa.com
  • http://www.aa.com
  • https://www.aa.com

Will NOT match the following

  • www.foufos
  • www.foufos-.gr
  • www.-foufos.gr
  • foufos.gr
  • http://www.foufos
  • http://foufos
  • www.mp3#.com

_x000D_
_x000D_
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
  'http://www.foufos.gr',_x000D_
  'https://www.foufos.gr',_x000D_
  'http://foufos.gr',_x000D_
  'http://www.foufos.gr/kino',_x000D_
  'http://werer.gr',_x000D_
  'www.foufos.gr',_x000D_
  'www.mp3.com',_x000D_
  'www.t.co',_x000D_
  'http://t.co',_x000D_
  'http://www.t.co',_x000D_
  'https://www.t.co',_x000D_
  'www.aa.com',_x000D_
  'http://aa.com',_x000D_
  'http://www.aa.com',_x000D_
  'https://www.aa.com',_x000D_
  'www.foufos',_x000D_
  'www.foufos-.gr',_x000D_
  'www.-foufos.gr',_x000D_
  'foufos.gr',_x000D_
  'http://www.foufos',_x000D_
  'http://foufos',_x000D_
  'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
  if (entry.match(regex)) {_x000D_
    $("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
  } else {_x000D_
    $("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Check it in rubular - NEW version

Check it in rubular - old version

How to avoid precompiled headers

Right click project solution

Properties -> Configuration Properties -> C/C++ -> Precompiled Headers

  1. Click on "Precompiled Headers" change to "Not Using Precompiled Headers".

  2. Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.

  3. Then you can feel free to delete the pch./stdafx. files in your project

Android ADB commands to get the device properties

For Power-Shell

./adb shell getprop | Select-String -Pattern '(model)|(version.sdk)|(manufacturer)|(platform)|(serialno)|(product.name)|(brand)'

For linux(burrowing asnwer from @0x8BADF00D)

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

For single string find in power shell

./adb shell getprop | Select-String -Pattern 'model'

or

./adb shell getprop | Select-String -Pattern '(model)'

For multiple

./adb shell getprop | Select-String -Pattern '(a|b|c|d)'

C# find highest array value and index

If the index is not sorted, you have to iterate through the array at least once to find the highest value. I'd use a simple for loop:

int? maxVal = null; //nullable so this works even if you have all super-low negatives
int index = -1;
for (int i = 0; i < anArray.Length; i++)
{
  int thisNum = anArray[i];
  if (!maxVal.HasValue || thisNum > maxVal.Value)
  {
    maxVal = thisNum;
    index = i;
  }
}

This is more verbose than something using LINQ or other one-line solutions, but it's probably a little faster. There's really no way to make this faster than O(N).

What are these attributes: `aria-labelledby` and `aria-hidden`

HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.

To be precise for your question, here is what your attributes are called as ARIA attribute states and model

aria-labelledby: Identifies the element (or elements) that labels the current element.

aria-hidden (state): Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.

Embed Youtube video inside an Android app

Pretty simple: Just put it inside a static method.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Understanding implicit in Scala

WARNING: contains sarcasm judiciously! YMMV...

Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    Text(prefix.text + " " + content)
  }

  def printText(text: Text): Unit = {
    println(text.content)
  }

  def main(args: Array[String]): Unit = {
    printText("World!")
  }

  // Best to hide this line somewhere below a pile of completely unrelated code.
  // Better yet, import its package from another distant place.
  implicit val prefixLOL = Prefix("Hello")
}

How do you get the current text contents of a QComboBox?

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())