Programs & Examples On #Acts as nested set

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

What is the difference between Jupyter Notebook and JupyterLab?

At this time (mid 2019), with JupyterLab 1.0 release, as a user, I think we should adopt JupyterLab for daily use. And from the JupyterLab official documentation:

The current release of JupyterLab is suitable for general daily use.

and

JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab.


Note that JupyterLab has a extensible modular architecture. So in the old days, there is just one Jupyter Notebook, and now with JupyterLab (and in the future), Notebook is just one of the core applications in JupyterLab (along with others like code Console, command-line Terminal, and a Text Editor).

How to delete all files and folders in a folder by cmd call

No, I don't know one.

If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

del /q destination\*
for /d %x in (destination\*) do @rd /s /q "%x"

This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

Note that within a batch file you need to double the % within the for loop:

del /q destination\*
for /d %%x in (destination\*) do @rd /s /q "%%x"

Multiple HttpPost method in Web API controller

Put Route Prefix [RoutePrefix("api/Profiles")] at the controller level and put a route at action method [Route("LikeProfile")]. Don't need to change anything in global.asax file

namespace KhandalVipra.Controllers
{
    [RoutePrefix("api/Profiles")]
    public class ProfilesController : ApiController
    {
        // POST: api/Profiles/LikeProfile
        [Authorize]
        [HttpPost]
        [Route("LikeProfile")]
        [ResponseType(typeof(List<Like>))]
        public async Task<IHttpActionResult> LikeProfile()
        {
        }
    }
}

Comparing strings in Java

[EDIT] I made a mistake earlier, because, to get the text, you need to use .getText().toString().

Here is a full working example:

package com.psegina.passwordTest01;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener {
    LinearLayout l;
    EditText user;
    EditText pwd;
    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        l = new LinearLayout(this);
        user = new EditText(this);
        pwd = new EditText(this);
        btn = new Button(this);

        l.addView(user);
        l.addView(pwd);
        l.addView(btn);
        btn.setOnClickListener(this);

        setContentView(l);
    }

    public void onClick(View v){
        String u = user.getText().toString();
        String p = pwd.getText().toString();
        if( u.equals( p ) )
            Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show();
    }
}

Original answer (Will not work because of the lack of toString())

Try using .getText() instead of .toString().

if( passw1.getText() == passw2.getText() )
#do something

.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())

How to Auto-start an Android Application?

I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).

Add the permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Add receiver and service:

<receiver android:enabled="true" android:name=".BootUpReceiver"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>
<service android:name="Launcher" />

Create class Launcher:

public class Launcher extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new AsyncTask<Service, Void, Service>() {

            @Override
            protected Service doInBackground(Service... params) {
                Service service = params[0];
                PackageManager pm = service.getPackageManager();
                try {
                    Intent target = pm.getLaunchIntentForPackage("your.package.id");
                    if (target != null) {
                        service.startActivity(target);
                        synchronized (this) {
                            wait(3000);
                        }
                    } else {
                        throw new ActivityNotFoundException();
                    }
                } catch (ActivityNotFoundException | InterruptedException ignored) {
                }
                return service;
            }

            @Override
            protected void onPostExecute(Service service) {
                service.stopSelf();
            }

        }.execute(this);

        return START_STICKY;
    }
}

Create class BootUpReceiver to do action after android reboot.

For example launch MainActivity:

public class BootUpReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent target = new Intent(context, MainActivity.class);  
        target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(target);  
    }
}

How to do SELECT MAX in Django?

I've tested this for my project, it finds the max/min in O(n) time:

from django.db.models import Max

# Find the maximum value of the rating and then get the record with that rating. 
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)

This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

JavaScript - Replace all commas in a string

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

How to clear File Input

In my case other solutions did not work than this way:

$('.bootstrap-filestyle :input').val('');

However, if you will have more than 1 file input on page, it will reset the text on all of them.

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

Assign value from successful promise resolve to external variable

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

getFeed().then(function(data) { vm.feed = data;});

The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1

Can I use CASE statement in a JOIN condition?

Took DonkeyKong's example.

The issue is I needed to use a declared variable. This allows for stating your left and right-hand side of what you need to compare. This is for supporting an SSRS report where different fields must be linked based on the selection by the user.

The initial case sets the field choice based on the selection and then I can set the field I need to match on for the join.

A second case statement could be added for the right-hand side if the variable is needed to choose from different fields

LEFT OUTER JOIN Dashboard_Group_Level_Matching ON
       case
         when @Level  = 'lvl1' then  cw.Lvl1
         when @Level  = 'lvl2' then  cw.Lvl2
         when @Level  = 'lvl3' then  cw.Lvl3
       end
    = Dashboard_Group_Level_Matching.Dashboard_Level_Name

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Linq order by, group by and order by each group?

Alternatively you can do like this :

     var _items = from a in StudentsGrades
                  group a by a.Name;

     foreach (var _itemGroup in _items)
     {
        foreach (var _item in _itemGroup.OrderBy(a=>a.grade))
        {
           ------------------------
           --------------------------
        }
     }

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

Callback functions in Java

When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.

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).

How to get city name from latitude and longitude coordinates in Google Maps?

You can use this if you have a list:

Address address = list.get(0);
String cityname = address.getLocality();

git rebase merge conflict

If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".

First, checkout temp branch and start standard merge

git checkout -b temp
git merge origin/master

You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.

git commit -m "Merge branch 'origin/master' into 'temp'"

Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.

git checkout alpha
git rebase origin/master -X theirs

Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.

git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)

And delete temporary branch

git branch -D temp

That's all. We did a rebase via hidden merge.

Also I wrote a script, so that can be done in a dialog manner, you can find it here.

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

How to get only time from date-time C#

There is only DateTime type in C# and it consist of both the date and time portion. If you don't care about the Date portion of DateTime, set it to default value like this:

DateTime myTime = default(DateTime).Add(myDateTime.TimeOfDay)

This way you can be consistent across all versions of .NET, even if Microsoft decides to change the base date to something else than 1/1/0001.

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using Spring boot and have this issue with the OffsetDateTime then need to use the registerModules as answered above by @greperror(answered May 28 '16 at 13:04) but note that there is one difference. The dependency mentioned doesn't need to be added as I am guessing that spring boot has it already. I was having this issue with Spring boot and it worked for me without adding this dependency.

Setting public class variables

If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.

It doesn't make sense to keep the property public with all those things added to the class.

Trying to embed newline in a variable in bash

There are three levels at which a newline could be inserted in a variable.
Well ..., technically four, but the first two are just two ways to write the newline in code.

1.1. At creation.

The most basic is to create the variable with the newlines already.
We write the variable value in code with the newlines already inserted.

$ var="a
> b
> c"
$ echo "$var"
a
b
c

Or, inside an script code:

var="a
b
c"

Yes, that means writing Enter where needed in the code.

1.2. Create using shell quoting.

The sequence $' is an special shell expansion in bash and zsh.

var=$'a\nb\nc'

The line is parsed by the shell and expanded to « var="anewlinebnewlinec" », which is exactly what we want the variable var to be.
That will not work on older shells.

2. Using shell expansions.

It is basically a command expansion with several commands:

  1. echo -e

    var="$( echo -e "a\nb\nc" )"
    
  2. The bash and zsh printf '%b'

    var="$( printf '%b' "a\nb\nc" )"
    
  3. The bash printf -v

    printf -v var '%b' "a\nb\nc"
    
  4. Plain simple printf (works on most shells):

    var="$( printf 'a\nb\nc' )"
    

3. Using shell execution.

All the commands listed in the second option could be used to expand the value of a var, if that var contains special characters.
So, all we need to do is get those values inside the var and execute some command to show:

var="a\nb\nc"                 # var will contain the characters \n not a newline.

echo -e "$var"                # use echo.
printf "%b" "$var"            # use bash %b in printf.
printf "$var"                 # use plain printf.

Note that printf is somewhat unsafe if var value is controlled by an attacker.

Sorting a DropDownList? - C#, ASP.NET

If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...

DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";

ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();

Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.

How to get a Char from an ASCII Character Code in c#

It is important to notice that in C# the char type is stored as Unicode UTF-16.

From ASCII equivalent integer to char

char c = (char)88;

or

char c = Convert.ToChar(88)

From char to ASCII equivalent integer

int asciiCode = (int)'A';

The literal must be ASCII equivalent. For example:

string str = "X?????????";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);

will print

X
3626

Extended ASCII ranges from 0 to 255.

From default UTF-16 literal to char

Using the Symbol

char c = 'X';

Using the Unicode code

char c = '\u0058';

Using the Hexadecimal

char c = '\x0058';

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

good postgresql client for windows?

For anyone looking for a web-enabled client for Postgres, I'll just put the link out here to TeamPostgreSQL, a very polished AJAX web client for pg:

http://www.teampostgresql.com

Set transparent background of an imageview on Android

If you use a drawable XML image you can make it transparent as shown in the picture below, or you can use a color code:

<color name="black">#99000000</color> 

Enter image description here

Text size of android design TabLayout tabs

Go on using tabTextAppearance as you did but

1) to fix the capital letter side effect add textAllCap in your style :

<style name="MyTabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
    <item name="android:textSize">14sp</item>
    <item name="android:textAllCaps">true</item>
</style>

2) to fix the selected tab color side effect add in TabLayout xml the following library attributes :

app:tabSelectedTextColor="@color/color1"
app:tabTextColor="@color/color2" 

Hope this helps.

Insert variable into Header Location PHP

We can also use this with the $_GET method

$employee_id = 'EMP-1234';

header('Location: employee.php?id='.$employee_id);

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

I try this. I hope to help. It work with

