Programs & Examples On #Wsgen

Replace whitespace with a comma in a text file in Linux

This worked for me.

sed -e 's/\s\+/,/g' input.txt >> output.csv

Support for the experimental syntax 'classProperties' isn't currently enabled

I am using the babel parser explicitly. None of the above solutions worked for me. This worked.

const ast = parser.parse(inputCode, {
      sourceType: 'module',
      plugins: [
        'jsx',
        'classProperties', // '@babel/plugin-proposal-class-properties',
      ],
    });

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

How to take screenshot of a div with JavaScript?

<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation

Autoplay an audio with HTML5 embed tag while the player is invisible

You can use this simple code:

<embed src="audio.mp3" AutoPlay loop hidden>

for the result seen here: https://hataken.000webhostapp.com/list-anime.html

Updating Anaconda fails: Environment Not Writable Error

I had installed anaconda via the system installer on OS X in the past, which created a ~/.conda/environments.txt owned by root. Conda could not modify this file, hence the error.

To fix this issue, I changed the ownership of that directory and file to my username:

sudo chown -R $USER ~/.conda

What is considered a good response time for a dynamic, personalized web application?

Not only does it depend on what keeps your users happy, but how much development time do you have? What kind of resources can you throw at the problem (software, hardware, and people)?

I don't mind a couple-few second delay for hosted applications if they're doing something "complex". If it's really simple, delays bother me.

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Apply CSS to jQuery Dialog Buttons

I’m reposting my answer to a similar question because no-one seems to have given it here and it’s much cleaner and neater:

Use the alternative buttons property syntax:

$dialogDiv.dialog({
    autoOpen: false,
    modal: true,
    width: 600,
    resizable: false,
    buttons: [
        {
            text: "Cancel",
            "class": 'cancelButtonClass',
            click: function() {
                // Cancel code here
            }
        },
        {
            text: "Save",
            "class": 'saveButtonClass',
            click: function() {
                // Save code here
            }
        }
    ],
    close: function() {
        // Close code here (incidentally, same as Cancel code)
    }
});

is there something like isset of php in javascript/jQuery?

typeof will serve the purpose I think

if(typeof foo != "undefined"){}

python: how to check if a line is an empty line

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

CSS Border Not Working

The height is a 100% unsure, try putting display: block; or display: inline-block;

SQLite in Android How to update a specific row

Simple way:

String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;

myDataBase.execSQL(strSQL);

Unable to cast object of type 'System.DBNull' to type 'System.String`

I use an extension to eliminate this problem for me, which may or may not be what you are after.

It goes like this:

public static class Extensions
{

    public String TrimString(this object item)
    {
        return String.Format("{0}", item).Trim();
    }

}

Note:

This extension does not return null values! If the item is null or DBNull.Value, it will return an empty String.

Usage:

public string GetCustomerNumber(Guid id)
{
    var obj = 
        DBSqlHelperFactory.ExecuteScalar(
            connectionStringSplendidmyApp, 
            CommandType.StoredProcedure, 
            "GetCustomerNumber", 
            new SqlParameter("@id", id)
        );
    return obj.TrimString();
}

How to automatically start a service when running a docker container?

In your Dockerfile, add at the last line

ENTRYPOINT service ssh restart && bash

It works for me

And this is the result:

root@ubuntu:/home/vagrant/docker/add# docker run -i -t ubuntu
 * Restarting OpenBSD Secure Shell server sshd   [ OK ]                                                                      
root@dccc354e422e:~# service ssh status
 * sshd is running

Why shouldn't I use "Hungarian Notation"?

Of course when 99% of programmers agree on something, there is something wrong. The reason they agree here is because most of them have never used Hungarian notation correctly.

For a detailed argument, I refer you to a blog post I have made on the subject.

http://codingthriller.blogspot.com/2007/11/rediscovering-hungarian-notation.html

What in the world are Spring beans?

In Spring, those objects that form the backbone of your application and that are managed by the Spring IoC container are referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container;

How can I tail a log file in Python?

All the answers that use tail -f are not pythonic.

Here is the pythonic way: ( using no external tool or library)

def follow(thefile):
     while True:
        line = thefile.readline()
        if not line or not line.endswith('\n'):
            time.sleep(0.1)
            continue
        yield line



if __name__ == '__main__':
    logfile = open("run/foo/access-log","r")
    loglines = follow(logfile)
    for line in loglines:
        print(line, end='')

Reload activity in Android

Start with an intent your same activity and close the activity.

Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.

Delete all rows with timestamp older than x days

DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY

Replace N with your day count

How to utilize date add function in Google spreadsheet?

You can just add the number to the cell with the date.

so if A1: 12/3/2012 and A2: =A1+7 then A2 would display 12/10/2012

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

javascript regex for special characters

this is the actual regex only match:

/[-!$%^&*()_+|~=`{}[:;<>?,.@#\]]/g

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

codaddict has provided the right answer. As for what you've tried, I'll explain why they don't make the cut:

  • [0-9]{1,45} is almost there, however it matches a 1-to-45-digit string even if it occurs within another longer string containing other characters. Hence you need ^ and $ to restrict it to an exact match.

  • ^[0-9]{45}*$ matches an exactly-45-digit string, repeated 0 or any number of times (*). That means the length of the string can only be 0 or a multiple of 45 (90, 135, 180...).

How to get first character of a string in SQL?

I prefer:

SUBSTRING (my_column, 1, 1)

because it is Standard SQL-92 syntax and therefore more portable.


Strictly speaking, the standard version would be

SUBSTRING (my_column FROM 1 FOR 1)

The point is, transforming from one to the other, hence to any similar vendor variation, is trivial.

p.s. It was only recently pointed out to me that functions in standard SQL are deliberately contrary, by having parameters lists that are not the conventional commalists, in order to make them easily identifiable as being from the standard!

add new element in laravel collection object

I have solved this if you are using array called for 2 tables. Example you have, $tableA['yellow'] and $tableA['blue'] . You are getting these 2 values and you want to add another element inside them to separate them by their type.

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

So, both of the tables value will have new element called type.

jQuery - multiple $(document).ready ...?

Execution is top-down. First come, first served.

If execution sequence is important, combine them.

How can I get the console logs from the iOS Simulator?

If you are using Swift, remember that println will only print to the debug log (which appears in xCode's debug area). If you want to print to system.log, you have to use NSLog as in the old days.

Then you can view the simulator log via its menu, Debug > Open System Log... (cmd + /)

What .NET collection provides the fastest search

Have you considered List.BinarySearch(item)?

You said that your large collection is already sorted so this seems like the perfect opportunity? A hash would definitely be the fastest, but this brings about its own problems and requires a lot more overhead for storage.

How can I hide or encrypt JavaScript code?

One of the best compressors (not specifically an obfuscator) is the YUI Compressor.

Integer division: How do you produce a double?

Just add "D".

int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D

if checkbox is checked, do this

Try this.

$('#checkbox').click(function(){
    if (this.checked) {
        $('p').css('color', '#0099ff')
    }
}) 

Sometimes we overkill jquery. Many things can be achieved using jquery with plain javascript.

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

For reference: I had this error when trying to do an unattended VS 2013 install in a windowsservercore docker container:

.\vs_professional.exe /Q

reason turned out to be having the installation files on a docker volume, copying to the disk of the container solved it.

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

Adding a new entry to the PATH variable in ZSH

You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

path+=/some/new/bin/dir

This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

(Notice that no : is needed/wanted as a separator.)

Common interactive usage

Then the common pattern for testing a new script/executable becomes:

path+=$PWD/.
# or
path+=$PWD/bin

Common config usage

You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

Related tidbits

Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

Also take a look at vared path as a dynamic way to edit path (and other things).

You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

You can even prevent PATH from taking on duplicate entries (refer to this and this):

typeset -U path

Identifying country by IP address

You can try using https://ip-api.io - geo location api that returns country among other IP information.

For example with Node.js

const request = require('request-promise')

request('http://ip-api.io/api/json/1.2.3.4')
  .then(response => console.log(JSON.parse(response)))
  .catch(err => console.log(err))

How to get the current user's Active Directory details in C#

The "pre Windows 2000" name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName.

So try:

using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
   using(DirectorySearcher adSearch = new DirectorySearcher(de))
   {
     adSearch.Filter = "(sAMAccountName=someuser)";
     SearchResult adSearchResult = adSearch.FindOne();
   }
}

[email protected] is the UserPrincipalName, but it isn't a required field.

Authenticating in PHP using LDAP through Active Directory

For those looking for a complete example check out http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/.

I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

What is an idiomatic way of representing enums in Go?

It's true that the above examples of using const and iota are the most idiomatic ways of representing primitive enums in Go. But what if you're looking for a way to create a more fully-featured enum similar to the type you'd see in another language like Java or Python?

A very simple way to create an object that starts to look and feel like a string enum in Python would be:

package main

import (
    "fmt"
)

var Colors = newColorRegistry()

func newColorRegistry() *colorRegistry {
    return &colorRegistry{
        Red:   "red",
        Green: "green",
        Blue:  "blue",
    }
}

type colorRegistry struct {
    Red   string
    Green string
    Blue  string
}

func main() {
    fmt.Println(Colors.Red)
}

Suppose you also wanted some utility methods, like Colors.List(), and Colors.Parse("red"). And your colors were more complex and needed to be a struct. Then you might do something a bit like this:

package main

import (
    "errors"
    "fmt"
)

var Colors = newColorRegistry()

type Color struct {
    StringRepresentation string
    Hex                  string
}

func (c *Color) String() string {
    return c.StringRepresentation
}

func newColorRegistry() *colorRegistry {

    red := &Color{"red", "F00"}
    green := &Color{"green", "0F0"}
    blue := &Color{"blue", "00F"}

    return &colorRegistry{
        Red:    red,
        Green:  green,
        Blue:   blue,
        colors: []*Color{red, green, blue},
    }
}

type colorRegistry struct {
    Red   *Color
    Green *Color
    Blue  *Color

    colors []*Color
}

func (c *colorRegistry) List() []*Color {
    return c.colors
}

func (c *colorRegistry) Parse(s string) (*Color, error) {
    for _, color := range c.List() {
        if color.String() == s {
            return color, nil
        }
    }
    return nil, errors.New("couldn't find it")
}

func main() {
    fmt.Printf("%s\n", Colors.List())
}

At that point, sure it works, but you might not like how you have to repetitively define colors. If at this point you'd like to eliminate that, you could use tags on your struct and do some fancy reflecting to set it up, but hopefully this is enough to cover most people.

HashMap allows duplicates?

Each key in a HashMap must be unique.

When "adding a duplicate key" the old value (for the same key, as keys must be unique) is simply replaced; see HashMap.put:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Returns the previous value associated with key, or null if there was no mapping for key.

As far as nulls: a single null key is allowed (as keys must be unique) but the HashMap can have any number of null values, and a null key need not have a null value. Per the documentation:

[.. HashMap] permits null values and [a] null key.

However, the documentation says nothing about null/null needing to be a specific key/value pair or null/"a" being invalid.

Disable Required validation attribute under certain circumstances

The cleanest way here I believe is going to disable your client side validation and on the server side you will need to:

  1. ModelState["SomeField"].Errors.Clear (in your controller or create an action filter to remove errors before the controller code is executed)
  2. Add ModelState.AddModelError from your controller code when you detect a violation of your detected issues.

Seems even a custom view model here wont solve the problem because the number of those 'pre answered' fields could vary. If they dont then a custom view model may indeed be the easiest way, but using the above technique you can get around your validations issues.

Handling errors in Promise.all

NEW ANSWER

const results = await Promise.all(promises.map(p => p.catch(e => e)));
const validResults = results.filter(result => !(result instanceof Error));

FUTURE Promise API

What is "not assignable to parameter of type never" error in typescript?

I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:

const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

Convert integer value to matching Java Enum

You can do something like this to automatically register them all into a collection with which to then easily convert the integers to the corresponding enum. (BTW, adding them to the map in the enum constructor is not allowed. It's nice to learn new things even after many years of using Java. :)

public enum PcapLinkType {
    DLT_NULL(0),
    DLT_EN10MB(1),
    DLT_EN3MB(2),
    DLT_AX25(3),
    /*snip, 200 more enums, not always consecutive.*/
    DLT_UNKNOWN(-1);

    private static final Map<Integer, PcapLinkType> typesByValue = new HashMap<Integer, PcapLinkType>();

    static {
        for (PcapLinkType type : PcapLinkType.values()) {
            typesByValue.put(type.value, type);
        }
    }

    private final int value;

    private PcapLinkType(int value) {
        this.value = value;
    }

    public static PcapLinkType forValue(int value) {
        return typesByValue.get(value);
    }
}

Can't stop rails server

Follow these steps:

  1. open your project
  2. select in tmp folder
  3. select pids folder
  4. delete server.pid file
  5. now start your rails server

100% width table overflowing div container

Add display: block; and overflow: auto; to .my-table. This will simply cut off anything past the 280px limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough which are wider than 280px.

sql query to get earliest date

Using "limit" and "top" will not work with all SQL servers (for example with Oracle). You can try a more complex query in pure sql:

select mt1.id, mt1."name", mt1.score, mt1."date" from mytable mt1
where mt1.id=2
and mt1."date"= (select min(mt2."date") from mytable mt2 where mt2.id=2)

How to load a xib file in a UIView

For swift 3 & 4

let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView

Validate Dynamically Added Input fields

$('#form-btn').click(function () {
//set global rules & messages array to use in validator
   var rules = {};
   var messages = {};
//get input, select, textarea of form
   $('#formId').find('input, select, textarea').each(function () {
      var name = $(this).attr('name');
      rules[name] = {};
      messages[name] = {};

      rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
      if (name === "email") {
         rules[name].email = true;
         //messages[name].email = "Please provide valid email";
      }
      else if(name==='url'){
        rules[name].required = false; // url filed is not required
//add other rules & messages
      }
   });
//submit form and use above created global rules & messages array
   $('#formId').submit(function (e) {
            e.preventDefault();
        }).validate({
            rules: rules,
            messages: messages,
            submitHandler: function (form) {
            console.log("validation success");
            }
        });
});

PHP passing $_GET in linux command prompt

Sometimes you don't have the option of editing the php file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.

I found this to be the best solution for that case:

php -r '$_GET["key"]="value"; require_once("script.php");' 

This avoids altering your php file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. Thought this options was worthy of mention

the -r means run the php code in the string following. you set the $_GET value manually there, and then reference the file you want to run.

Its worth noting you should run this in the right folder, often but not always the folder the php file is in. Requires statements will use the location of your command to resolve relative urls, NOT the location of the file

Printing string variable in Java

You could also use BufferedReader:

import java.io.*;

public class TestApplication {
   public static void main (String[] args) {
      System.out.print("Enter a password: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String password = null;
      try {
         password = br.readLine();
      } catch (IOException e) {
         System.out.println("IO error trying to read your password!");
         System.exit(1);
      }
      System.out.println("Successfully read your password.");
   }
}

Get file size before uploading

Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.

ActiveX warning

If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).

function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Compare string with all values in list

In Python you may use the in operator. You can do stuff like this:

>>> "c" in "abc"
True

Taking this further, you can check for complex structures, like tuples:

>>> (2, 4, 8) in ((1, 2, 3), (2, 4, 8))
True

change cursor to finger pointer

_x000D_
_x000D_
div{cursor: pointer; color:blue}_x000D_
_x000D_
p{cursor: text; color:red;}
_x000D_
<div> im Pointer  cursor </div> _x000D_
<p> im Txst cursor </p> 
_x000D_
_x000D_
_x000D_

How do I get started with Node.js

Use the source, Luke.

No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.

Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

EditText, clear focus on touch outside

Just put these properties in the top most parent.

android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="true" 

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

I had the same problem earlier today. I could not figure out why the class file I was trying to reference was not being seen by the compiler. I had recently changed the namespace of the class file in question to a different but already existing namespace. (I also had using references to the class's new and previous namespaces where I was trying to instantiate it)

Where the compiler was telling me I was missing a reference when trying to instantiate the class, I right clicked and hit "generate class stub". Once Visual Studio generated a class stub for me, I coped and pasted the code from the old class file into this stub, saved the stub and when I tried to compile again it worked! No issues.

Might be a solution specific to my build, but its worth a try.

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

What characters are allowed in an email address?

A good read on the matter.

Excerpt:

These are all valid email addresses!

"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/[email protected]
\[email protected]
!def!xyz%[email protected]
[email protected]

batch script - read line by line

The "call" solution has some problems.

It fails with many different contents, as the parameters of a CALL are parsed twice by the parser.
These lines will produce more or less strange problems

one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty

the end

Therefore you shouldn't use the value of %%a with a call, better move it to a variable and then call a function with only the name of the variable.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "myVar=%%a"
    call :processLine myVar
)
goto :eof

:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof

How to write the Fibonacci Sequence?

fibonacci

The fibonacci sequence if you don't know what that is basically you print out a number and each each number that you print out is the previous two numbers added together.

a, b = 0,1 
for i in range(0, 10):
    print(a)
    a, b = b, a + b

output:

0
1
1
2
3
5
8
13
21
34

So 0 and 1 if you add those together it equals 1 if you add 1 and 1 it equals 2 if you add 1 and 2 it equals 3 and it keeps going and keeps going.


Fibonacci sequence here that I've written using generators:

def fib(num): 
    a, b = 0,1 
    for i in range(0, num):
        yield "{}: {}".format(i+1, a)
        a, b = b, a + b
        
for item in fib(10):
    print(item)

output:

1: 0
2: 1
3: 1
4: 2
5: 3
6: 5
7: 8
8: 13
9: 21
10: 34

Fibonacci sequence that we went over before except now we have a function here yields and yield is the keyword that lets you know that it's a generator.

  • So, it yields your result and then we can loop through the generator and print out each item.
  • If we run through then we can see that it still works just like it worked before but now we're using generators instead which have more advantages over returning a list but there are times and when you wouldn't want to use generators.
  • You need do to your research and figure out when you really do get those advantages from generators and when they may not be the best option for you.

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

numpy: most efficient frequency counts for unique values in an array

As of Numpy 1.9, the easiest and fastest method is to simply use numpy.unique, which now has a return_counts keyword argument:

import numpy as np

x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)

print np.asarray((unique, counts)).T

Which gives:

 [[ 1  5]
  [ 2  3]
  [ 5  1]
  [25  1]]

A quick comparison with scipy.stats.itemfreq:

In [4]: x = np.random.random_integers(0,100,1e6)

In [5]: %timeit unique, counts = np.unique(x, return_counts=True)
10 loops, best of 3: 31.5 ms per loop

In [6]: %timeit scipy.stats.itemfreq(x)
10 loops, best of 3: 170 ms per loop

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

<img title="<a href="javascript:alert('hello world')">The Link</a>" /> 

Is there a way to get colored text in GitHubflavored Markdown?

As an alternative to rendering a raster image, you can embed a SVG:

https://gist.github.com/CyberShadow/95621a949b07db295000

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

Convert integer to hexadecimal and back again

int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output

Android - get children inside a View?

As an update for those who come across this question after 2018, if you are using Kotlin, you can simply use the Android KTX extension property ViewGroup.children to get a sequence of the View's immediate children.

How do I run Visual Studio as an administrator by default?

Applying this change will make it so that when you double click on a .sln file Visual Studio will not open. Also, you will not be able to drag and drop files into Visual Studio.

Follow the numbered instructions for each file in the bullited list. The paths are for a standard 64-bit install so you may have to adjust them for your system.

  • C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\VSLauncher.exe
  • C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe
  • C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
  • C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe

    1. Right click on the file and select Properties
    2. Select the Compatibility tab
    3. Optional: Select Change settings for all users
    4. Select Run this program as an administrator
    5. Select Ok and close the dialog

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

Mederr's context transform works perfectly. If you need to extract orientation only use this function - you don't need any EXIF-reading libs. Below is a function for re-setting orientation in base64 image. Here's a fiddle for it. I've also prepared a fiddle with orientation extraction demo.

function resetOrientation(srcBase64, srcOrientation, callback) {
  var img = new Image();    

  img.onload = function() {
    var width = img.width,
        height = img.height,
        canvas = document.createElement('canvas'),
        ctx = canvas.getContext("2d");

    // set proper canvas dimensions before transform & export
    if (4 < srcOrientation && srcOrientation < 9) {
      canvas.width = height;
      canvas.height = width;
    } else {
      canvas.width = width;
      canvas.height = height;
    }

    // transform context before drawing image
    switch (srcOrientation) {
      case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
      case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
      case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
      case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
      case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
      case 7: ctx.transform(0, -1, -1, 0, height, width); break;
      case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
      default: break;
    }

    // draw image
    ctx.drawImage(img, 0, 0);

    // export base64
    callback(canvas.toDataURL());
  };

  img.src = srcBase64;
};

Bootstrap modal: is not a function

The problem is due to having jQuery instances more than one time. Take care if you are using many files with multiples instance of jQuery. Just leave 1 instance of jQuery and your code will work.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

$(document).on("click"... not working?

Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).

Jquery:

$(document).on('click','#test-element',function(){
    alert("You clicked the element with and ID of 'test-element'");
});

As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element but not for any that follow.

If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document instead of test-element. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different documents and therefore you are clicking the document.

If neither of these are the answer, posting HTML will go a long way toward figuring it out.

Hiding button using jQuery

jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:

$('#comanda').hide();

One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):

$('#comanda').hide('fast');

In case you want to do something just after the element hid, you must provide a callback as a parameter too:

$('#comanda').hide('fast', function() {
  alert('It is hidden now!');
});

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

There are a few options:

  • Nest the AsyncTask class within your Activity class. Assuming you don't use the same task in multiple activities, this is the easiest way. All your code stays the same, you just move the existing task class to be a nested class inside your activity's class.

    public class MyActivity extends Activity {
        // existing Activity code
        ...
    
        private class MyAsyncTask extends AsyncTask<String, Void, String> {
            // existing AsyncTask code
            ...
        }
    }
    
  • Create a custom constructor for your AsyncTask that takes a reference to your Activity. You would instantiate the task with something like new MyAsyncTask(this).execute(param1, param2).

    public class MyAsyncTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public MyAsyncTask(Activity activity) {
            this.activity = activity;
        }
    
        // existing AsyncTask code
        ...
    }
    

Get selected option text with JavaScript

You'll need to get the innerHTML of the option, and not its value.

Use this.innerHTML instead of this.selectedIndex.

Edit: You'll need to get the option element first and then use innerHTML.

Use this.text instead of this.selectedIndex.

List submodules in a Git repository

You can use:

git submodule | awk '{ print $2 }'

How to move table from one tablespace to another in oracle 11g

Try this to move your table (tbl1) to tablespace (tblspc2).

alter table tb11 move tablespace tblspc2;

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x

p <- ggplot(plot, aes(x = pred, y = value)) +
     geom_point(size = 2.5) +
     theme_bw()+
     coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p

enter image description here

How do I tell if a regular file does not exist in Bash?

This shell script also works for finding a file in a directory:

echo "enter file"

read -r a

if [ -s /home/trainee02/"$a" ]
then
    echo "yes. file is there."
else
    echo "sorry. file is not there."
fi

Converting Python dict to kwargs?

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

Generate an integer sequence in MySQL

You could try something like this:

SELECT @rn:=@rn+1 as n
FROM (select @rn:=2)t, `order` rows_1, `order` rows_2 --, rows_n as needed...
LIMIT 4

Where order is just en example of some table with a reasonably large set of rows.

Edit: The original answer was wrong, and any credit should go to David Poor who provided a working example of the same concept

Could not find a part of the path ... bin\roslyn\csc.exe

Per a comment by Daniel Neel above :

version 1.0.3 of the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package works for me, but version 1.0.6 causes the error in this question

Downgrading to 1.0.3 resolved this issue for me.

How to get size of mysql database?

Alternatively, if you are using phpMyAdmin, you can take a look at the sum of the table sizes in the footer of your database structure tab. The actual database size may be slightly over this size, however it appears to be consistent with the table_schema method mentioned above.

Screen-shot :

enter image description here

How to get the current taxonomy term ID (not the slug) in WordPress?

If you are in taxonomy page.

That's how you get all details about the taxonomy.

get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

This is how you get the taxonomy id

$termId = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) )->term_id;

But if you are in post page (taxomony -> child)

$terms = wp_get_object_terms( get_queried_object_id(), 'taxonomy-name');
$term_id = $terms[0]->term_id;

Numbering rows within groups in a data frame

For making this question more complete, a base R alternative with sequence and rle:

df$num <- sequence(rle(df$cat)$lengths)

which gives the intended result:

> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

If df$cat is a factor variable, you need to wrap it in as.character first:

df$num <- sequence(rle(as.character(df$cat))$lengths)

Sharing a variable between multiple different threads

Both T1 and T2 can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.

See this article for more info.

Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.

And note the pros/cons of using volatile vs more complex means of sharing state.

When should I use a List vs a LinkedList

Essentially, a List<> in .NET is a wrapper over an array. A LinkedList<> is a linked list. So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list. Probably the two most important factors in your decision of which to use would come down to:

  • Linked lists have much better insertion/removal performance, so long as the insertions/removals are not on the last element in the collection. This is because an array must shift all remaining elements that come after the insertion/removal point. If the insertion/removal is at the tail end of the list however, this shift is not needed (although the array may need to be resized, if its capacity is exceeded).
  • Arrays have much better accessing capabilities. Arrays can be indexed into directly (in constant time). Linked lists must be traversed (linear time).

Create a button programmatically and set a background image

Swift: Ui Button create programmatically

let myButton = UIButton()

myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)

myButton.titleLabel!.text = "Button Label"

myButton.titleLabel!.textColor = UIColor.redColor()

myButton.titleLabel!.textAlignment = .Center

myButton.addTarget(self,action:"Action:",forControlEvents:UIControlEvent.TouchUpInside)

self.view.addSubview(myButton)

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

MySQLi prepared statements error reporting

Not sure if this answers your question or not. Sorry if not

To get the error reported from the mysql database about your query you need to use your connection object as the focus.

so:

echo $mysqliDatabaseConnection->error

would echo the error being sent from mysql about your query.

Hope that helps

JAX-RS — How to return JSON and HTTP status code together?

Here's an example:

@GET
@Path("retrieve/{uuid}")
public Response retrieveSomething(@PathParam("uuid") String uuid) {
    if(uuid == null || uuid.trim().length() == 0) {
        return Response.serverError().entity("UUID cannot be blank").build();
    }
    Entity entity = service.getById(uuid);
    if(entity == null) {
        return Response.status(Response.Status.NOT_FOUND).entity("Entity not found for UUID: " + uuid).build();
    }
    String json = //convert entity to json
    return Response.ok(json, MediaType.APPLICATION_JSON).build();
}

Take a look at the Response class.

Note that you should always specify a content type, especially if you are passing multiple content types, but if every message will be represented as JSON, you can just annotate the method with @Produces("application/json")

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

How do I iterate through children elements of a div using jQuery?

Use children() and each(), you can optionally pass a selector to children

$('#mydiv').children('input').each(function () {
    alert(this.value); // "this" is the current element in the loop
});

You could also just use the immediate child selector:

$('#mydiv > input').each(function () { /* ... */ });

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

Eclipse error "Could not find or load main class"

I faced the similar problem, a workaround is to open up a terminal, go to project folder and run

java cp target/<your_jar_artifact.jar> <com.your_package.YourMainClass>

How to find the Windows version from the PowerShell command line

Windows PowerShell 2.0:

$windows = New-Object -Type PSObject |
           Add-Member -MemberType NoteProperty -Name Caption -Value (Get-WmiObject -Class Win32_OperatingSystem).Caption -PassThru |
           Add-Member -MemberType NoteProperty -Name Version -Value [Environment]::OSVersion.Version                     -PassThru

Windows PowerShell 3.0:

$windows = [PSCustomObject]@{
    Caption = (Get-WmiObject -Class Win32_OperatingSystem).Caption
    Version = [Environment]::OSVersion.Version
}

For display (both versions):

"{0}  ({1})" -f $windows.Caption, $windows.Version 

Loop Through All Subfolders Using VBA

Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

A monad is just a monoid in the category of endofunctors, what's the problem?

First, the extensions and libraries that we're going to use:

{-# LANGUAGE RankNTypes, TypeOperators #-}

import Control.Monad (join)

Of these, RankNTypes is the only one that's absolutely essential to the below. I once wrote an explanation of RankNTypes that some people seem to have found useful, so I'll refer to that.

Quoting Tom Crockett's excellent answer, we have:

A monad is...

  • An endofunctor, T : X -> X
  • A natural transformation, µ : T × T -> T, where × means functor composition
  • A natural transformation, ? : I -> T, where I is the identity endofunctor on X

...satisfying these laws:

  • µ(µ(T × T) × T)) = µ(T × µ(T × T))
  • µ(?(T)) = T = µ(T(?))

How do we translate this to Haskell code? Well, let's start with the notion of a natural transformation:

-- | A natural transformations between two 'Functor' instances.  Law:
--
-- > fmap f . eta g == eta g . fmap f
--
-- Neat fact: the type system actually guarantees this law.
--
newtype f :-> g =
    Natural { eta :: forall x. f x -> g x }

A type of the form f :-> g is analogous to a function type, but instead of thinking of it as a function between two types (of kind *), think of it as a morphism between two functors (each of kind * -> *). Examples:

listToMaybe :: [] :-> Maybe
listToMaybe = Natural go
    where go [] = Nothing
          go (x:_) = Just x

maybeToList :: Maybe :-> []
maybeToList = Natural go
    where go Nothing = []
          go (Just x) = [x]

reverse' :: [] :-> []
reverse' = Natural reverse

Basically, in Haskell, natural transformations are functions from some type f x to another type g x such that the x type variable is "inaccessible" to the caller. So for example, sort :: Ord a => [a] -> [a] cannot be made into a natural transformation, because it's "picky" about which types we may instantiate for a. One intuitive way I often use to think of this is the following:

  • A functor is a way of operating on the content of something without touching the structure.
  • A natural transformation is a way of operating on the structure of something without touching or looking at the content.

Now, with that out of the way, let's tackle the clauses of the definition.

The first clause is "an endofunctor, T : X -> X." Well, every Functor in Haskell is an endofunctor in what people call "the Hask category," whose objects are Haskell types (of kind *) and whose morphisms are Haskell functions. This sounds like a complicated statement, but it's actually a very trivial one. All it means is that that a Functor f :: * -> * gives you the means of constructing a type f a :: * for any a :: * and a function fmap f :: f a -> f b out of any f :: a -> b, and that these obey the functor laws.

Second clause: the Identity functor in Haskell (which comes with the Platform, so you can just import it) is defined this way:

newtype Identity a = Identity { runIdentity :: a }

instance Functor Identity where
    fmap f (Identity a) = Identity (f a)

So the natural transformation ? : I -> T from Tom Crockett's definition can be written this way for any Monad instance t:

return' :: Monad t => Identity :-> t
return' = Natural (return . runIdentity)

Third clause: The composition of two functors in Haskell can be defined this way (which also comes with the Platform):

newtype Compose f g a = Compose { getCompose :: f (g a) }

-- | The composition of two 'Functor's is also a 'Functor'.
instance (Functor f, Functor g) => Functor (Compose f g) where
    fmap f (Compose fga) = Compose (fmap (fmap f) fga)

So the natural transformation µ : T × T -> T from Tom Crockett's definition can be written like this:

join' :: Monad t => Compose t t :-> t
join' = Natural (join . getCompose)

The statement that this is a monoid in the category of endofunctors then means that Compose (partially applied to just its first two parameters) is associative, and that Identity is its identity element. I.e., that the following isomorphisms hold:

  • Compose f (Compose g h) ~= Compose (Compose f g) h
  • Compose f Identity ~= f
  • Compose Identity g ~= g

These are very easy to prove because Compose and Identity are both defined as newtype, and the Haskell Reports define the semantics of newtype as an isomorphism between the type being defined and the type of the argument to the newtype's data constructor. So for example, let's prove Compose f Identity ~= f:

Compose f Identity a
    ~= f (Identity a)                 -- newtype Compose f g a = Compose (f (g a))
    ~= f a                            -- newtype Identity a = Identity a
Q.E.D.

Can I start the iPhone simulator without "Build and Run"?

For Xcode 7.2

open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator.app

sudo ./Simulator

And adding this path in your profile is the best way.

undefined reference to `WinMain@16'

This error occurs when the linker can't find WinMain function, so it is probably missing. In your case, you are probably missing main too.

Consider the following Windows API-level program:

#define NOMINMAX
#include <windows.h>

int main()
{
    MessageBox( 0, "Blah blah...", "My Windows app!", MB_SETFOREGROUND );
}

Now let's build it using GNU toolchain (i.e. g++), no special options. Here gnuc is just a batch file that I use for that. It only supplies options to make g++ more standard:

C:\test> gnuc x.cpp

C:\test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000003        (Windows CUI)

C:\test> _

This means that the linker by default produced a console subsystem executable. The subsystem value in the file header tells Windows what services the program requires. In this case, with console system, that the program requires a console window.

This also causes the command interpreter to wait for the program to complete.

Now let's build it with GUI subsystem, which just means that the program does not require a console window:

C:\test> gnuc x.cpp -mwindows

C:\test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:\test> _

Hopefully that's OK so far, although the -mwindows flag is just semi-documented.

Building without that semi-documented flag one would have to more specifically tell the linker which subsystem value one desires, and some Windows API import libraries will then in general have to be specified explicitly:

C:\test> gnuc x.cpp -Wl,-subsystem,windows

C:\test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:\test> _

That worked fine, with the GNU toolchain.

But what about the Microsoft toolchain, i.e. Visual C++?

Well, building as a console subsystem executable works fine:

C:\test> msvc x.cpp user32.lib
x.cpp

C:\test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               3 subsystem (Windows CUI)

C:\test> _

However, with Microsoft's toolchain building as GUI subsystem does not work by default:

C:\test> msvc x.cpp user32.lib /link /subsystem:windows
x.cpp
LIBCMT.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartu
p
x.exe : fatal error LNK1120: 1 unresolved externals

C:\test> _

Technically this is because Microsoft’s linker is non-standard by default for GUI subsystem. By default, when the subsystem is GUI, then Microsoft's linker uses a runtime library entry point, the function where the machine code execution starts, called winMainCRTStartup, that calls Microsoft's non-standard WinMain instead of standard main.

No big deal to fix that, though.

All you have to do is to tell Microsoft's linker which entry point to use, namely mainCRTStartup, which calls standard main:

C:\test> msvc x.cpp user32.lib /link /subsystem:windows /entry:mainCRTStartup
x.cpp

C:\test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               2 subsystem (Windows GUI)

C:\test> _

No problem, but very tedious. And so arcane and hidden that most Windows programmers, who mostly only use Microsoft’s non-standard-by-default tools, do not even know about it, and mistakenly think that a Windows GUI subsystem program “must” have non-standard WinMain instead of standard main. In passing, with C++0x Microsoft will have a problem with this, since the compiler must then advertize whether it's free-standing or hosted (when hosted it must support standard main).

Anyway, that's the reason why g++ can complain about WinMain missing: it's a silly non-standard startup function that Microsoft's tools require by default for GUI subsystem programs.

But as you can see above, g++ has no problem with standard main even for a GUI subsystem program.

So what could be the problem?

Well, you are probably missing a main. And you probably have no (proper) WinMain either! And then g++, after having searched for main (no such), and for Microsoft's non-standard WinMain (no such), reports that the latter is missing.

Testing with an empty source:

C:\test> type nul >y.cpp

C:\test> gnuc y.cpp -mwindows
c:/program files/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined referen
ce to `WinMain@16'
collect2: ld returned 1 exit status

C:\test> _

How to set locale in DatePipe in Angular 2?

Solution with LOCALE_ID is great if you want to set the language for your app once. But it doesn’t work, if you want to change the language during runtime. For this case you can implement custom date pipe.

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'localizedDate',
  pure: false
})
export class LocalizedDatePipe implements PipeTransform {

  constructor(private translateService: TranslateService) {
  }

  transform(value: any, pattern: string = 'mediumDate'): any {
    const datePipe: DatePipe = new DatePipe(this.translateService.currentLang);
    return datePipe.transform(value, pattern);
  }

}

Now if you change the app display language using TranslateService (see ngx-translate)

this.translateService.use('en');

the formats within your app should automatically being updated.

Example of use:

<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>

or check my simple "Notes" project here.

enter image description here

Get Base64 encode file-data from Input Form

I used FileReader to display image on click of the file upload button not using any Ajax requests. Following is the code hope it might help some one.

$(document).ready(function($) {
    $.extend( true, jQuery.fn, {        
        imagePreview: function( options ){          
            var defaults = {};
            if( options ){
                $.extend( true, defaults, options );
            }
            $.each( this, function(){
                var $this = $( this );              
                $this.bind( 'change', function( evt ){

                    var files = evt.target.files; // FileList object
                    // Loop through the FileList and render image files as thumbnails.
                    for (var i = 0, f; f = files[i]; i++) {
                        // Only process image files.
                        if (!f.type.match('image.*')) {
                        continue;
                        }
                        var reader = new FileReader();
                        // Closure to capture the file information.
                        reader.onload = (function(theFile) {
                            return function(e) {
                                // Render thumbnail.
                                    $('#imageURL').attr('src',e.target.result);                         
                            };
                        })(f);
                        // Read in the image file as a data URL.
                        reader.readAsDataURL(f);
                    }

                });
            });
        }   
    });
    $( '#fileinput' ).imagePreview();
});

Postgres password authentication fails

pg_hba.conf entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf in order to get proper help.

Change this line:

host    all             all             <my-ip-address>/32        md5

To reflect your local network settings. So, if your IP is 192.168.16.78 (class C) with a mask of 255.255.255.0, then put this:

host    all             all             192.168.16.0/24        md5

Make sure your WINDOWS MACHINE is in that network 192.168.16.0 and try again.

C linked list inserting node at the end

The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node.

/* Given a reference (pointer to pointer) to the head
   of a list and an int, appends a new node at the end  */


    void append(struct node** head_ref, int new_data)
    {
    /* 1. allocate node */
         struct node* new_node = (struct node*) malloc(sizeof(struct node));

        struct node *last = *head_ref;  /* used in step 5*/

    /* 2. put in the data  */
        new_node->data  = new_data;

    /* 3. This new node is going to be the last node, so make next 
          of it as NULL*/
        new_node->next = NULL;

    /* 4. If the <a href="#">Linked List</a> is empty, then make the new node as head */
        if (*head_ref == NULL)
        {
       *head_ref = new_node;
       return;
        }  

    /* 5. Else traverse till the last node */
        while (last->next != NULL)
        last = last->next;

    /* 6. Change the next of last node */
        last->next = new_node;
        return;    
}

Bundler: Command not found

My problem was that I did:

sudo gem install bundler

So I had installed as root rather than as myself. So I uninstalled as root, then installed as myself:

sudo gem uninstall bundler
gem install bundler
rbenv rehash

(last command for if you are using rbenv)

And it worked. The "correct" path was in .bashrc (or other shell profile), at least according to

$PATH
=> zsh: /Users/myself/.rbenv/shims:/Users/myself/.rbenv/bin: ... etc

but it was expecting it to be installed for myself - not for root. In my case, its rightful installation place is in ~/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/bundler

C++11 reverse range-based for-loop

You could simply use BOOST_REVERSE_FOREACH which iterates backwards. For example, the code

#include <iostream>
#include <boost\foreach.hpp>

int main()
{
    int integers[] = { 0, 1, 2, 3, 4 };
    BOOST_REVERSE_FOREACH(auto i, integers)
    {
        std::cout << i << std::endl;
    }
    return 0;
}

generates the following output:

4

3

2

1

0

jQuery Ajax File Upload

Use FormData. It works really well :-) ...

var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit

$.ajax({
    url: '/your-form-processing-page-url-here',
    type: 'POST',
    data: jform,
    dataType: 'json',
    mimeType: 'multipart/form-data', // this too
    contentType: false,
    cache: false,
    processData: false,
    success: function(data, status, jqXHR){
        alert('Hooray! All is well.');
        console.log(data);
        console.log(status);
        console.log(jqXHR);

    },
    error: function(jqXHR,status,error){
        // Hopefully we should never reach here
        console.log(jqXHR);
        console.log(status);
        console.log(error);
    }
});

Command line .cmd/.bat script, how to get directory of running script

Raymond Chen has a few ideas:

https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573

Quoted here in full because MSDN archives tend to be somewhat unreliable:

The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory

(Of course, directory save/restore could more easily have been done with pushd/popd, but that's not the point here.)

The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.

set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args

(I like to use %_% as my scratch environment variable.)

Type SET /? to see the other pseudo-variables provided by the command processor.

Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):

http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741

This covers the use of %~dp0:

If you want to know where the batch file lives: %~dp0

%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.

Angular 2: How to call a function after get a response from subscribe http.post

You can add a callback function to your list of get_category(...) parameters.

Ex:

 get_categories(number, callback){
 this.http.post( url, body, {headers: headers, withCredentials:true})
    .subscribe( 
      response => {
        this.total = response.json();
        callback(); 

      }, error => {
    }
  ); 

}

And then you can just call get_category(...) like this:

this.get_category(1, name_of_function);

What is the difference between decodeURIComponent and decodeURI?

To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.

The main difference is that:

  • The encodeURI function is intended for use on the full URI.
  • The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

Insert new column into table in sqlite?

You can add new column with the query

ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)

But it will be added at the end, not in between the existing columns.

Is a new line = \n OR \r\n?

The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):

  • \r\n is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.
  • \n is used for all other systems, applications and the Internet.

You'll notice that I've put most Windows apps in the \n group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n because, while Windows may use \r\n, the Internet uses \n. Therefore, it is best practice for applications to use \n alone if you want your output to be Internet friendly.

PHP also defines a newline character called PHP_EOL. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n for Windows and \n for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.

If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use / for your path separator (not \).

The even longer explanation:

An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n then display a period).

Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).

That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

Pushing an existing Git repository to SVN

I just want to share some of my experience with the accepted answer. I did all steps and all was fine before I ran the last step:

git svn dcommit

$ git svn dcommit

Use of uninitialized value $u in substitution (s///) at /usr/lib/perl5/vendor_perl/5.22/Git/SVN.pm line 101.

Use of uninitialized value $u in concatenation (.) or string at /usr/lib/perl5/vendor_perl/5.22/Git/SVN.pm line 101. refs/remotes/origin/HEAD: 'https://192.168.2.101/svn/PROJECT_NAME' not found in ''

I found the thread https://github.com/nirvdrum/svn2git/issues/50 and finally the solution which I applied in the following file in line 101 /usr/lib/perl5/vendor_perl/5.22/Git/SVN.pm

I replaced

$u =~ s!^\Q$url\E(/|$)!! or die

with

if (!$u) {
    $u = $pathname;
} 
else {
       $u =~ s!^\Q$url\E(/|$)!! or die
      "$refname: '$url' not found in '$u'\n";
}

This fixed my issue.

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

HTML5 form validation pattern alphanumeric with spaces?

How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+". If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"

Vertical Tabs with JQuery?

Another options is Matteo Bicocchi's jQuery mb.extruder tabs plug-in: http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-extruder/

Prevent div from moving while resizing the page

hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body> in a fixed width <div style="margin: 0 auto; width: 900px> to achieve what you have done with the body {margin: 0 10% 0 10%}

How to compare strings in sql ignoring case?

To avoid string conversions comparisons, use COLLATE SQL_Latin1_General_CP1_CI_AS.

EXAMPLE:

SELECT UserName FROM Users
WHERE UserName **COLLATE SQL_Latin1_General_CP1_CI_AS** = 'Angel'

That will return any usernames, whether ANGEL, angel, or Angel, etc.

How do I configure Maven for offline development?

A new plugin has appeared to fix shortcomings of mvn dependency:go-offline:

https://github.com/qaware/go-offline-maven-plugin

Add it in your pom, then run mvn -T1C de.qaware.maven:go-offline-maven-plugin:resolve-dependencies. Once you've setup all dynamic dependencies, maven won't try to download anything again (until you update versions).

C99 stdint.h header and MS Visual Studio

Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible. (Thanks to rdentato for his comment.)

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

How do you run a command for each line of a file?

The logic applies to many other objectives. And how to read .sh_history of each user from /home/ filesystem? What if there are thousand of them?

#!/bin/ksh
last |head -10|awk '{print $1}'|
 while IFS= read -r line
 do
su - "$line" -c 'tail .sh_history'
 done

Here is the script https://github.com/imvieira/SysAdmin_DevOps_Scripts/blob/master/get_and_run.sh

How can I get dictionary key as variable directly in Python (not by searching from value)?

As simple as that:

mydictionary={'keyname':'somevalue'}
result = mydictionary.popitem()[0]

You will modify your dictionary and should make a copy of it first

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

JAVA_HOME and PATH are set but java -version still shows the old one

Try this:

  • export JAVA_HOME=put_here_your_java_home_path
  • type export PATH=$JAVA_HOME/bin:$PATH (ensure that $JAVA_HOME is the first element in PATH)
  • try java -version

Reason: there could be other PATH elements point to alternative java home. If you put first your preferred JAVA_HOME, the system will use this one.

Why does HTML think “chucknorris” is a color?

chucknorris starts with c, and the browser reads it into a hexadecimal value.

Because A, B, C, D, E, and F are characters in hexadecimal.

The browser converts chucknorris to a hexadecimal value, C00C00000000.

Then the C00C00000000 hexadecimal value is converted to RGB format (divided by 3):

C00C00000000 ? R:C00C, G:0000, B:0000

The browser needs only two digits to indicate the colour:

R:C00C, G:0000, B:0000 ? R:C0, G:00, B:00 ? C00000

Finally, show bgcolor = C00000 in the web browser.

Here's an example demonstrating it:

_x000D_
_x000D_
<table>
  <tr>
    <td bgcolor="chucknorris" cellpadding="10" width="150" align="center">chucknorris</td>
    <td bgcolor="c00c00000000" cellpadding="10" width="150" align="center">c00c00000000</td>
    <td bgcolor="c00000" cellpadding="10" width="150" align="center">c00000</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Just add this one-line class in your CSS, and use the bootstrap label component.

.label-as-badge {
    border-radius: 1em;
}

Compare this label and badge side by side:

<span class="label label-default label-as-badge">hello</span>
<span class="badge">world</span>

enter image description here

They appear the same. But in the CSS, label uses em so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples:

<span class="label label-success label-as-badge">Yay! Rah!</span>

enter image description here

Or where things are bigger:

<div style="font-size: 36px"><!-- pretend an enclosing class has big font size -->
    <span class="label label-success label-as-badge">Yay! Rah!</span>
</div>

enter image description here


11/16/2015: Looking at how we'll do this in Bootstrap 4

Looks like .badge classes are completely gone. But there's a built-in .label-pill class (here) that looks like what we want.

.label-pill {
  padding-right: .6em;
  padding-left: .6em;
  border-radius: 10rem;
}

In use it looks like this:

<span class="label label-pill label-default">Default</span>
<span class="label label-pill label-primary">Primary</span>
<span class="label label-pill label-success">Success</span>
<span class="label label-pill label-info">Info</span>
<span class="label label-pill label-warning">Warning</span>
<span class="label label-pill label-danger">Danger</span>

enter image description here


11/04/2014: Here's an update on why cross-pollinating alert classes with .badge is not so great. I think this picture sums it up:

enter image description here

Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive.

The .label-as-badge solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The .label-as-badge class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS.

Yep, it is easier to just hack away and drop in those .alert-xxxxx classes -- you don't have to add any lines of CSS. Or you could care more about the little things and add one line.

Remote Procedure call failed with sql server 2008 R2

start SQL Server Agent from the command prompt using:

SQLAGENT90 -C -V>C:\SQLAGENT.OUT

Getting full-size profile picture

Profile pictures are scaled down to 125x125 on the facebook sever when they're uploaded, so as far as I know you can't get pictures bigger than that. How big is the picture you're getting?

Select and trigger click event of a radio button in jquery

Switch the order of the code: You're calling the click event before it is attached.

$(document).ready(function() {
      $("#checkbox_div input:radio").click(function() {

           alert("clicked");

      });

      $("input:radio:first").prop("checked", true).trigger("click");

});

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

How do I programmatically click on an element in JavaScript?

element.click() is a standard method outlined by the W3C DOM specification. Mozilla's Gecko/Firefox follows the standard and only allows this method to be called on INPUT elements.

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

INSERT VALUES WHERE NOT EXISTS

There is a great solution for this problem ,You can use the Merge Keyword of Sql

Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

You can check this before following, below is the sample

IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
    DROP TABLE dbo.TargetTable
GO

CREATE TABLE dbo.TargetTable
    (
    Id   INT NOT NULL,
    Name VARCHAR (255) NOT NULL,
    CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
    )
GO



INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO


Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

What is the difference between primary, unique and foreign key constraints, and indexes?

  1. A primary key is a column or a set of columns that uniquely identify a row in a table. A primary key should be short, stable and simple. A foreign key is a column (or set of columns) in a second table whose value is required to match the value of the primary key in the original table. Usually a foreign key is in a table that is different from the table whose primary key is required to match. A table can have multiple foreign keys.
  2. The primary key cannot accept null values. Foreign keys can accept multiple.
  3. We can have only one primary key in a table. We can have more than one foreign key in a table.
  4. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. Foreign keys do not automatically create an index, clustered or non-clustered. You can manually create an index on a foreign key.

Text-align class for inside a table

You can use this CSS below:

.text-right {text-align: right} /* For right align */
.text-left {text-align: left} /* For left align */
.text-center {text-align: center} /* For center align */

Get value of c# dynamic property via string

To get properties from dynamic doc when .GetType() returns null, try this:

var keyValuePairs = ((System.Collections.Generic.IDictionary<string, object>)doc);
var val = keyValuePairs["propertyName"].ToObject<YourModel>;

How to get URL parameter using jQuery or plain JavaScript?

_x000D_
_x000D_
var RequestQuerystring;_x000D_
(window.onpopstate = function () {_x000D_
    var match,_x000D_
        pl = /\+/g,  // Regex for replacing addition symbol with a space_x000D_
        search = /([^&=]+)=?([^&]*)/g,_x000D_
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },_x000D_
        query = window.location.search.substring(1);_x000D_
_x000D_
    RequestQuerystring = {};_x000D_
    while (match = search.exec(query))_x000D_
        RequestQuerystring[decode(match[1])] = decode(match[2]);_x000D_
})();
_x000D_
_x000D_
_x000D_

RequestQuerystring is now an object with all you parameters

SQL query question: SELECT ... NOT IN

SELECT Reservations.idCustomer FROM Reservations (nolock)
LEFT OUTER JOIN @reservations ExcludedReservations (nolock) ON Reservations.idCustomer=ExcludedReservations.idCustomer AND DATEPART(hour, ExcludedReservations.insertDate) < 2
WHERE ExcludedReservations.idCustomer IS NULL AND Reservations.idCustomer IS NOT NULL
GROUP BY Reservations.idCustomer

[Update: Added additional criteria to handle idCustomer being NULL, which was apparently the main issue the original poster had]

Installing Homebrew on OS X

On an out of the box MacOS High Sierra 10.13.6

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Gives the following error:

curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option.

If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL).

If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option.

HTTPS-proxy has similar options --proxy-cacert and --proxy-insecure.

Solution: Just add a k to your Curl Options

$ ruby -e "$(curl -fsSLk https://raw.githubusercontent.com/Homebrew/install/master/install)"

Unordered List (<ul>) default indent

I found the following removed the indent and the margin from both the left AND right sides, but allowed the bullets to remain left-justified below the text above it. Add this to your css file:

ul.noindent {
    margin-left: 5px;
    margin-right: 0px;
    padding-left: 10px;
    padding-right: 0px;
}

To use it in your html file add class="noindent" to the UL tag. I've tested w/FF 14 and IE 9.

I have no idea why browsers default to the indents, but I haven't really had a reason for changing them that often.

Get keys of a Typescript interface as array of strings

The following requires you to list the keys on your own, but at least TypeScript will enforce IUserProfile and IUserProfileKeys have the exact same keys (Required<T> was added in TypeScript 2.8):

export interface IUserProfile  {
  id: string;
  name: string;
};
type KeysEnum<T> = { [P in keyof Required<T>]: true };
const IUserProfileKeys: KeysEnum<IUserProfile> = {
  id: true,
  name: true,
};

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I used String encodedUrl = new URI(null, url, null).toASCIIString(); to encode urls. To add parameters after the existing ones in the url I use UriComponentsBuilder

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

PHP str_replace replace spaces with underscores

I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green).

$journalName = preg_replace('/\s+/', '_', $journalName);

instead of:

$journalName = str_replace(' ', '_', $journalName);

Functional programming vs Object Oriented programming

  1. If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.

  2. In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

From MSDN:

The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.

There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:

  1. Stop the WPF Font Cache 4.0 service.
  2. Delete all of the WPFFontCache_v0400* files. In Windows XP, you'll find them in your C:\Documents and Settings\LocalService\Local Settings\Application Data\ folder.
  3. Start the service again.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

When you establish a connection for a transaction, you acquire a lock before performing the transaction. If not able to acquire the lock, then you try for sometime. If lock is still not obtainable, then lock wait time exceeded error is thrown. Why you will not able to acquire a lock is that you are not closing the connection. So, when you are trying to get a lock second time, you will not be able to acquire the lock as your previous connection is still unclosed and holding the lock.

Solution: close the connection or setAutoCommit(true) (according to your design) to release the lock.

How to make a background 20% transparent on Android

Try this code :)

Its an fully transparent hex code - "#00000000"

Java URLConnection Timeout

You can manually force disconnection by a Thread sleep. This is an example:

URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();

then

public class InterruptThread implements Runnable {

    HttpURLConnection con;
    public InterruptThread(HttpURLConnection con) {
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
        } catch (InterruptedException e) {

        }
        con.disconnect();
        System.out.println("Timer thread forcing to quit connection");
    }
}

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

Finding non-numeric rows in dataframe in pandas?

Already some great answers to this question, however here is a nice snippet that I use regularly to drop rows if they have non-numeric values on some columns:

# Eliminate invalid data from dataframe (see Example below for more context)

num_df = (df.drop(data_columns, axis=1)
         .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

num_df = num_df[num_df[data_columns].notnull().all(axis=1)]

The way this works is we first drop all the data_columns from the df, and then use a join to put them back in after passing them through pd.to_numeric (with option 'coerce', such that all non-numeric entries are converted to NaN). The result is saved to num_df.

On the second line we use a filter that keeps only rows where all values are not null.

Note that pd.to_numeric is coercing to NaN everything that cannot be converted to a numeric value, so strings that represent numeric values will not be removed. For example '1.25' will be recognized as the numeric value 1.25.

Disclaimer: pd.to_numeric was introduced in pandas version 0.17.0

Example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"item": ["a", "b", "c", "d", "e"],
   ...:                    "a": [1,2,3,"bad",5],
   ...:                    "b":[0.1,0.2,0.3,0.4,0.5]})

In [3]: df
Out[3]: 
     a    b item
0    1  0.1    a
1    2  0.2    b
2    3  0.3    c
3  bad  0.4    d
4    5  0.5    e

In [4]: data_columns = ['a', 'b']

In [5]: num_df = (df
   ...:           .drop(data_columns, axis=1)
   ...:           .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

In [6]: num_df
Out[6]: 
  item   a    b
0    a   1  0.1
1    b   2  0.2
2    c   3  0.3
3    d NaN  0.4
4    e   5  0.5

In [7]: num_df[num_df[data_columns].notnull().all(axis=1)]
Out[7]: 
  item  a    b
0    a  1  0.1
1    b  2  0.2
2    c  3  0.3
4    e  5  0.5

Replace duplicate spaces with a single space in T-SQL

This is the solution via multiple replace, which works for any strings (does not need special characters, which are not part of the string).

declare @value varchar(max)
declare @result varchar(max)
set @value = 'alpha   beta gamma  delta       xyz'

set @result = replace(replace(replace(replace(replace(replace(replace(
  @value,'a','ac'),'x','ab'),'  ',' x'),'x ',''),'x',''),'ab','x'),'ac','a')

select @result -- 'alpha beta gamma delta xyz'

How to show two figures using matplotlib?

I had this same problem.


Did:

f1 = plt.figure(1)

# code for figure 1

# don't write 'plt.show()' here


f2 = plt.figure(2)

# code for figure 2

plt.show()


Write 'plt.show()' only once, after the last figure. Worked for me.

Laravel 5 Clear Views Cache

To answer your additional question how disable views caching:

You can do this by automatically delete the files in the folder for each request with the command php artisan view:clear mentioned by DilipGurung. Here is an example Middleware class from https://stackoverflow.com/a/38598434/2311074

<?php
namespace App\Http\Middleware;

use Artisan;
use Closure;

class ClearViewCache
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (env('APP_DEBUG') || env('APP_ENV') === 'local') 
            Artisan::call('view:clear');

        return $next($request);
    }
}

However you may note that Larevel will recompile the files in the /app/storage/views folder whenever the time on the views files is earlier than the time on the PHP blade files for the layout. THus, I cannot really think of a scenario where this would be necessary to do.

How to push a single file in a subdirectory to Github (not master)

It will only push the new commits. It won't push the whole "master" branch. That is part of the benefit of working with a Distributed Version Control System. Git figures out what is actually needed and only pushes those pieces. If the branch you are on has been changed and pushed by someone else you'll need to pull first. Then push your commits.

Difference between staticmethod and classmethod

Here is a short article on this question

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).

Do we have router.reload in vue-router?

this.$router.go(this.$router.currentRoute)

Vue-Router Docs:

I checked vue-router repo on GitHub and it seems that there isn't reload() method any more. But in the same file, there is: currentRoute object.

Source: vue-router/src/index.js
Docs: docs

get currentRoute (): ?Route {
    return this.history && this.history.current
  }

Now you can use this.$router.go(this.$router.currentRoute) for reload current route.

Simple example.

Version for this answer:

"vue": "^2.1.0",
"vue-router": "^2.1.1"

Callback functions in Java

Create an Interface, and Create the Same Interface Property in Callback Class.

interface dataFetchDelegate {
    void didFetchdata(String data);
}
//callback class
public class BackendManager{
   public dataFetchDelegate Delegate;

   public void getData() {
       //Do something, Http calls/ Any other work
       Delegate.didFetchdata("this is callbackdata");
   }

}

Now in the class where you want to get called back implement the above Created Interface. and Also Pass "this" Object/Reference of your class to be called back.

public class Main implements dataFetchDelegate
{       
    public static void main( String[] args )
    {
        new Main().getDatafromBackend();
    }

    public void getDatafromBackend() {
        BackendManager inc = new BackendManager();
        //Pass this object as reference.in this Scenario this is Main Object            
        inc.Delegate = this;
        //make call
        inc.getData();
    }

    //This method is called after task/Code Completion
    public void didFetchdata(String callbackData) {
        // TODO Auto-generated method stub
        System.out.println(callbackData);
    }
}

Best method to download image from url in Android

Try to use this:

public Bitmap getBitmapFromURL(String src) {
    try {
        java.net.URL url = new java.net.URL(src);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

And for OutOfMemory issue:

 public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);

    // "RECREATE" THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
            matrix, false);

    return resizedBitmap;
}

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

How to insert DECIMAL into MySQL database

I noticed something else about your coding.... look

INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')

in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be

'0',

you put

0,

lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)

UPDATE.....

I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol

ExecJS and could not find a JavaScript runtime

I had this same error but only on my staging server not my production environment. nodejs was already installed on both environments.

By typing:

which node

I found out that the node command was located in: /usr/bin/node on production but: /usr/local/bin/node in staging.

After creating a symlink on staging i.e. :

sudo ln -s /usr/local/bin/node /usr/bin/node

the application then worked in staging.

No muss no fuss.

how to make a whole row in a table clickable as a link?

You could include an anchor inside every <td>, like so:

<tr>
  <td><a href="#">Blah Blah</a></td>
  <td><a href="#">1234567</a></td>
  <td><a href="#">more text</a></td>
</tr>

You could then use display:block; on the anchors to make the full row clickable.

tr:hover { 
   background: red; 
}
td a { 
   display: block; 
   border: 1px solid black;
   padding: 16px; 
}

Example jsFiddle here.

This is probably about as optimum as you're going to get it unless you resort to JavaScript.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

Spring Rest POST Json RequestBody Content type not supported

It looks an old thread, but in case someone still struggles, I have solved as Thibaut said it,

Avoid having two setter POJO class, I had two-setters for a specific property , The first one was in the regular setter and another one in under constructor after I removed the one in the constructor it worked.

Hive External Table Skip First Row

create external table table_name( 
Year int, 
Month int,
column_name data_type ) 
row format delimited fields terminated by ',' 
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

Today`s date in an excel macro

Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

Javascript - remove an array item by value

var id_tag = [1,2,3,78,5,6,7,8,47,34,90]; 
var delete_where_id_tag = 90
    id_tag =id_tag.filter((x)=> x!=delete_where_id_tag); 

Use of PUT vs PATCH methods in REST API real life scenarios

One additional information I just one to add is that a PATCH request use less bandwidth compared to a PUT request since just a part of the data is sent not the whole entity. So just use a PATCH request for updates of specific records like (1-3 records) while PUT request for updating a larger amount of data. That is it, don't think too much or worry about it too much.

static linking only some libraries

Some loaders (linkers) provide switches for turning dynamic loading on and off. If GCC is running on such a system (Solaris - and possibly others), then you can use the relevant option.

If you know which libraries you want to link statically, you can simply specify the static library file in the link line - by full path.

python getoutput() equivalent in subprocess

Use subprocess.Popen:

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

Why does visual studio 2012 not find my tests?

I hit the same problem while trying to open the solution on a network share in VS2013 Ultimate.

I corrected the problem by turning on

Control Panel -> Internet Options -> "Security" Tab -> Click "Local intranet", click on sites and make sure "Automatically detect intranet network" is ticked.

Phone number formatting an EditText in Android

Follow the instructions in this Answer to format the EditText mask.

https://stackoverflow.com/a/34907607/1013929

And after that, you can catch the original numbers from the masked string with:

String phoneNumbers = maskedString.replaceAll("[^\\d]", "");

Select a date from date picker using Selenium webdriver

Here's a tidy solution where you provide the target date as a Calendar object.

// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
    MONTH_TO_CALENDAR_INDEX.put("January",  0);
    MONTH_TO_CALENDAR_INDEX.put("February",1);
    MONTH_TO_CALENDAR_INDEX.put("March",2);
    MONTH_TO_CALENDAR_INDEX.put("April",3);
    MONTH_TO_CALENDAR_INDEX.put("May",4);
    MONTH_TO_CALENDAR_INDEX.put("June",5);
    MONTH_TO_CALENDAR_INDEX.put("July",6);
    MONTH_TO_CALENDAR_INDEX.put("August",7);
    MONTH_TO_CALENDAR_INDEX.put("September",8);
    MONTH_TO_CALENDAR_INDEX.put("October",9);
    MONTH_TO_CALENDAR_INDEX.put("November",10);
    MONTH_TO_CALENDAR_INDEX.put("December",11);
}

        // ====================================================================================================
        // setCalendarPicker
        // ====================================================================================================

        /**
         * Sets the value of specified web element while assuming the element is a JQuery calendar.
         * @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
         * @param byPicker The By phrase that locates the JQuery calendar.
         * @param targetDate The target date that you want set.
         * @throws AssertionError if the method is unable to set the date.
         */

        public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {

            // Open the JQuery calendar.
            WebElement opener = driver.findElement(byOpen);
            opener.click();

            // Locate the JQuery calendar.
            WebElement picker = driver.findElement(byPicker);

            // Calculate the target and current year-and-month as an integer where value = year*12+month.
            // The difference between the two is the number of months we have to move ahead or backward.
            int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
            int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
                    + Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
            // Calculate the number of months we need to move the JQuery calendar.
            int delta = targetYearMonth - currentYearMonth;
            // As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
            if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");

            // Push the JQuery calendar forward or backward as appropriate.
            if (delta > 0) {
                while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
            } else if (delta < 0 ){
                while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
            }

            // Select the day within the month.
            String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
            WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
            for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
                if (dayOfMonth.equals(we.getText())) {
                    we.click();

                    // Send a tab to completely leave this control.  If the next control the user will access is another CalendarPicker,
                    // the picker might not get selected properly if we stay on the current control.
                    opener.sendKeys("\t");

                    return;
                }
            }

            throw new AssertionError(String.format("Unable to select specified day"));
        }

Scroll to bottom of div?

Javascript or jquery:

var scroll = document.getElementById('messages');
   scroll.scrollTop = scroll.scrollHeight;
   scroll.animate({scrollTop: scroll.scrollHeight});

Css:

 .messages
 {
      height: 100%;
      overflow: auto;
  }

How to sort a List<Object> alphabetically using Object name field

something like

  List<FancyObject> theList = … ;
  Collections.sort (theList,
                    new Comparator<FancyObject> ()
                    { int compare (final FancyObject a, final FancyObject d)
                          { return (a.getName().compareTo(d.getName())); }});

Batchfile to create backup and rename with timestamp

See if this is what you want to do:

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%

set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%

copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});