static void Main()
    {
        string[,] matrix = {
                               { "aa", "aaa" },
                               { "bb", "bbb" }
                           };
        int index = 0;
        foreach (string element in matrix)
        {
            if (index < matrix.GetLength(1))
            {
                Console.Write(element);
                if (index < (matrix.GetLength(1) - 1))
                {
                    Console.Write(" ");
                }
                index++;
            }
            if (index == matrix.GetLength(1))
            {
                Console.Write("\n");
                index = 0;
            }
        }

PHP PDO returning single row

Did you try:

$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;

What is "406-Not Acceptable Response" in HTTP?

Your operation did not fail.

Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.

Ref: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

  1. Find out the response (content type) returned by Service.
  2. Provide this (content type) in your request Accept header.

http://en.wikipedia.org/wiki/HTTP_status_code -> 406

Generate random string/characters in JavaScript

I have made a String prototype which can generate a random String with a given length.

You also can secify if you want special chars and you can avoid some.

/**
 * STRING PROTOTYPE RANDOM GENERATOR
 * Used to generate a random string
 * @param {Boolean} specialChars
 * @param {Number} length
 * @param {String} avoidChars
 */
String.prototype.randomGenerator = function (specialChars = false, length = 1, avoidChars = '') {
    let _pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    _pattern += specialChars === true ? '(){}[]+-*/=' : '';
    if (avoidChars && avoidChars.length) {
        for (let char of avoidChars) {
            _pattern = _pattern.replace(char, '');
        }
    }
    let _random = '';
    for (let element of new Array(parseInt(length))) {
        _random += _pattern.charAt(Math.floor(Math.random() * _pattern.length));
    }
    return _random;
};

You can use like this :

// Generate password with specialChars which contains 10 chars and avoid iIlL chars
var password = String().randomGenerator(true, 10, 'iIlL');

Hope it helps.

How to retrieve the current version of a MySQL database management system (DBMS)?

Many answers suggest to use mysql --version. But the mysql programm is the client. The server is mysqld. So the command should be

mysqld --version

or

mysqld --help

That works for me on Debian and Windows.

When connected to a MySQL server with a client you can use

select version()

or

select @@version

Bash script plugin for Eclipse?

ShellEd is a good plugin for Eclipse.

This link helped me to install it: http://mattnorris.me/blog/install-eclipse-shelled-plugin/

Steps:

  1. Download ShellEd: http://sourceforge.net/projects/shelled/files/latest/download - The file is a zipped archive named something like net.sourceforge.shelled-site-2.0.x.zip.

  2. Then click Help > Install New Software...

  3. Click Add... in the upper right.
  4. Click Archive...
  5. Navigate to where you saved the zipped archive net.sourceforge.shelled-site-2.0.x.zip and select it.
  6. Click OK. (Don't worry about the optional Name field. Eclipse will name it automatically.)
  7. Select the new Shell Script checkbox.
  8. Click Next.
  9. Click Next again.
  10. Select "I accept the terms of the license agreement."
  11. Click Finish.
  12. Restart Eclipse.

How to change the button text of <input type="file" />?

In Bootstrap +4.5 you can simply add bellow style to your code:

<style>
    .custom-file-input ~ .custom-file-label::after {
        content: "Your custom text ...";
    }
</style>

and your input:

<div class="custom-file">
    <input type="file" class="custom-file-input">
    <label class="custom-file-label">Your custom placeholder ...</label>
</div>

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

http://search.cpan.org/dist/B-C/perlcompile.pod

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.

How to get rid of punctuation using NLTK tokenizer?

Sincerely asking, what is a word? If your assumption is that a word consists of alphabetic characters only, you are wrong since words such as can't will be destroyed into pieces (such as can and t) if you remove punctuation before tokenisation, which is very likely to affect your program negatively.

Hence the solution is to tokenise and then remove punctuation tokens.

import string

from nltk.tokenize import word_tokenize

tokens = word_tokenize("I'm a southern salesman.")
# ['I', "'m", 'a', 'southern', 'salesman', '.']

tokens = list(filter(lambda token: token not in string.punctuation, tokens))
# ['I', "'m", 'a', 'southern', 'salesman']

...and then if you wish, you can replace certain tokens such as 'm with am.

How to connect PHP with Microsoft Access database

The problem is a simple typo. You named your variable 'conc' on line 2 but then referenced 'conn' on line 4.

How to embed an autoplaying YouTube video in an iframe?

2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip

rel=0&amp;autoplay 

Example Below: .

<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

Differences between Emacs and Vim

VI is always available and will run on the most crippled, single user mode, broken graphics, no keymap, slow link machine - so it's worth knowing how to edit simple files in it just for sysadmin tasks.

Emacs is a complete user interface in an editor. The idea is that you fire up Emacs when you start the machine and never leave it. It's possible to have thousands of sessions present.

Whether learning the capabilities of Emacs are worth it compared to using a GUI editor/IDE and using something like python/awk/etc for extra tasks is up to you.

Superscript in markdown (Github flavored)?

Use the <sup></sup>tag (<sub></sub> is the equivalent for subscripts). See this gist for an example.

What is the proper way to URL encode Unicode characters?

The general rule seems to be that browsers encode form responses according to the content-type of the page the form was served from. This is a guess that if the server sends us "text/xml; charset=iso-8859-1", then they expect responses back in the same format.

If you're just entering a URL in the URL bar, then the browser doesn't have a base page to work on and therefore just has to guess. So in this case it seems to be doing utf-8 all the time (since both your inputs produced three-octet form values).

The sad truth is that AFAIK there's no standard for what character set the values in a query string, or indeed any characters in the URL, should be interpreted as. At least in the case of values in the query string, there's no reason to suppose that they necessarily do correspond to characters.

It's a known problem that you have to tell your server framework which character set you expect the query string to be encoded as--- for instance, in Tomcat, you have to call request.setEncoding() (or some similar method) before you call any of the request.getParameter() methods. The dearth of documentation on this subject probably reflects the lack of awareness of the problem amongst many developers. (I regularly ask Java interviewees what the difference between a Reader and an InputStream is, and regularly get blank looks)

Finding square root without using sqrt function?

There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:

#include <math.h>

double sqrt(double x) {
    if (x <= 0)
        return 0;       // if negative number throw an exception?
    int exp = 0;
    x = frexp(x, &exp); // extract binary exponent from x
    if (exp & 1) {      // we want exponent to be even
        exp--;
        x *= 2;
    }
    double y = (1+x)/2; // first approximation
    double z = 0;
    while (y != z) {    // yes, we CAN compare doubles here!
        z = y;
        y = (y + x/y) / 2;
    }
    return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}

Algorithm starts with 1 as first approximation for square root value. Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.

UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().

c# open a new form then close the current form?

use this code snippet in your form1.

public static void ThreadProc()
{
Application.Run(new Form());
}

private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}

I got this from here

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

Shortcut to open file in Vim

If you're editing files in a common directory, you can :cd to that directory, then use :e on just the filename.

For example, rather than:

:e /big/long/path/that/takes/a/while/to/type/or/tab/complete/thingy.rb
:sp /big/long/path/that/takes/a/while/to/type/or/tab/complete/other_thingy.c
:vs /big/long/path/that/takes/a/while/to/type/or/tab/complete/one_more_thingy.java

You can do:

:cd /big/long/path/that/takes/a/while/to/type/or/tab/complete/
:e thingy.rb
:sp other_thingy.c
:vs one_more_thingy.java

Or, if you already have a file in the desired directory open, you can use the % shorthand for the current filename, and trim it to the current directory with the :h modifier (:help :_%:) :

:e /big/long/path/that/takes/a/while/to/type/or/tab/complete/thingy.rb
:cd %:h
:sp other_thingy.c
:vs one_more_thingy.java

And, like others have said, you can tab-complete file names on the ex-line (see :help cmdline-completion for more).

How to "log in" to a website using Python's Requests module?

If the information you want is on the page you are directed to immediately after login...

Lets call your ck variable payload instead, like in the python-requests docs:

payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)

Otherwise...

See https://stackoverflow.com/a/17633072/111362 below.

how to create inline style with :before and :after

I resolved a similar problem by border-color: inherit

, see:

<li style="border-color: <?php echo $hex ?>;">...</li>

li {
    border-width: 0;
}

li:before {
    content: '';
    display: inline-block;
    float: none;
    margin-right: 10px;
    border-width: 4px;
    border-style: solid;
    border-color: inherit;
}

Setting Short Value Java

There is no such thing as a byte or short literal. You need to cast to short using (short)100

summing two columns in a pandas dataframe

You could also use the .add() function:

 df.loc[:,'variance'] = df.loc[:,'budget'].add(df.loc[:,'actual'])

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

Since I got an instance which isn't null and if I compared to DBNULL I got Operator '==' cannot be applied to operands of type 'string' and 'system.dbnull' exeption, and if I tried to change to compare to NULL, it simply didn't work ( since DBNull is an object) even that's the accepted answer.

I decided to simply use the 'is' keyword. So the result is very readable:

data = (item is DBNull) ? String.Empty : item

Double array initialization in Java

It is called an array initializer and can be explained in the Java specification 10.6.

This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.

Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

When should we use Observer and Observable?

Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

How to rearrange Pandas column sequence?

There may be an elegant built-in function (but I haven't found it yet). You could write one:

# reorder columns
def set_column_sequence(dataframe, seq, front=True):
    '''Takes a dataframe and a subsequence of its columns,
       returns dataframe with seq as first columns if "front" is True,
       and seq as last columns if "front" is False.
    '''
    cols = seq[:] # copy so we don't mutate seq
    for x in dataframe.columns:
        if x not in cols:
            if front: #we want "seq" to be in the front
                #so append current column to the end of the list
                cols.append(x)
            else:
                #we want "seq" to be last, so insert this
                #column in the front of the new column list
                #"cols" we are building:
                cols.insert(0, x)
return dataframe[cols]

For your example: set_column_sequence(df, ['x','y']) would return the desired output.

If you want the seq at the end of the DataFrame instead simply pass in "front=False".

Regular cast vs. static_cast vs. dynamic_cast

static_cast

static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:

void func(void *data) {
  // Conversion from MyClass* -> void* is implicit
  MyClass *c = static_cast<MyClass*>(data);
  ...
}

int main() {
  MyClass c;
  start_thread(&func, &c)  // func(&c) will be called
      .join();
}

In this example, you know that you passed a MyClass object, and thus there isn't any need for a runtime check to ensure this.

dynamic_cast

dynamic_cast is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case).

if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
  ...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
  ...
}

You cannot use dynamic_cast if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base doesn't contain any virtual function:

struct Base { };
struct Derived : Base { };
int main() {
  Derived d; Base *b = &d;
  dynamic_cast<Derived*>(b); // Invalid
}

An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion.

Regular Cast

These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe, because it does not use dynamic_cast.

In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that.

Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.

Regex to match URL end-of-line or "/" character

/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$

1st Capturing Group (.+)

.+ matches any character (except for line terminators)

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (\d{4}-\d{2}-\d{2})

\d{4} matches a digit (equal to [0-9])

  • {4} Quantifier — Matches exactly 4 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

3rd Capturing Group (\d+)

\d+ matches a digit (equal to [0-9])

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

4th Capturing Group (.*)?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

.* matches any character (except for line terminators)

  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string

Increasing the maximum number of TCP/IP connections in Linux

Maximum number of connections are impacted by certain limits on both client & server sides, albeit a little differently.

On the client side: Increase the ephermal port range, and decrease the tcp_fin_timeout

To find out the default values:

sysctl net.ipv4.ip_local_port_range
sysctl net.ipv4.tcp_fin_timeout

The ephermal port range defines the maximum number of outbound sockets a host can create from a particular I.P. address. The fin_timeout defines the minimum time these sockets will stay in TIME_WAIT state (unusable after being used once). Usual system defaults are:

  • net.ipv4.ip_local_port_range = 32768 61000
  • net.ipv4.tcp_fin_timeout = 60

This basically means your system cannot consistently guarantee more than (61000 - 32768) / 60 = 470 sockets per second. If you are not happy with that, you could begin with increasing the port_range. Setting the range to 15000 61000 is pretty common these days. You could further increase the availability by decreasing the fin_timeout. Suppose you do both, you should see over 1500 outbound connections per second, more readily.

To change the values:

sysctl net.ipv4.ip_local_port_range="15000 61000"
sysctl net.ipv4.tcp_fin_timeout=30

The above should not be interpreted as the factors impacting system capability for making outbound connections per second. But rather these factors affect system's ability to handle concurrent connections in a sustainable manner for large periods of "activity."

Default Sysctl values on a typical Linux box for tcp_tw_recycle & tcp_tw_reuse would be

net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0

These do not allow a connection from a "used" socket (in wait state) and force the sockets to last the complete time_wait cycle. I recommend setting:

sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1 

This allows fast cycling of sockets in time_wait state and re-using them. But before you do this change make sure that this does not conflict with the protocols that you would use for the application that needs these sockets. Make sure to read post "Coping with the TCP TIME-WAIT" from Vincent Bernat to understand the implications. The net.ipv4.tcp_tw_recycle option is quite problematic for public-facing servers as it won’t handle connections from two different computers behind the same NAT device, which is a problem hard to detect and waiting to bite you. Note that net.ipv4.tcp_tw_recycle has been removed from Linux 4.12.

On the Server Side: The net.core.somaxconn value has an important role. It limits the maximum number of requests queued to a listen socket. If you are sure of your server application's capability, bump it up from default 128 to something like 128 to 1024. Now you can take advantage of this increase by modifying the listen backlog variable in your application's listen call, to an equal or higher integer.

sysctl net.core.somaxconn=1024

txqueuelen parameter of your ethernet cards also have a role to play. Default values are 1000, so bump them up to 5000 or even more if your system can handle it.

ifconfig eth0 txqueuelen 5000
echo "/sbin/ifconfig eth0 txqueuelen 5000" >> /etc/rc.local

Similarly bump up the values for net.core.netdev_max_backlog and net.ipv4.tcp_max_syn_backlog. Their default values are 1000 and 1024 respectively.

sysctl net.core.netdev_max_backlog=2000
sysctl net.ipv4.tcp_max_syn_backlog=2048

Now remember to start both your client and server side applications by increasing the FD ulimts, in the shell.

Besides the above one more popular technique used by programmers is to reduce the number of tcp write calls. My own preference is to use a buffer wherein I push the data I wish to send to the client, and then at appropriate points I write out the buffered data into the actual socket. This technique allows me to use large data packets, reduce fragmentation, reduces my CPU utilization both in the user land and at kernel-level.

preferredStatusBarStyle isn't called

If someone run into this problem with UISearchController. Just create a new subclass of UISearchController, and then add code below into that class:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return .LightContent
}

How do I temporarily disable triggers in PostgreSQL?

Alternatively, if you are wanting to disable all triggers, not just those on the USER table, you can use:

SET session_replication_role = replica;

This disables triggers for the current session.

To re-enable for the same session:

SET session_replication_role = DEFAULT;

Source: http://koo.fi/blog/2013/01/08/disable-postgresql-triggers-temporarily/

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

Microsoft's Using sp_executesql article recommends using sp_executesql instead of execute statement.

Because this stored procedure supports parameter substitution, sp_executesql is more versatile than EXECUTE; and because sp_executesql generates execution plans that are more likely to be reused by SQL Server, sp_executesql is more efficient than EXECUTE.

So, the take away: Do not use execute statement. Use sp_executesql.

Show empty string when date field is 1/1/1900

An alternate solution that covers both min (1/1/1900) and max (6/6/2079) dates:

ISNULL(NULLIF(NULLIF(CONVERT(VARCHAR(10), CreatedDate, 120), '1900-01-01'), '2079-06-06'), '').

Whatever solution you use, you should do a conversion of your date (or datetime) field to a specific format to bulletproof against different default server configurations.

See CAST and CONVERT on MSDN: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Differences between Octave and MATLAB?

Nested functions and closures are now supported by many languages, including MATLAB. JavaScript promotes closures as a first class design principle.

Sadly, Octave does not support closures (nested functions with lexical scoping).

According http://osdir.com/ml/octave-bug-tracker/2013-06/msg00210.html one might even get the impression that the developers do not want or are unable to get it right.

This will break a lot of code, both ways. No workaround.

How to iterate std::set?

How do you iterate std::set?

int main(int argc,char *argv[]) 
{
    std::set<int> mset;
    mset.insert(1); 
    mset.insert(2);
    mset.insert(3);

    for ( auto it = mset.begin(); it != mset.end(); it++ )
        std::cout << *it;
}

What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

Pygame mouse clicking detection

I assume your game has a main loop, and all your sprites are in a list called sprites.

In your main loop, get all events, and check for the MOUSEBUTTONDOWN or MOUSEBUTTONUP event.

while ... # your main loop
  # get all events
  ev = pygame.event.get()

  # proceed events
  for event in ev:

    # handle MOUSEBUTTONUP
    if event.type == pygame.MOUSEBUTTONUP:
      pos = pygame.mouse.get_pos()

      # get a list of all sprites that are under the mouse cursor
      clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
      # do something with the clicked sprites...

So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().

Pygame does not offer event driven programming, as e.g. cocos2d does.

Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.

if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
  print ("You have opened a chest!")

You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.

handled = False

while ... // your loop

  if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
    print ("You have opened a chest!")
    handled = pygame.mouse.get_pressed()[0]

Of course you can subclass Sprite and add a method called is_clicked like this:

class MySprite(Sprite):
  ...

  def is_clicked(self):
    return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())

So, it's better to use the first approach IMHO.

How can I stop .gitignore from appearing in the list of untracked files?

I think that there are situations where ignoring the .gitignore is very useful. For instance, when you have multiple teams or a large team working on the same codebase. In that case, you need to have certain conventions, one of those convention is regarding what is ignored at the git repo. It is usually about ignoring files and directories created by IDE or OS, some generated logs, etc.

However, there is a force which is tending to introduce non-conventional changes to .gitignore file. The .gitignore file can be further changed by irresponsible person, by mistake, by a tool that is used, or in some other case.

To have a counter force to this, we can do as followed:

  1. The initial .gitignore should reflect convention in team(s),
  2. After it is pushed, the .gitignore should be secured by adding .gitignore entry and push that change again.The .gitignore file is "sealed" in this way.

The "sealed" .gitignore file can be changed, just locally, without propagating that changers to other members of team(s). However, if a change is widely agreed throughout the whole team(s) than it is possible to "unseal" it, change it and than "seal" it again. That can't be done by mistake, only intentionally.

Sadly, you cannot be 100% protected from the stupidity, but this way you have done everything you can to prevent stupid things to happen.

If you have relatively small team with very good professionals, than this wouldn't be important, but even those guys would appreciate to have one thing less to worry about.

Using .git/info/exclude is cool when you cannot do anything about infrastructure settings, just covering your own a** not to make a mistake.

From a standing point of what is right and what is wrong I am voting for having .gitignore entry inside .gitignore file, giving everybody the freedom to do locally whatever they want, but not invading others.

How to change the text color of first select option

You can do this by using CSS: JSFiddle

HTML:

<select>
    <option>Text 1</option>
    <option>Text 2</option>
    <option>Text 3</option>
</select>

CSS:

select option:first-child { color:red; }

Or if you absolutely need to use JavaScript (not adviced for this): JSFiddle

JavaScript:

$(function() {
    $("select option:first-child").addClass("highlight");
});

CSS:

.highlight { color:red; }

Clearing my form inputs after submission

var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
 
btnClear.addEventListener('click', () => {
    inputs.forEach(input =>  input.value = '');
});

What is the maximum number of edges in a directed graph with n nodes?

There can be as many as n(n-1)/2 edges in the graph if not multi-edge is allowed.

And this is achievable if we label the vertices 1,2,...,n and there's an edge from i to j iff i>j.

See here.

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Java Regex to Validate Full Name allow only Spaces and Letters

@amal. This code will match your requirement. Only letter and space in between will be allow, no number. The text begin with any letter and could have space in between only. "^" denotes the beginning of the line and "$" denotes end of the line.

public static boolean validateLetters(String txt) {

    String regx = "^[a-zA-Z ]+$";
    Pattern pattern = Pattern.compile(regx,Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(txt);
    return matcher.find();

}

Separating class code into a header and cpp file

A2DD.h

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);

  int getSum();
};

A2DD.cpp

  A2DD::A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int A2DD::getSum()
  {
    return gx + gy;
  }

The idea is to keep all function signatures and members in the header file.
This will allow other project files to see how the class looks like without having to know the implementation.

And besides that, you can then include other header files in the implementation instead of the header. This is important because whichever headers are included in your header file will be included (inherited) in any other file that includes your header file.

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

How to get the date from jQuery UI datepicker

Try this, works like charm, gives the date you have selected. onsubmit form try to get this value:-

var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();

Reference here

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

I got the same error, and because I have 4 ssh-keys, so I tried follow:

ssh-keygen -t rsa
heroku keys:add

then, four options show:

1) github_rsa.pub
2) id_boot2docker.pub
3) id_rsa.pub
4) sshkey.pub

I choose 3), the newest one

Then, I fix the error.

how does Request.QueryString work?

The HttpRequest class represents the request made to the server and has various properties associated with it, such as QueryString.

The ASP.NET run-time parses a request to the server and populates this information for you.

Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.

Note: not all properties will be populated, for instance if your request has no query string, then the QueryString will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:

if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
    // Query string value is there so now use it
    int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}

Scala vs. Groovy vs. Clojure

I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.

It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.

php - insert a variable in an echo string

You can try this

$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i; 

React-router v4 this.props.history.push(...) not working

It seems things have changed around a bit in the latest version of react router. You can now access history via the context. this.context.history.push('/path')

Also see the replies to the this github issue: https://github.com/ReactTraining/react-router/issues/4059

JUNIT testing void methods

I think you should avoid writing side-effecting method. Return true or false from your method and you can check these methods in unit tests.

HTML 5 video or audio playlist

I created a JS fiddle for this here:

http://jsfiddle.net/Barzi/Jzs6B/9/

First, your HTML markup looks like this:

<video id="videoarea" controls="controls" poster="" src=""></video>

<ul id="playlist">
    <li movieurl="VideoURL1.webm" moviesposter="VideoPoster1.jpg">First video</li>
    <li movieurl="VideoURL2.webm">Second video</li>
    ...
    ...
</ul>

Second, your JavaScript code via JQuery library will look like this:

$(function() {
    $("#playlist li").on("click", function() {
        $("#videoarea").attr({
            "src": $(this).attr("movieurl"),
            "poster": "",
            "autoplay": "autoplay"
        })
    })
    $("#videoarea").attr({
        "src": $("#playlist li").eq(0).attr("movieurl"),
        "poster": $("#playlist li").eq(0).attr("moviesposter")
    })
})?

And last but not least, your CSS:

#playlist {
    display:table;
}
#playlist li{
    cursor:pointer;
    padding:8px;
}
#playlist li:hover{
    color:blue;                        
}
#videoarea {
    float:left;
    width:640px;
    height:480px;
    margin:10px;    
    border:1px solid silver;
}?

HTML / CSS How to add image icon to input type="button"?

This should do do what you want, assuming your button image is 16 by 16 pixels.

<input type="button" value="Add a new row" class="button-add" />
input.button-add {
    background-image: url(/images/buttons/add.png); /* 16px x 16px */
    background-color: transparent; /* make the button transparent */
    background-repeat: no-repeat;  /* make the background image appear only once */
    background-position: 0px 0px;  /* equivalent to 'top left' */
    border: none;           /* assuming we don't want any borders */
    cursor: pointer;        /* make the cursor like hovering over an <a> element */
    height: 16px;           /* make this the size of your image */
    padding-left: 16px;     /* make text start to the right of the image */
    vertical-align: middle; /* align the text vertically centered */
}

Example button:

example button

Update

If you happen to use Less, this mixin might come in handy.

.icon-button(@icon-url, @icon-size: 16px, @icon-inset: 10px, @border-color: #000, @background-color: transparent) {
    height: @icon-size * 2;
    padding-left: @icon-size + @icon-inset * 2;
    padding-right: @icon-inset;
    border: 1px solid @border-color;
    background: @background-color url(@icon-url) no-repeat @icon-inset center;
    cursor: pointer;
}

input.button-add {
    .icon-button("http://placehold.it/16x16", @background-color: #ff9900);
}

The above compiles into

input.button-add {
  height: 32px;
  padding-left: 36px;
  padding-right: 10px;
  border: 1px solid #000000;
  background: #ff9900 url("http://placehold.it/16x16") no-repeat 10px center;
  cursor: pointer;
}

JSFiddle

Crop image in android

This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.

You will crop your images with a few lines of code.

1 - Add the dependecies into buid.gradle (Module: app)

compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

2 - Add the permissions into AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

3 - Add CropImageActivity into AndroidManifest.xml

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
 android:theme="@style/Base.Theme.AppCompat"/>

4 - Start the activity with one of the cases below, depending on your requirements.

// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);

// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);

// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);

5 - Get the result in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.

How to dynamically build a JSON object with Python?

You can use EasyDict library (doc):

EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.

USEAGE

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1

>>> d = edict(foo=3)
>>> d.foo
3

[INSTALLATION]:

  • pip install easydict

Callback when CSS3 transition finishes

There is an animationend Event that can be observed see documentation here, also for css transition animations you could use the transitionend event

There is no need for additional libraries these all work with vanilla JS

_x000D_
_x000D_
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
 this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
_x000D_
_x000D_

HSL to RGB color conversion

With H, S,and L in [0,1] range:

ConvertHslToRgb: function (iHsl)
{
    var min, sv, sextant, fract, vsf;

    var v = (iHsl.l <= 0.5) ? (iHsl.l * (1 + iHsl.s)) : (iHsl.l + iHsl.s - iHsl.l * iHsl.s);
    if (v === 0)
        return { Red: 0, Green: 0, Blue: 0 };

    min = 2 * iHsl.l - v;
    sv = (v - min) / v;
    var h = (6 * iHsl.h) % 6;
    sextant = Math.floor(h);
    fract = h - sextant;
    vsf = v * sv * fract;

    switch (sextant)
    {
        case 0: return { r: v, g: min + vsf, b: min };
        case 1: return { r: v - vsf, g: v, b: min };
        case 2: return { r: min, g: v, b: min + vsf };
        case 3: return { r: min, g: v - vsf, b: v };
        case 4: return { r: min + vsf, g: min, b: v };
        case 5: return { r: v, g: min, b: v - vsf };
    }
}

Java Date cut off time information

Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

Returning a value from thread?

I'm no kind of expert in threading, that's why I did it like this:

I created a Settings file and

Inside the new thread:

Setting.Default.ValueToBeSaved;
Setting.Default.Save();

Then I pick up that value whenever I need it.

Extract and delete all .gz in a directory- Linux

Extract all gz files in current directory and its subdirectories:

 find . -name "*.gz" | xargs gunzip 

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

ip address validation in python using regex

Use anchors instead:

aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)

These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^ anchor because it's implicit in the .match() method).

Then, check if the regex did in fact match before trying to access its results:

if aa:
    ip = aa.group()

Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:

ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)

Here, the \b word boundary anchors make sure that the digits don't exceed 3 for each segment.

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

How to add property to object in PHP >= 5.3 strict mode without generating error

If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.

$data = json_decode($json, TRUE);

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

What are NDF Files?

An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.

How does Content Security Policy (CSP) work?

The Content-Security-Policy meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.

I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.

For brevity I won’t write the full tag in each sample. Instead I'll only show the content property, so a sample that says content="default-src 'self'" means this:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

1. How can I allow multiple sources?

You can simply list your sources after a directive as a space-separated list:

content="default-src 'self' https://example.com/js/"

Note that there are no quotes around parameters other than the special ones, like 'self'. Also, there's no colon (:) after the directive. Just the directive, then a space-separated list of parameters.

Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:

https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js

These, however, would not be valid:

http://example.com/js/file.js
^^^^ wrong protocol

https://example.com/file.js
                   ^^ above the specified path

2. How can I use different directives? What do they each do?

The most common directives are:

  • default-src the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc
  • script-src defines valid sources for javascript files
  • style-src defines valid sources for css files
  • img-src defines valid sources for images
  • connect-src defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400 error

There are others, but these are the ones you're most likely to need.

3. How can I use multiple directives?

You define all your directives inside one meta-tag by terminating them with a semicolon (;):

content="default-src 'self' https://example.com/js/; style-src 'self'"

4. How can I handle ports?

Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:

content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"

The above would result in:

https://ajax.googleapis.com:123
                           ^^^^ Not ok, wrong port

https://ajax.googleapis.com - OK

http://example.com/free/stuff/file.js
                 ^^ Not ok, only the port 123 is allowed

http://example.com:123/free/stuff/file.js - OK

As I mentioned, you can also use an asterisk to explicitly allow all ports:

content="default-src example.com:*"

5. How can I handle different protocols?

By default, only standard protocols are allowed. For example to allow WebSockets ws:// you will have to allow it explicitly:

content="default-src 'self'; connect-src ws:; style-src 'self'"
                                         ^^^ web Sockets are now allowed on all domains and ports.

6. How can I allow the file protocol file://?

If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem parameter:

content="default-src filesystem"

7. How can I use inline scripts and style definitions?

Unless explicitly allowed, you can't use inline style definitions, code inside <script> tags or in tag properties like onclick. You allow them like so:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

You'll also have to explicitly allow inline, base64 encoded images:

content="img-src data:"

8. How can I allow eval()?

I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:

content="script-src 'unsafe-eval'"

9. What exactly does 'self' mean?

You might take 'self' to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.

I've used 'self' in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.

But hang on a minute! Can't I just use content="default-src *" and be done with it?

No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

... but I trust you won’t.

Further reading:

http://content-security-policy.com

http://en.wikipedia.org/wiki/Content_Security_Policy

How to set an HTTP proxy in Python 2.7?

You can install pip (or any other package) with easy_install almost as described in the first answer. However you will need a HTTPS proxy, too. The full sequence of commands is:

set http_proxy=http://proxy.myproxy.com
set https_proxy=http://proxy.myproxy.com
easy_install pip

You might also want to add a port to the proxy, such as http{s}_proxy=http://proxy.myproxy.com:8080

Custom exception type

Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Rather than editing the webpack config file, the easier way to disable the host check is by adding a .env file to your root folder and putting this:

DANGEROUSLY_DISABLE_HOST_CHECK=true

As the variable name implies, disabling it is insecure and is only advisable to use only in dev environment.

Trying to detect browser close event

Have you tried this code?

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.

One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.

Set value of textarea in jQuery

Have you tried val?

$("textarea#ExampleMessage").val(result.exampleMessage);

Same Navigation Drawer in different Activities

Create Navigation drawer in your MainActivity using fragment.
Initialize the Navigation Drawer in MainActivity
now in all other activities you want to use same Navigation Drawer put DrawerLayout as base and fragment as navigation drawer. Just set android:name in your fragment pointing to your fragment Java file. You won't need to initialize the fragment in other Activities.
You can access Nav Drawer by swipe in other activities like in Google Play Store app

Difference between <? super T> and <? extends T> in Java

I love the answer from @Bert F but this is the way my brain sees it.

I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...

List<? super   X>

If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X

List<? extends X>

Hope this helps.

What's the fastest way to do a bulk insert into Postgres?

UNNEST function with arrays can be used along with multirow VALUES syntax. I'm think that this method is slower than using COPY but it is useful to me in work with psycopg and python (python list passed to cursor.execute becomes pg ARRAY):

INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
VALUES (
    UNNEST(ARRAY[1, 2, 3]), 
    UNNEST(ARRAY[100, 200, 300]), 
    UNNEST(ARRAY['a', 'b', 'c'])
);

without VALUES using subselect with additional existance check:

INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
SELECT * FROM (
    SELECT UNNEST(ARRAY[1, 2, 3]), 
           UNNEST(ARRAY[100, 200, 300]), 
           UNNEST(ARRAY['a', 'b', 'c'])
) AS temptable
WHERE NOT EXISTS (
    SELECT 1 FROM tablename tt
    WHERE tt.fieldname1=temptable.fieldname1
);

the same syntax to bulk updates:

UPDATE tablename
SET fieldname1=temptable.data
FROM (
    SELECT UNNEST(ARRAY[1,2]) AS id,
           UNNEST(ARRAY['a', 'b']) AS data
) AS temptable
WHERE tablename.id=temptable.id;

Can't import Numpy in Python

I was trying to import numpy in python 3.2.1 on windows 7.

Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it

cd numpy-1.6
python setup.py install

but got an error with a statement as below

unable to find vcvarsall.bat

For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.

In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"

Installation went smoothly and now I am able to import numpy without using mingW.

Long story short try using windows installer for numpy, if one is available.

multiple packages in context:component-scan, spring config

Another general Annotation approach:

@ComponentScan(basePackages = {"x.y.z"})

Where are the recorded macros stored in Notepad++?

You can find the shortcuts.xml in AppData\Roaming\Notepad++\ path only when using the default settings. If you have backup configured, you can find and set the path in Preferences -> Backup -> Backup path.

When these settings are applied, files in AppData directory won't be used.

Fastest way to implode an associative array with keys

echo implode(",", array_keys($companies->toArray()));

$companies->toArray() -- this is just in case if your $variable is an object, otherwise just pass $companies.

That's it!

Contains case insensitive

You can try this

_x000D_
_x000D_
str = "Wow its so COOL"_x000D_
searchStr = "CoOl"_x000D_
_x000D_
console.log(str.toLowerCase().includes(searchStr.toLowerCase()))
_x000D_
_x000D_
_x000D_

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

This still appears to be an issue, causing package installations to be aborted with warnings about optional packages no being installed because of "Unsupported platform".

The problem relates to the "shrinkwrap" or package-lock.json which gets persisted after every package manager execution. Subsequent attempts keep failing as this file is referenced instead of package.json.

Adding these options to the npm install command should allow packages to install again.

   --no-optional argument will prevent optional dependencies from being installed.

   --no-shrinkwrap argument, which will ignore an available package lock or
                   shrinkwrap file and use the package.json instead.

   --no-package-lock argument will prevent npm from creating a package-lock.json file.

The complete command looks like this:

    npm install --no-optional --no-shrinkwrap --no-package-lock

nJoy!

Quick Sort Vs Merge Sort

quicksort is named so for a reason ,

highlights : both are stable sorts,(simply an implementation nuisance ) , so lets just move on to complexities

its very confusing with just the big-oh notations being spilled and "abused" , both have average case complexity of 0(nlogn) ,

but merge sort is always 0(nlogn) , whereas quicksort for bad partitions, ie skewed partitions like 1 element-10 element (which can happen due to sorted or reverse sorted list ) can lead to a 0(n^2)..

.. and so we have randomized quicksort , where we pick the pivot randomly and avoid such skewed partitioning , thereby nullifying the whole n^2 scenario anyway even for moderately skewed partitioning like 3-4 , we have a nlog(7/4)n, ideally we want 1-1 partion , thus the whole 2 of O(nlog(2)n).

so it is O(nlogn) , almost always and unlike merge sort the constants hidden under the "big-oh" notation are better for quicksort than for mergesort ..and it doesnt use up extra space like merge sort.

but getting quicksort run perfectly requires tweaking ,rephrase , quicksort provides you opportunities to tweak ....

Radio button checked event handling

Try something like this:

$(function(){
  $('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      alert($(this).val());
    }
  });
});

If you give your radio buttons a class then you can replace the code $('input[type="radio"]') with $('.someclass').

jQuery - Dynamically Create Button and Attach Event Handler

You were just adding the html string. Not the element you created with a click event listener.

Try This:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
    <table id="addNodeTable">
        <tr>
            <td>
                Row 1
            </td>
        </tr>
        <tr >
            <td>
                Row 2
            </td>
        </tr>
    </table>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function() {
        var test = $('<button>Test</button>').click(function () {
            alert('hi');
        });
        $("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);

    });
</script>

How to change text and background color?

SetConsoleTextAttribute.

HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);

This would produce red text on a white background.

How to get the device's IMEI/ESN programmatically in android?

From: http://mytechead.wordpress.com/2011/08/28/how-to-get-imei-number-of-android-device/:

The following code helps in obtaining IMEI number of android devices :

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();

Permissions required in Android Manifest:

android.permission.READ_PHONE_STATE

NOTE: In case of tablets or devices which can’t act as Mobile Phone IMEI will be null.

How to read a text file into a string variable and strip newlines?

Maybe you could try this? I use this in my programs.

Data= open ('data.txt', 'r')
data = Data.readlines()
for i in range(len(data)):
    data[i] = data[i].strip()+ ' '
data = ''.join(data).strip()

Get value of input field inside an iframe

Yes it should be possible, even if the site is from another domain.

For example, in an HTML page on my site I have an iFrame whose contents are sourced from another website. The iFrame content is a single select field.

I need to be able to read the selected value on my site. In other words, I need to use the select list from another domain inside my own application. I do not have control over any server settings.

Initially therefore we might be tempted to do something like this (simplified):

HTML in my site:

<iframe name='select_frame' src='http://www.othersite.com/select.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>

HTML contents of iFrame (loaded from select.php on another domain):

<select id='select_name'>
    <option value='john'>John</option>
    <option value='jim' selected>Jim</option>
</select>

jQuery:

$('input:button[name=save]').click(function() {
    var name = $('iframe[name=select_frame]').contents().find('#select_name').val();
});

However, I receive this javascript error when I attempt to read the value:

Blocked a frame with origin "http://www.myownsite.com" from accessing a frame with origin "http://www.othersite.com". Protocols, domains, and ports must match.

To get around this problem, it seems that you can indirectly source the iFrame from a script in your own site, and have that script read the contents from the other site using a method like file_get_contents() or curl etc.

So, create a script (for example: select_local.php in the current directory) on your own site with contents similar to this:

PHP content of select_local.php:

<?php
    $url = "http://www.othersite.com/select.php?" . $_SERVER['QUERY_STRING'];
    $html_select = file_get_contents($url);
    echo $html_select;
?>

Also modify the HTML to call this local (instead of the remote) script:

<iframe name='select_frame' src='select_local.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>

Now your browser should think that it is loading the iFrame content from the same domain.

Boolean vs boolean in Java

Yes you can use Boolean/boolean instead.

First one is Object and second one is primitive type.

  • On first one, you will get more methods which will be useful.

  • Second one is cheap considering memory expense The second will save you a lot more memory, so go for it

Now choose your way.

HMAC-SHA256 Algorithm for signature calculation

Here is my solution:

public String HMAC_SHA256(String secret, String message)
{
    String hash="";
    try{
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        hash = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
    }catch (Exception e)
    {

    }
    return hash.trim();
}

MySQL: Insert record if not exists in table

I'm not actually suggesting that you do this, as the UNIQUE index as suggested by Piskvor and others is a far better way to do it, but you can actually do what you were attempting:

CREATE TABLE `table_listnames` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `tele` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

Insert a record:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

Try to insert the same record again:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

Insert a different record:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
|  2 | John   | Doe       | 022  |
+----+--------+-----------+------+

And so on...


Update:

To prevent #1060 - Duplicate column name error in case two values may equal, you must name the columns of the inner SELECT:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+---------+-----------+------+
| id | name    | address   | tele |
+----+---------+-----------+------+
|  1 | Rupert  | Somewhere | 022  |
|  2 | John    | Doe       | 022  |
|  3 | Unknown | Unknown   | 022  |
+----+---------+-----------+------+

How to calculate the number of occurrence of a given character in each row of a column of strings?

s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
p <- "a"
s2 <- gsub(p,"",s)
numOcc <- nchar(s) - nchar(s2)

May not be the efficient one but solve my purpose.

PHP - find entry by object property from an array of objects

YurkamTim is right. It needs only a modification:

After function($) you need a pointer to the external variable by "use(&$searchedValue)" and then you can access the external variable. Also you can modify it.

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use (&$searchedValue) {
        return $e->id == $searchedValue;
    }
);

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

ggplot with 2 y axes on each side and different scales

The technical backbone to the solution of this challenge has been provided by Kohske some 3 years ago [KOHSKE]. The topic and the technicalities around its solution have been discussed on several instances here on Stackoverflow [IDs: 18989001, 29235405, 21026598]. So i shall only provide a specific variation and some explanatory walkthrough, using above solutions.

Let us assume we do have some data y1 in group G1 to which some data y2 in group G2 is related in some way, e.g. range/scale transformed or with some noise added. So one wants to plot the data together on one plot with the scale of y1 on the left and y2 on the right.

  df <- data.frame(item=LETTERS[1:n],  y1=c(-0.8684, 4.2242, -0.3181, 0.5797, -0.4875), y2=c(-5.719, 205.184, 4.781, 41.952, 9.911 )) # made up!

> df
  item      y1         y2
1    A -0.8684 -19.154567
2    B  4.2242 219.092499
3    C -0.3181  18.849686
4    D  0.5797  46.945161
5    E -0.4875  -4.721973

If we now plot our data together with something like

ggplot(data=df, aes(label=item)) +
  theme_bw() + 
  geom_segment(aes(x='G1', xend='G2', y=y1, yend=y2), color='grey')+
  geom_text(aes(x='G1', y=y1), color='blue') +
  geom_text(aes(x='G2', y=y2), color='red') +
  theme(legend.position='none', panel.grid=element_blank())

it doesnt align nicely as the smaller scale y1 obviosuly gets collapsed by larger scale y2.

The trick here to meet the challenge is to techncially plot both data sets against the first scale y1 but report the second against a secondary axis with labels showing the original scale y2.

So we build a first helper function CalcFudgeAxis which calculates and collects features of the new axis to be shown. The function can be amended to ayones liking (this one just maps y2 onto the range of y1).

CalcFudgeAxis = function( y1, y2=y1) {
  Cast2To1 = function(x) ((ylim1[2]-ylim1[1])/(ylim2[2]-ylim2[1])*x) # x gets mapped to range of ylim2
  ylim1 <- c(min(y1),max(y1))
  ylim2 <- c(min(y2),max(y2))    
  yf <- Cast2To1(y2)
  labelsyf <- pretty(y2)  
  return(list(
    yf=yf,
    labels=labelsyf,
    breaks=Cast2To1(labelsyf)
  ))
}

what yields some:

> FudgeAxis <- CalcFudgeAxis( df$y1, df$y2 )

> FudgeAxis
$yf
[1] -0.4094344  4.6831656  0.4029175  1.0034664 -0.1009335

$labels
[1] -50   0  50 100 150 200 250

$breaks
[1] -1.068764  0.000000  1.068764  2.137529  3.206293  4.275058  5.343822


> cbind(df, FudgeAxis$yf)
  item      y1         y2 FudgeAxis$yf
1    A -0.8684 -19.154567   -0.4094344
2    B  4.2242 219.092499    4.6831656
3    C -0.3181  18.849686    0.4029175
4    D  0.5797  46.945161    1.0034664
5    E -0.4875  -4.721973   -0.1009335

Now I wraped Kohske's solution in the second helper function PlotWithFudgeAxis (into which we throw the ggplot object and helper object of the new axis):

library(gtable)
library(grid)

PlotWithFudgeAxis = function( plot1, FudgeAxis) {
  # based on: https://rpubs.com/kohske/dual_axis_in_ggplot2
  plot2 <- plot1 + with(FudgeAxis, scale_y_continuous( breaks=breaks, labels=labels))

  #extract gtable
  g1<-ggplot_gtable(ggplot_build(plot1))
  g2<-ggplot_gtable(ggplot_build(plot2))

  #overlap the panel of the 2nd plot on that of the 1st plot
  pp<-c(subset(g1$layout, name=="panel", se=t:r))
  g<-gtable_add_grob(g1, g2$grobs[[which(g2$layout$name=="panel")]], pp$t, pp$l, pp$b,pp$l)

  ia <- which(g2$layout$name == "axis-l")
  ga <- g2$grobs[[ia]]
  ax <- ga$children[[2]]
  ax$widths <- rev(ax$widths)
  ax$grobs <- rev(ax$grobs)
  ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
  g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
  g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

  grid.draw(g)
}

Now all can be put together: Below code shows, how the proposed solution could be used in a day-to-day environment. The plot call now doesnt plot the original data y2 anymore but a cloned version yf (held inside the pre-calculated helper object FudgeAxis), which runs of the scale of y1. The original ggplot objet is then manipulated with Kohske's helper function PlotWithFudgeAxis to add a second axis preserving the scales of y2. It plots as well the manipulated plot.

FudgeAxis <- CalcFudgeAxis( df$y1, df$y2 )

tmpPlot <- ggplot(data=df, aes(label=item)) +
      theme_bw() + 
      geom_segment(aes(x='G1', xend='G2', y=y1, yend=FudgeAxis$yf), color='grey')+
      geom_text(aes(x='G1', y=y1), color='blue') +
      geom_text(aes(x='G2', y=FudgeAxis$yf), color='red') +
      theme(legend.position='none', panel.grid=element_blank())

PlotWithFudgeAxis(tmpPlot, FudgeAxis)

This now plots as desired with two axis, y1 on the left and y2 on the right

2 axes

Above solution is, to put it straight, a limited shaky hack. As it plays with the ggplot kernel it will throw some warnings that we exchange post-the-fact scales, etc. It has to be handled with care and may produce some undesired behaviour in another setting. As well one may need to fiddle around with the helper functions to get the layout as desired. The placement of the legend is such an issue (it would be placed between the panel and the new axis; this is why I droped it). The scaling / alignment of the 2 axis is as well a bit challenging: The code above works nicely when both scales contain the "0", else one axis gets shifted. So definetly with some opportunities to improve...

In case on wants to save the pic one has to wrap the call into device open / close:

png(...)
PlotWithFudgeAxis(tmpPlot, FudgeAxis)
dev.off()

How to pass variable number of arguments to a PHP function

An old question, I know, however, none of the answers here really do a good job of simply answer the question.

I just played around with php and the solution looks like this:

function myFunction($requiredArgument, $optionalArgument = "default"){
   echo $requiredArgument . $optionalArgument;
}

This function can do two things:

If its called with only the required parameter: myFunction("Hi") It will print "Hi default"

But if it is called with the optional parameter: myFunction("Hi","me") It will print "Hi me";

I hope this helps anyone who is looking for this down the road.

Detect click outside element

I create a div at the end of the body like that:

<div v-if="isPopup" class="outside" v-on:click="away()"></div>

Where .outside is :

.outside {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0px;
  left: 0px;
}

And away() is a method in Vue instance :

away() {
 this.isPopup = false;
}

Easy, works well.

How to revert uncommitted changes including files and folders?

Git 2.23 introduced git restore command to restore working tree files.

https://git-scm.com/docs/git-restore

To restore all files in the current directory

git restore .

If you want to restore all C source files to match the version in the index, you can do

git restore '*.c'

Node.js/Express.js App Only Works on Port 3000

I think the best way is to use dotenv package and set the port on the .env config file without to modify the file www inside the folder bin.

Just install the package with the command:

npm install dotenv

require it on your application:

require('dotenv').config()

Create a .env file in the root directory of your project, and add the port in it (for example) to listen on port 5000

PORT=5000

and that's it.

More info here

Difference between require, include, require_once and include_once?

From the manual:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

The same is true for the _once() variants.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

async/await - when to return a Task vs void?

I have come across this very useful article about async and void written by Jérôme Laban: https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

The bottom line is that an async+void can crash the system and usually should be used only on the UI side event handlers.

The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.

When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How to save LogCat contents to file?

In addition to answer by Dinesh Prajapati, Use

 adb -d logcat <your package name>:<log level>

where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.

Now your command goes like:

adb -d logcat com.example.example:V > logfileName_WithPath.txt

Java using enum with switch statement

The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY

Google Maps JS API v3 - Simple Multiple Marker Example

Accepted answer, rewritten in ES6:

$(document).ready(() => {
  const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map');

  // Display a map on the page
  const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' });

  const buildings = [
    {
      title: 'London Eye, London', 
      coordinates: [51.503454, -0.119562],
      info: 'carousel'
    },
    {
      title: 'Palace of Westminster, London', 
      coordinates: [51.499633, -0.124755],
      info: 'palace'
    }
  ];

  placeBuildingsOnMap(buildings, map);
});


const placeBuildingsOnMap = (buildings, map) => {
  // Loop through our array of buildings & place each one on the map  
  const bounds = new google.maps.LatLngBounds();
  buildings.forEach((building) => {
    const position = { lat: building.coordinates[0], lng: building.coordinates[1] }
    // Stretch our bounds to the newly found marker position
    bounds.extend(position);

    const marker = new google.maps.Marker({
      position: position,
      map: map,
      title: building.title
    });

    const infoWindow = new google.maps.InfoWindow();
    // Allow each marker to have an info window
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(building.info);
      infoWindow.open(map, marker);
    })

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
  })
})

Run a single test method with maven

The test parameter mentioned by tobrien allows you to specify a method using a # before the method name. This should work for JUnit and TestNG. I've never tried it, just read it on the Surefire Plugin page:

Specify this parameter to run individual tests by file name, overriding the includes/excludes parameters. Each pattern you specify here will be used to create an include pattern formatted like **/${test}.java, so you can just type "-Dtest=MyTest" to run a single test called "foo/MyTest.java". This parameter overrides the includes/excludes parameters, and the TestNG suiteXmlFiles parameter. since 2.7.3 You can execute a limited number of method in the test with adding #myMethod or #my*ethod. Si type "-Dtest=MyTest#myMethod" supported for junit 4.x and testNg

Open file dialog box in JavaScript

Simple answer .

(1) Put input element type="file" anywhere on page and set attribute type="hidden" or style="display:none". Give an id to input element. e.g. id="myid"

(2) Chose any div, image, button or any element which you want to use to open file dialog box, set an onclick attribute to it, like this- onclick="document.getElementById('myid').click()"

That is all.

How to check if array is not empty?

len(self.table) checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):

Python 2:

if len(self.table) > 0:
    #Do code here

Python 3:

if(len(self.table) > 0):
    #Do code here

It's also possible to use

if self.table:
    #Execute if self.table is not empty
else:
    #Execute if self.table is empty

to see if the list is not empty.

Declaring static constants in ES6 classes?

Adding up to other answers you need to export the class to use in a different class. This is a typescript version of it.

_x000D_
_x000D_
//Constants.tsx
const DEBUG: boolean = true;

export class Constants {
  static get DEBUG(): boolean {
    return DEBUG;
  }
}

//Anotherclass.tsx
import { Constants } from "Constants";

if (Constants.DEBUG) {
  console.log("debug mode")
}
_x000D_
_x000D_
_x000D_

if A vs if A is not None:

Most guides I've seen suggest that you should use

if A:

unless you have a reason to be more specific.

There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.

Get type of a generic parameter in Java with reflection

You can get the type of a generic parameter with reflection like in this example that I found here:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Home<E> {
    @SuppressWarnings ("unchecked")
    public Class<E> getTypeParameterClass(){
        Type type = getClass().getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) type;
        return (Class<E>) paramType.getActualTypeArguments()[0];
    }

    private static class StringHome extends Home<String>{}
    private static class StringBuilderHome extends Home<StringBuilder>{}
    private static class StringBufferHome extends Home<StringBuffer>{}   

    /**
     * This prints "String", "StringBuilder" and "StringBuffer"
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Object object0 = new StringHome().getTypeParameterClass().newInstance();
        Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
        Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
        System.out.println(object0.getClass().getSimpleName());
        System.out.println(object1.getClass().getSimpleName());
        System.out.println(object2.getClass().getSimpleName());
    }
}

build maven project with propriatery libraries included

You could either add the jar to your project and mess around with the maven-assembly-plugin, or add the jar to your local repository:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
       <group-id>      the group that the file should be registered under
       <artifact-id>   the artifact name for the file
       <version>       the version of the file
       <packaging>     the packaging of the file e.g. jar

convert string array to string

Try:

String.Join("", test);

which should return a string joining the two elements together. "" indicates that you want the strings joined together without any separators.

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Accept function as parameter in PHP

Tested for PHP 5.3

As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php

What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.

The function to do check:

if( is_callable( $string_function_name ) ){
    /*perform the call*/
}

Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php

call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );

as it follows (in a similar, parameterless, way):

    function funToBeCalled(){
        print("----------------------i'm here");
    }
    function wrapCaller($fun){
        if( is_callable($fun)){
            print("called");
            call_user_func($fun);
        }else{
            print($fun." not called");
        }
    }

    wrapCaller("funToBeCalled");
    wrapCaller("cannot call me");

Here's a class explaining how to do something similar :

<?php
class HolderValuesOrFunctionsAsString{
    private $functions = array();
    private $vars = array();

    function __set($name,$data){
        if(is_callable($data))
            $this->functions[$name] = $data;
        else
            $this->vars[$name] = $data;
    }

    function __get($name){
        $t = $this->vars[$name];
        if(isset($t))
            return $t;
        else{
            $t = $this->$functions[$name];
            if( isset($t))
                return $t;
        }
    }

    function __call($method,$args=null){
        $fun = $this->functions[$method];
        if(isset($fun)){
            call_user_func_array($fun,$args);
        } else {
            // error out
            print("ERROR: Funciton not found: ". $method);
        }
    }
}
?>

and an example of usage

<?php
    /*create a sample function*/
    function sayHello($some = "all"){
    ?>
         <br>hello to <?=$some?><br>
    <?php
    }

    $obj = new HolderValuesOrFunctionsAsString;

    /*do the assignement*/
    $obj->justPrintSomething = 'sayHello'; /*note that the given
        "sayHello" it's a string ! */

    /*now call it*/
    $obj->justPrintSomething(); /*will print: "hello to all" and
        a break-line, for html purpose*/

    /*if the string assigned is not denoting a defined method
         , it's treat as a simple value*/
    $obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';

    echo $obj->justPrintSomething; /*what do you expect to print?
        just that string*/
    /*N.B.: "justPrintSomething" is treated as a variable now!
        as the __set 's override specify"*/

    /*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
     $obj->justPrintSomething("Jack Sparrow");


     /*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/

     $obj->justPrintSomething( $obj->justPrintSomething );
         /*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/

    /*in fact, "justPrintSomething" it's a name used to identify both
         a value (into the dictionary of values) or a function-name
         (into the dictionary of functions)*/
?>

How to compare times in Python?

Inspired by Roger Pate:

import datetime
def todayAt (hr, min=0, sec=0, micros=0):
   now = datetime.datetime.now()
   return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)    

# Usage demo1:
print todayAt (17), todayAt (17, 15)

# Usage demo2:    
timeNow = datetime.datetime.now()
if timeNow < todayAt (13):
   print "Too Early"

How to debug "ImagePullBackOff"?

I ran into this issue on GKE and the reason was no credentials for docker.

Running this resolved it:

gcloud auth configure-docker

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

Mounting multiple volumes on a docker container?

Or you can do

docker run -v /var/volume1 -v /var/volume2 DATA busybox true

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

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

Checking for a null int value from a Java ResultSet

I think, it is redundant. rs.getObject("ID_PARENT") should return an Integer object or null, if the column value actually was NULL. So it should even be possible to do something like:

if (rs.next()) {
  Integer idParent = (Integer) rs.getObject("ID_PARENT");
  if (idParent != null) {
    iVal = idParent; // works for Java 1.5+
  } else {
    // handle this case
  }      
}

IDENTITY_INSERT is set to OFF - How to turn it ON?

The Reference: http://technet.microsoft.com/en-us/library/aa259221%28v=sql.80%29.aspx

My table is named Genre with the 3 columns of Id, Name and SortOrder

The code that I used is as:

SET IDENTITY_INSERT Genre ON

INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

ASP.NET Core - Swashbuckle not creating swagger.json file

#if DEBUG
   // For Debug in Kestrel
   c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
#else
   // To deploy on IIS
   c.SwaggerEndpoint("/webapi/swagger/v1/swagger.json", "Web API V1");
#endif

When deployed to IIS webapi(base URL) is the Application Alias. You need to keep Application Alias(base URL) same for all IIS deployments because swagger looks for swagger.json at "/swagger/v1/swagger.json" location but wont prefix application Alias(base URL) that is the reason it wont work.

For Example:

localhost/swagger/v1/swagger.json - Couldn't find swagger.json

ALTER TABLE add constraint

Omit the parenthesis:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

Expand and collapse with angular js

I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.

Assign a boolean variable to ng-show and toggle it on click of header.

Check it out here enter image description here

jquery ajax function not working

I was having this issue and none of these answers were able to help me with the issue. For anyone else who happens to have the same problem, here is a possible solution that worked for me. Simply reformat the code to be the following:

$("#postcontent").submit(function(e) {
  $.ajax({
    type:"POST",
    url:"add_new_post.php",
    data:$("#postcontent").serialize(),
    beforeSend:function(){
      $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
    },
    success (response) {   
      //alert(response);
      $("#return_update_msg").html(response); 
      $(".post_submitting").fadeOut(1000);                
    },
    error (data) {
      // handle the error
    }
  });
});

The difference in the code is that this code has an error handler. You can choose to handle the error however you wish but it is best practice to have the error handler in case of an exception. Also, the formatting of the success and error functions within the ajax function are different. This is the only format for success/error that would work for me. Hope it helps!

what is Ljava.lang.String;@

[ stands for single dimension array
Ljava.lang.String stands for the string class (L followed by class/interface name)

Few Examples:

  1. Class.forName("[D") -> Array of primitive double
  2. Class.forName("[[Ljava.lang.String") -> Two dimensional array of strings.

List of notations:
Element Type : Notation
boolean : Z
byte : B
char : C
class or interface : Lclassname
double : D
float : F
int : I
long : J
short : S

How to allow only numeric (0-9) in HTML inputbox using jQuery?

You would want to allow tab:

$("#txtboxToFilter").keydown(function(event) {
    // Allow only backspace and delete
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
        // let it happen, don't do anything
    }
    else {
        // Ensure that it is a number and stop the keypress
        if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
            event.preventDefault(); 
        }   
    }
});

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

Sounds like myversioncontrol.com have added a pre-commit hook, or have one that is now failing. If it's a free account, it might be you've exceeded some sort of monthly commit or bandwidth limit. Check their terms of service and/or contact them to see what's up.

UPDATE:
I've just checked their website, and it looks like the free account is only valid for 30 days, so you might've exceeded that. You may need to pony up the £3.50pcm or find somewhere else (Google Code is one suggestion, though there are others).

Simon Groenewolt makes a good point that you may have changed something in the control panel on their website that has turned on a pre-commit hook but where it's configured incorrectly.

How to set up googleTest as a shared library on Linux

Update for Debian/Ubuntu

Google Mock (package: google-mock) and Google Test (package: libgtest-dev) have been merged. The new package is called googletest. Both old names are still available for backwards compatibility and now depend on the new package googletest.

So, to get your libraries from the package repository, you can do the following:

sudo apt-get install googletest -y
cd /usr/src/googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp googlemock/*.a googlemock/gtest/*.a /usr/lib

After that, you can link against -lgmock (or against -lgmock_main if you do not use a custom main method) and -lpthread. This was sufficient for using Google Test in my cases at least.

If you want the most current version of Google Test, download it from github. After that, the steps are similar:

git clone https://github.com/google/googletest
cd googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp lib/*.a /usr/lib

As you can see, the path where the libraries are created has changed. Keep in mind that the new path might be valid for the package repositories soon, too.

Instead of copying the libraries manually, you could use sudo make install. It "currently" works, but be aware that it did not always work in the past. Also, you don't have control over the target location when using this command and you might not want to pollute /usr/lib.

How could I convert data from string to long in c#

You can also use long.TryParse and long.Parse.

long l1;
l1 = long.Parse("1100.25");
//or
long.TryParse("1100.25", out l1);

Python: avoiding pylint warnings about too many arguments

Do you want a better way to pass the arguments or just a way to stop pylint from giving you a hard time? If the latter, I seem to recall that you could stop the nagging by putting pylint-controlling comments in your code along the lines of:

#pylint: disable=R0913

or, better:

#pylint: disable=too-many-arguments

remembering to turn them back on as soon as practicable.

In my opinion, there's nothing inherently wrong with passing a lot of arguments and solutions advocating wrapping them all up in some container argument don't really solve any problems, other than stopping pylint from nagging you :-).

If you need to pass twenty arguments, then pass them. It may be that this is required because your function is doing too much and a re-factoring could assist there, and that's something you should look at. But it's not a decision we can really make unless we see what the 'real' code is.

Programmatic equivalent of default(Type)

Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

How to solve Permission denied (publickey) error when using Git?

Are you in a corporate environment? Is it possible that your system variables have recently changed? Per this SO answer, ssh keys live at %HOMEDRIVE%%HOMEPATH%\.ssh\id_rsa.pub. So if %HOMEDRIVE% recently changed, git doesn't know where to look for your key, and thus all of the authentication stuff.

Try running ssh -vT [email protected]. Take note of where the identity file is located. For me, that was pointing not to my normal \Users\MyLogin but rather to a network drive, because of a change to environment variables pushed at the network level.

The solution? Since my new %HOMEDRIVE% has the same permissions as my local files, I just moved my .ssh folder there, and called it a day.

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, ie: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

Block Comments in a Shell Script

Another mode is: If your editor HAS NO BLOCK comment option,

  1. Open a second instance of the editor (for example File=>New File...)
  2. From THE PREVIOUS file you are working on, select ONLY THE PART YOU WANT COMMENT
  3. Copy and paste it in the window of the new temporary file...
  4. Open the Edit menu, select REPLACE and input as string to be replaced '\n'
  5. input as replace string: '\n#'
  6. press the button 'replace ALL'

DONE

it WORKS with ANY editor

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Configuring a working email client from localhost is quite a chore, I have spent hours of frustration attempting it. At last I have found this way to send mails (using WAMP, XAMPP, etc.):

Install hMailServer

Configure this hMailServer setting:

  1. Open hMailServer Administrator.
  2. Click the "Add domain ..." button to create a new domain.
  3. Under the domain text field, enter your computer's localhost IP.
    • Example: 127.0.0.1 is your localhost IP.
  4. Click the "Save" button.
  5. Now go to Settings > Protocols > SMTP and select the "Delivery of Email" tab.
  6. Find the localhost field enter "localhost".
  7. Click the Save button.

Configure your Gmail account, perform following modification:

  1. Go to Settings > Protocols > SMTP and select "Delivery of Email" tab.
  2. Enter "smtp.gmail.com" in the Remote Host name field.
  3. Enter "465" as the port number.
  4. Check "Server requires authentication".
  5. Enter your Google Mail address in the Username field.
  6. Enter your Google Mail password in the password field.
  7. Check mark "Use SSL"
  8. Save all changes.

Optional

If you want to send email from another computer you need to allow deliveries from External to External accounts by following steps:

  1. Go to Settings > Advanced > IP Ranges and double click on "My Computer" which should have IP address of 127.0.0.1
  2. Check the Allow Deliveries from External to External accounts Checkbox.
  3. Save settings using Save button.

How can I remove the string "\n" from within a Ruby string?

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

See here for more info

Counter increment in Bash loop not working

count=0   
base=1
(( count += base ))

What is a reasonable code coverage % for unit tests (and why)?

Code coverage is great, but functionality coverage is even better. I don't believe in covering every single line I write. But I do believe in writing 100% test coverage of all the functionality I want to provide (even for the extra cool features I came with myself and which were not discussed during the meetings).

I don't care if I would have code which is not covered in tests, but I would care if I would refactor my code and end up having a different behaviour. Therefore, 100% functionality coverage is my only target.

How to pass a value from one jsp to another jsp page?

Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'

<body>
<form action="display.jsp" method="post">
 <input type="hidden" name="u1" value="<%=u1%>"/>
 <input type="hidden" name="u2" value="<%=u2%>" />
 <input type="hidden" name="u3" value="<%=u3%>" />
 <button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
  <script type="text/javascript">
     document.getElementById("qq").click();
  </script>
</body>

// Code to be written in 'display.jsp'

 <% String u1 = request.getParameter("u1").toString();
    String u2 = request.getParameter("u2").toString();
    String u3 = request.getParameter("u3").toString();
 %>

If you want to use these variables of servlets in javascript then simply write

<script type="text/javascript">
 var a=<%=u1%>;
</script>

Hope it helps :)

Lambda function in list comprehensions

The first one

f = lambda x: x*x
[f(x) for x in range(10)]

runs f() for each value in the range so it does f(x) for each value

the second one

[lambda x: x*x for x in range(10)]

runs the lambda for each value in the list, so it generates all of those functions.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle module is:

# save data to a file
with open('myfile.pickle','wb') as fout:
    pickle.dump([1,2,3],fout)

# read data from a file
with open('myfile.pickle') as fin:
    print pickle.load(fin)

# output
>> [1, 2, 3]

If you dumped a list, you'll load a list, there's no need to load each item individually.

you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.

If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

makefile:4: *** missing separator. Stop

If you are using mcedit for makefile edit. you have to see the following mark. enter image description here

How to read values from the querystring with ASP.NET Core?

in .net core if you want to access querystring in our view use it like

@Context.Request.Query["yourKey"]

if we are in location where @Context is not avilable we can inject it like

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@if (HttpContextAccessor.HttpContext.Request.Query.Keys.Contains("yourKey"))
{
      <text>do something </text>
}

also for cookies

HttpContextAccessor.HttpContext.Request.Cookies["DeniedActions"]

How to make a hyperlink in telegram without using bots?

In telegram desktop, use this hotkey: ctrl+K

In android:

  1. type your text
  2. select it
  3. and click on Create Link from its options

You can see these steps in this image: link creation in telegram android

How can I detect when an Android application is running in the emulator?

All answers in one method

static boolean checkEmulator()
{
    try
    {
        String buildDetails = (Build.FINGERPRINT + Build.DEVICE + Build.MODEL + Build.BRAND + Build.PRODUCT + Build.MANUFACTURER + Build.HARDWARE).toLowerCase();

        if (buildDetails.contains("generic") 
        ||  buildDetails.contains("unknown") 
        ||  buildDetails.contains("emulator") 
        ||  buildDetails.contains("sdk") 
        ||  buildDetails.contains("genymotion") 
        ||  buildDetails.contains("x86") // this includes vbox86
        ||  buildDetails.contains("goldfish")
        ||  buildDetails.contains("test-keys"))
            return true;
    }   
    catch (Throwable t) {Logger.catchedError(t);}

    try
    {
        TelephonyManager    tm  = (TelephonyManager) App.context.getSystemService(Context.TELEPHONY_SERVICE);
        String              non = tm.getNetworkOperatorName().toLowerCase();
        if (non.equals("android"))
            return true;
    }
    catch (Throwable t) {Logger.catchedError(t);}

    try
    {
        if (new File ("/init.goldfish.rc").exists())
            return true;
    }
    catch (Throwable t) {Logger.catchedError(t);}

    return false;
}

Classes residing in App_Code is not accessible

I haven't figured out yet why this occurs, but I had classes that were in my App_Code folder that were calling methods in each other, and were fine in doing this when I built a .NET 4.5.2 project, but then I had to revert it to 4.0 as the target server wasn't getting upgraded. That's when I found this problem (after fixing the langversion in my web.config from 6 to 5... another story)....

One of my methods kept having an error like:

The type X.Y conflicts with the imported type X.Y in MyProject.DLL

All of my classes were already set to "Compile" in their properties, as suggested on the accepted answer here, and each had a common namespace that was the same, and each had using MyNamespace; at the top of each class.

I found that if I just moved the offending classes that had to call methods in each other to another, standard folder named something other than "App_Code", they stopped having this conflict issue.

Note: If you create a standard folder called "AppCode", move your classes into it, delete the "App_Code" folder, then rename "AppCode" to "App_Code", your problems will return. It doesn't matter if you use the "New Folder" or "Add ASP .NET Folder" option to create "App_Code" - it seems to key in on the name.

Maybe this is just a .NET 4.0 (and possibly earlier) issue... I was just fine in 4.5.2 before having to revert!

Send FormData with other field in AngularJS

Using $resource in AngularJS you can do:

task.service.js

$ngTask.factory("$taskService", [
    "$resource",
    function ($resource) {
        var taskModelUrl = 'api/task/';
        return {
            rest: {
                taskUpload: $resource(taskModelUrl, {
                    id: '@id'
                }, {
                    save: {
                        method: "POST",
                        isArray: false,
                        headers: {"Content-Type": undefined},
                        transformRequest: angular.identity
                    }
                })
            }
        };
    }
]);

And then use it in a module:

task.module.js

$ngModelTask.controller("taskController", [
    "$scope",
    "$taskService",
    function (
        $scope,
        $taskService,
    ) {
    $scope.saveTask = function (name, file) {
        var newTask,
            payload = new FormData();
        payload.append("name", name);
        payload.append("file", file);
        newTask = $taskService.rest.taskUpload.save(payload);
        // check if exists
    }
}